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"
56 #include "core/backup_type.hpp"
59 #include "newgrf_commons.h"
60 #include "misc/getoptdata.h"
61 #include "game/game.hpp"
62 #include "game/game_config.hpp"
64 #include "subsidy_func.h"
65 #include "gfx_layout.h"
66 #include "viewport_sprite_sorter.h"
67 #include "smallmap_gui.h"
68 #include "viewport_func.h"
69 #include "bridge_signal_map.h"
72 #include "linkgraph/linkgraphschedule.h"
73 #include "tracerestrict.h"
77 #include "safeguards.h"
79 void CallLandscapeTick();
81 void DoPaletteAnimations();
84 void CallWindowTickEvent();
85 bool HandleBootstrap();
87 extern Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
);
88 extern void ShowOSErrorBox(const char *buf
, bool system
);
89 extern char *_config_file
;
92 * Error handling for fatal user errors.
93 * @param s the string to print.
94 * @note Does NEVER return.
96 void CDECL
usererror(const char *s
, ...)
102 vseprintf(buf
, lastof(buf
), s
, va
);
105 ShowOSErrorBox(buf
, false);
106 if (VideoDriver::GetInstance() != NULL
) VideoDriver::GetInstance()->Stop();
112 * Error handling for fatal non-user errors.
113 * @param s the string to print.
114 * @note Does NEVER return.
116 void CDECL
error(const char *s
, ...)
122 vseprintf(buf
, lastof(buf
), s
, va
);
125 ShowOSErrorBox(buf
, true);
127 /* Set the error message for the crash log and then invoke it. */
128 CrashLog::SetErrorMessage(buf
);
132 void CDECL
assert_msg_error(int line
, const char *file
, const char *expr
, const char *str
, ...)
138 b
+= seprintf(b
, lastof(buf
), "Assertion failed at line %i of %s: %s\n\t", line
, file
, expr
);
141 vseprintf(b
, lastof(buf
), str
, va
);
144 ShowOSErrorBox(buf
, true);
146 /* Set the error message for the crash log and then invoke it. */
147 CrashLog::SetErrorMessage(buf
);
152 * Shows some information on the console/a popup box depending on the OS.
153 * @param str the text to show.
155 void CDECL
ShowInfoF(const char *str
, ...)
160 vseprintf(buf
, lastof(buf
), str
, va
);
166 * Show the help message when someone passed a wrong parameter.
168 static void ShowHelp()
173 p
+= seprintf(p
, lastof(buf
), "OpenTTD %s\n", _openttd_revision
);
177 "Command line options:\n"
178 " -v drv = Set video driver (see below)\n"
179 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
180 " -m drv = Set music driver (see below)\n"
181 " -b drv = Set the blitter to use (see below)\n"
182 " -r res = Set resolution (for instance 800x600)\n"
183 " -h = Display this help text\n"
184 " -t year = Set starting year\n"
185 " -d [[fac=]lvl[,...]]= Debug mode\n"
186 " -e = Start Editor\n"
187 " -g [savegame] = Start new/save game immediately\n"
188 " -G seed = Set random seed\n"
189 #if defined(ENABLE_NETWORK)
190 " -n [ip:port#company]= Join network game\n"
191 " -p password = Password to join server\n"
192 " -P password = Password to join company\n"
193 " -D [ip][:port] = Start dedicated server\n"
194 " -l ip[:port] = Redirect DEBUG()\n"
195 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
196 " -f = Fork into the background (dedicated only)\n"
198 #endif /* ENABLE_NETWORK */
199 " -I graphics_set = Force the graphics set (see below)\n"
200 " -S sounds_set = Force the sounds set (see below)\n"
201 " -M music_set = Force the music set (see below)\n"
202 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
203 " -x = Do not automatically save to config file on exit\n"
204 " -q savegame = Write some information about the savegame and exit\n"
209 /* List the graphics packs */
210 p
= BaseGraphics::GetSetsList(p
, lastof(buf
));
212 /* List the sounds packs */
213 p
= BaseSounds::GetSetsList(p
, lastof(buf
));
215 /* List the music packs */
216 p
= BaseMusic::GetSetsList(p
, lastof(buf
));
218 /* List the drivers */
219 p
= DriverFactoryBase::GetDriversInfo(p
, lastof(buf
));
221 /* List the blitters */
222 p
= BlitterFactory::GetBlittersInfo(p
, lastof(buf
));
224 /* List the debug facilities. */
225 p
= DumpDebugFacilityNames(p
, lastof(buf
));
227 /* We need to initialize the AI, so it finds the AIs */
229 p
= AI::GetConsoleList(p
, lastof(buf
), true);
230 AI::Uninitialize(true);
232 /* We need to initialize the GameScript, so it finds the GSs */
234 p
= Game::GetConsoleList(p
, lastof(buf
), true);
235 Game::Uninitialize(true);
237 /* ShowInfo put output to stderr, but version information should go
238 * to stdout; this is the only exception */
239 #if !defined(WIN32) && !defined(WIN64)
246 static void WriteSavegameInfo(const char *name
)
248 extern uint16 _sl_version
;
249 uint32 last_ottd_rev
= 0;
250 byte ever_modified
= 0;
251 bool removed_newgrfs
= false;
253 GamelogInfo(_load_check_data
.gamelog_action
, _load_check_data
.gamelog_actions
, &last_ottd_rev
, &ever_modified
, &removed_newgrfs
);
257 p
+= seprintf(p
, lastof(buf
), "Name: %s\n", name
);
258 p
+= seprintf(p
, lastof(buf
), "Savegame ver: %d\n", _sl_version
);
259 p
+= seprintf(p
, lastof(buf
), "NewGRF ver: 0x%08X\n", last_ottd_rev
);
260 p
+= seprintf(p
, lastof(buf
), "Modified: %d\n", ever_modified
);
262 if (removed_newgrfs
) {
263 p
+= seprintf(p
, lastof(buf
), "NewGRFs have been removed\n");
266 p
= strecpy(p
, "NewGRFs:\n", lastof(buf
));
267 if (_load_check_data
.HasNewGrfs()) {
268 for (GRFConfig
*c
= _load_check_data
.grfconfig
; c
!= NULL
; c
= c
->next
) {
270 md5sumToString(md5sum
, lastof(md5sum
), HasBit(c
->flags
, GCF_COMPATIBLE
) ? c
->original_md5sum
: c
->ident
.md5sum
);
271 p
+= seprintf(p
, lastof(buf
), "%08X %s %s\n", c
->ident
.grfid
, md5sum
, c
->filename
);
275 /* ShowInfo put output to stderr, but version information should go
276 * to stdout; this is the only exception */
277 #if !defined(WIN32) && !defined(WIN64)
286 * Extract the resolution from the given string and store
287 * it in the 'res' parameter.
288 * @param res variable to store the resolution in.
289 * @param s the string to decompose.
291 static void ParseResolution(Dimension
*res
, const char *s
)
293 const char *t
= strchr(s
, 'x');
295 ShowInfoF("Invalid resolution '%s'", s
);
299 res
->width
= max(strtoul(s
, NULL
, 0), 64UL);
300 res
->height
= max(strtoul(t
+ 1, NULL
, 0), 64UL);
305 * Unitializes drivers, frees allocated memory, cleans pools, ...
306 * Generally, prepares the game for shutting down
308 static void ShutdownGame()
312 if (_network_available
) NetworkShutDown(); // Shut down the network and close any open connections
314 DriverFactoryBase::ShutdownDrivers();
316 UnInitWindowSystem();
318 /* stop the scripts */
319 AI::Uninitialize(false);
320 Game::Uninitialize(false);
322 /* Uninitialize variables that are allocated dynamically */
325 #ifdef ENABLE_NETWORK
329 LinkGraphSchedule::Clear();
330 ClearBridgeSimulatedSignalMapping();
331 ClearTraceRestrictMapping();
332 PoolBase::Clean(PT_ALL
);
336 /* No NewGRFs were loaded when it was still bootstrapping. */
337 if (_game_mode
!= GM_BOOTSTRAP
) ResetNewGRFData();
339 /* Close all and any open filehandles */
346 ViewportMapClearTunnelCache();
350 * Load the introduction game.
351 * @param load_newgrfs Whether to load the NewGRFs or not.
353 static void LoadIntroGame(bool load_newgrfs
= true)
355 _game_mode
= GM_MENU
;
357 if (load_newgrfs
) ResetGRFConfig(false);
359 /* Setup main window */
361 SetupColoursAndInitialWindow();
363 /* Load the default opening screen savegame */
364 if (SaveOrLoad("opntitle.dat", SLO_LOAD
, DFT_GAME_FILE
, BASESET_DIR
) != SL_OK
) {
365 GenerateWorld(GWM_EMPTY
, 64, 64); // if failed loading, make empty world.
366 WaitTillGeneratedWorld();
367 SetLocalCompany(COMPANY_SPECTATOR
);
369 SetLocalCompany(COMPANY_FIRST
);
372 _pause_mode
= PM_UNPAUSED
;
373 _cursor
.fix_at
= false;
375 CheckForMissingGlyphs();
377 /* Play main theme */
378 if (MusicDriver::GetInstance()->IsSongPlaying()) ResetMusic();
381 void MakeNewgameSettingsLive()
383 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
384 if (_settings_game
.ai_config
[c
] != NULL
) {
385 delete _settings_game
.ai_config
[c
];
388 if (_settings_game
.game_config
!= NULL
) {
389 delete _settings_game
.game_config
;
392 /* Copy newgame settings to active settings.
393 * Also initialise old settings needed for savegame conversion. */
394 _settings_game
= _settings_newgame
;
395 _old_vds
= _settings_client
.company
.vehicle
;
397 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
398 _settings_game
.ai_config
[c
] = NULL
;
399 if (_settings_newgame
.ai_config
[c
] != NULL
) {
400 _settings_game
.ai_config
[c
] = new AIConfig(_settings_newgame
.ai_config
[c
]);
403 _settings_game
.game_config
= NULL
;
404 if (_settings_newgame
.game_config
!= NULL
) {
405 _settings_game
.game_config
= new GameConfig(_settings_newgame
.game_config
);
409 void OpenBrowser(const char *url
)
411 /* Make sure we only accept urls that are sure to open a browser. */
412 if (strstr(url
, "http://") != url
&& strstr(url
, "https://") != url
) return;
414 extern void OSOpenBrowser(const char *url
);
418 /** Callback structure of statements to be executed after the NewGRF scan. */
419 struct AfterNewGRFScan
: NewGRFScanCallback
{
420 Year startyear
; ///< The start year.
421 uint generation_seed
; ///< Seed for the new game.
422 char *dedicated_host
; ///< Hostname for the dedicated server.
423 uint16 dedicated_port
; ///< Port for the dedicated server.
424 char *network_conn
; ///< Information about the server to connect to, or NULL.
425 const char *join_server_password
; ///< The password to join the server with.
426 const char *join_company_password
; ///< The password to join the company with.
427 bool *save_config_ptr
; ///< The pointer to the save config setting.
428 bool save_config
; ///< The save config setting.
431 * Create a new callback.
432 * @param save_config_ptr Pointer to the save_config local variable which
433 * decides whether to save of exit or not.
435 AfterNewGRFScan(bool *save_config_ptr
) :
436 startyear(INVALID_YEAR
), generation_seed(GENERATE_NEW_SEED
),
437 dedicated_host(NULL
), dedicated_port(0), network_conn(NULL
),
438 join_server_password(NULL
), join_company_password(NULL
),
439 save_config_ptr(save_config_ptr
), save_config(true)
443 virtual void OnNewGRFsScanned()
445 ResetGRFConfig(false);
447 TarScanner::DoScan(TarScanner::SCENARIO
);
452 /* We want the new (correct) NewGRF count to survive the loading. */
453 uint last_newgrf_count
= _settings_client
.gui
.last_newgrf_count
;
455 _settings_client
.gui
.last_newgrf_count
= last_newgrf_count
;
456 /* Since the default for the palette might have changed due to
457 * reading the configuration file, recalculate that now. */
458 UpdateNewGRFConfigPalette();
460 Game::Uninitialize(true);
461 AI::Uninitialize(true);
464 LoadHotkeysFromConfig();
465 WindowDesc::LoadFromConfig();
467 /* We have loaded the config, so we may possibly save it. */
468 *save_config_ptr
= save_config
;
470 /* restore saved music volume */
471 MusicDriver::GetInstance()->SetVolume(_settings_client
.music
.music_vol
);
473 if (startyear
!= INVALID_YEAR
) _settings_newgame
.game_creation
.starting_year
= startyear
;
474 if (generation_seed
!= GENERATE_NEW_SEED
) _settings_newgame
.game_creation
.generation_seed
= generation_seed
;
476 #if defined(ENABLE_NETWORK)
477 if (dedicated_host
!= NULL
) {
478 _network_bind_list
.Clear();
479 *_network_bind_list
.Append() = stredup(dedicated_host
);
481 if (dedicated_port
!= 0) _settings_client
.network
.server_port
= dedicated_port
;
482 #endif /* ENABLE_NETWORK */
484 /* initialize the ingame console */
487 IConsoleCmdExec("exec scripts/autoexec.scr 0");
489 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
490 if (_switch_mode
!= SM_NONE
) MakeNewgameSettingsLive();
492 #ifdef ENABLE_NETWORK
493 if (_network_available
&& network_conn
!= NULL
) {
494 const char *port
= NULL
;
495 const char *company
= NULL
;
496 uint16 rport
= NETWORK_DEFAULT_PORT
;
497 CompanyID join_as
= COMPANY_NEW_COMPANY
;
499 ParseConnectionString(&company
, &port
, network_conn
);
501 if (company
!= NULL
) {
502 join_as
= (CompanyID
)atoi(company
);
504 if (join_as
!= COMPANY_SPECTATOR
) {
506 if (join_as
>= MAX_COMPANIES
) {
512 if (port
!= NULL
) rport
= atoi(port
);
515 _switch_mode
= SM_NONE
;
516 NetworkClientConnectGame(NetworkAddress(network_conn
, rport
), join_as
, join_server_password
, join_company_password
);
518 #endif /* ENABLE_NETWORK */
520 /* After the scan we're not used anymore. */
525 #if defined(UNIX) && !defined(__MORPHOS__)
526 extern void DedicatedFork();
529 /** Options of OpenTTD. */
530 static const OptionData _options
[] = {
531 GETOPT_SHORT_VALUE('I'),
532 GETOPT_SHORT_VALUE('S'),
533 GETOPT_SHORT_VALUE('M'),
534 GETOPT_SHORT_VALUE('m'),
535 GETOPT_SHORT_VALUE('s'),
536 GETOPT_SHORT_VALUE('v'),
537 GETOPT_SHORT_VALUE('b'),
538 #if defined(ENABLE_NETWORK)
539 GETOPT_SHORT_OPTVAL('D'),
540 GETOPT_SHORT_OPTVAL('n'),
541 GETOPT_SHORT_VALUE('l'),
542 GETOPT_SHORT_VALUE('p'),
543 GETOPT_SHORT_VALUE('P'),
544 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
545 GETOPT_SHORT_NOVAL('f'),
547 #endif /* ENABLE_NETWORK */
548 GETOPT_SHORT_VALUE('r'),
549 GETOPT_SHORT_VALUE('t'),
550 GETOPT_SHORT_OPTVAL('d'),
551 GETOPT_SHORT_NOVAL('e'),
552 GETOPT_SHORT_OPTVAL('g'),
553 GETOPT_SHORT_VALUE('G'),
554 GETOPT_SHORT_VALUE('c'),
555 GETOPT_SHORT_NOVAL('x'),
556 GETOPT_SHORT_VALUE('q'),
557 GETOPT_SHORT_NOVAL('h'),
562 * Main entry point for this lovely game.
563 * @param argc The number of arguments passed to this game.
564 * @param argv The values of the arguments.
565 * @return 0 when there is no error.
567 int openttd_main(int argc
, char *argv
[])
569 char *musicdriver
= NULL
;
570 char *sounddriver
= NULL
;
571 char *videodriver
= NULL
;
572 char *blitter
= NULL
;
573 char *graphics_set
= NULL
;
574 char *sounds_set
= NULL
;
575 char *music_set
= NULL
;
576 Dimension resolution
= {0, 0};
577 /* AfterNewGRFScan sets save_config to true after scanning completed. */
578 bool save_config
= false;
579 AfterNewGRFScan
*scanner
= new AfterNewGRFScan(&save_config
);
580 #if defined(ENABLE_NETWORK)
581 bool dedicated
= false;
582 char *debuglog_conn
= NULL
;
584 extern bool _dedicated_forks
;
585 _dedicated_forks
= false;
586 #endif /* ENABLE_NETWORK */
588 _game_mode
= GM_MENU
;
589 _switch_mode
= SM_MENU
;
592 GetOptData
mgo(argc
- 1, argv
+ 1, _options
);
596 while ((i
= mgo
.GetOpt()) != -1) {
598 case 'I': free(graphics_set
); graphics_set
= stredup(mgo
.opt
); break;
599 case 'S': free(sounds_set
); sounds_set
= stredup(mgo
.opt
); break;
600 case 'M': free(music_set
); music_set
= stredup(mgo
.opt
); break;
601 case 'm': free(musicdriver
); musicdriver
= stredup(mgo
.opt
); break;
602 case 's': free(sounddriver
); sounddriver
= stredup(mgo
.opt
); break;
603 case 'v': free(videodriver
); videodriver
= stredup(mgo
.opt
); break;
604 case 'b': free(blitter
); blitter
= stredup(mgo
.opt
); break;
605 #if defined(ENABLE_NETWORK)
611 musicdriver
= stredup("null");
612 sounddriver
= stredup("null");
613 videodriver
= stredup("dedicated");
614 blitter
= stredup("null");
616 SetDebugString("net=6");
617 if (mgo
.opt
!= NULL
) {
618 /* Use the existing method for parsing (openttd -n).
619 * However, we do ignore the #company part. */
620 const char *temp
= NULL
;
621 const char *port
= NULL
;
622 ParseConnectionString(&temp
, &port
, mgo
.opt
);
623 if (!StrEmpty(mgo
.opt
)) scanner
->dedicated_host
= mgo
.opt
;
624 if (port
!= NULL
) scanner
->dedicated_port
= atoi(port
);
627 case 'f': _dedicated_forks
= true; break;
629 scanner
->network_conn
= mgo
.opt
; // optional IP parameter, NULL if unset
632 debuglog_conn
= mgo
.opt
;
635 scanner
->join_server_password
= mgo
.opt
;
638 scanner
->join_company_password
= mgo
.opt
;
640 #endif /* ENABLE_NETWORK */
641 case 'r': ParseResolution(&resolution
, mgo
.opt
); break;
642 case 't': scanner
->startyear
= atoi(mgo
.opt
); break;
647 if (mgo
.opt
!= NULL
) SetDebugString(mgo
.opt
);
650 case 'e': _switch_mode
= (_switch_mode
== SM_LOAD_GAME
|| _switch_mode
== SM_LOAD_SCENARIO
? SM_LOAD_SCENARIO
: SM_EDITOR
); break;
652 if (mgo
.opt
!= NULL
) {
653 _file_to_saveload
.SetName(mgo
.opt
);
654 bool is_scenario
= _switch_mode
== SM_EDITOR
|| _switch_mode
== SM_LOAD_SCENARIO
;
655 _switch_mode
= is_scenario
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
;
656 _file_to_saveload
.SetMode(SLO_LOAD
, is_scenario
? FT_SCENARIO
: FT_SAVEGAME
, DFT_GAME_FILE
);
658 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
659 const char *t
= strrchr(_file_to_saveload
.name
, '.');
661 FiosType ft
= FiosGetSavegameListCallback(SLO_LOAD
, _file_to_saveload
.name
, t
, NULL
, NULL
);
662 if (ft
!= FIOS_TYPE_INVALID
) _file_to_saveload
.SetMode(ft
);
668 _switch_mode
= SM_NEWGAME
;
669 /* Give a random map if no seed has been given */
670 if (scanner
->generation_seed
== GENERATE_NEW_SEED
) {
671 scanner
->generation_seed
= InteractiveRandom();
675 DeterminePaths(argv
[0]);
676 if (StrEmpty(mgo
.opt
)) {
678 goto exit_noshutdown
;
683 FiosGetSavegameListCallback(SLO_LOAD
, mgo
.opt
, strrchr(mgo
.opt
, '.'), title
, lastof(title
));
685 _load_check_data
.Clear();
686 SaveOrLoadResult res
= SaveOrLoad(mgo
.opt
, SLO_CHECK
, DFT_GAME_FILE
, SAVE_DIR
, false);
687 if (res
!= SL_OK
|| _load_check_data
.HasErrors()) {
688 fprintf(stderr
, "Failed to open savegame\n");
689 if (_load_check_data
.HasErrors()) {
691 SetDParamStr(0, _load_check_data
.error_data
);
692 GetString(buf
, _load_check_data
.error
, lastof(buf
));
693 fprintf(stderr
, "%s\n", buf
);
695 goto exit_noshutdown
;
698 WriteSavegameInfo(title
);
700 goto exit_noshutdown
;
702 case 'G': scanner
->generation_seed
= atoi(mgo
.opt
); break;
703 case 'c': free(_config_file
); _config_file
= stredup(mgo
.opt
); break;
704 case 'x': scanner
->save_config
= false; break;
706 i
= -2; // Force printing of help.
712 if (i
== -2 || mgo
.numleft
> 0) {
713 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
714 * In all cases, print the help, and exit.
716 * The next two functions are needed to list the graphics sets. We can't do them earlier
717 * because then we cannot show it on the debug console as that hasn't been configured yet. */
718 DeterminePaths(argv
[0]);
719 TarScanner::DoScan(TarScanner::BASESET
);
720 BaseGraphics::FindSets();
721 BaseSounds::FindSets();
722 BaseMusic::FindSets();
725 goto exit_noshutdown
;
728 #if defined(WINCE) && defined(_DEBUG)
729 /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
733 DeterminePaths(argv
[0]);
734 TarScanner::DoScan(TarScanner::BASESET
);
736 #if defined(ENABLE_NETWORK)
737 if (dedicated
) DEBUG(net
, 0, "Starting dedicated version %s", _openttd_revision
);
738 if (_dedicated_forks
&& !dedicated
) _dedicated_forks
= false;
740 #if defined(UNIX) && !defined(__MORPHOS__)
741 /* We must fork here, or we'll end up without some resources we need (like sockets) */
742 if (_dedicated_forks
) DedicatedFork();
746 LoadFromConfig(true);
748 if (resolution
.width
!= 0) _cur_resolution
= resolution
;
751 * The width and height must be at least 1 pixel and width times
752 * height times bytes per pixel must still fit within a 32 bits
753 * integer, even for 32 bpp video modes. This way all internal
754 * drawing routines work correctly.
756 _cur_resolution
.width
= ClampU(_cur_resolution
.width
, 1, UINT16_MAX
/ 2);
757 _cur_resolution
.height
= ClampU(_cur_resolution
.height
, 1, UINT16_MAX
/ 2);
759 /* Assume the cursor starts within the game as not all video drivers
760 * get an event that the cursor is within the window when it is opened.
761 * Saying the cursor is there makes no visible difference as it would
762 * just be out of the bounds of the window. */
763 _cursor
.in_window
= true;
765 /* enumerate language files */
766 InitializeLanguagePacks();
768 /* Initialize the regular font for FreeType */
771 /* This must be done early, since functions use the SetWindowDirty* calls */
774 BaseGraphics::FindSets();
775 if (graphics_set
== NULL
&& BaseGraphics::ini_set
!= NULL
) graphics_set
= stredup(BaseGraphics::ini_set
);
776 if (!BaseGraphics::SetSet(graphics_set
)) {
777 if (!StrEmpty(graphics_set
)) {
778 BaseGraphics::SetSet(NULL
);
780 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND
);
781 msg
.SetDParamStr(0, graphics_set
);
782 ScheduleErrorMessage(msg
);
787 /* Initialize game palette */
790 DEBUG(misc
, 1, "Loading blitter...");
791 if (blitter
== NULL
&& _ini_blitter
!= NULL
) blitter
= stredup(_ini_blitter
);
792 _blitter_autodetected
= StrEmpty(blitter
);
793 /* Activate the initial blitter.
794 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
795 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
796 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
797 * - Use 8bpp blitter otherwise.
799 if (!_blitter_autodetected
||
800 (_support8bpp
!= S8BPP_NONE
&& (BaseGraphics::GetUsedSet() == NULL
|| BaseGraphics::GetUsedSet()->blitter
== BLT_8BPP
)) ||
801 BlitterFactory::SelectBlitter("32bpp-anim") == NULL
) {
802 if (BlitterFactory::SelectBlitter(blitter
) == NULL
) {
804 usererror("Failed to autoprobe blitter") :
805 usererror("Failed to select requested blitter '%s'; does it exist?", blitter
);
810 if (videodriver
== NULL
&& _ini_videodriver
!= NULL
) videodriver
= stredup(_ini_videodriver
);
811 DriverFactoryBase::SelectDriver(videodriver
, Driver::DT_VIDEO
);
814 InitializeSpriteSorter();
816 /* Initialize the zoom level of the screen to normal */
817 _screen
.zoom
= ZOOM_LVL_NORMAL
;
819 NetworkStartUp(); // initialize network-core
821 #if defined(ENABLE_NETWORK)
822 if (debuglog_conn
!= NULL
&& _network_available
) {
823 const char *not_used
= NULL
;
824 const char *port
= NULL
;
827 rport
= NETWORK_DEFAULT_DEBUGLOG_PORT
;
829 ParseConnectionString(¬_used
, &port
, debuglog_conn
);
830 if (port
!= NULL
) rport
= atoi(port
);
832 NetworkStartDebugLog(NetworkAddress(debuglog_conn
, rport
));
834 #endif /* ENABLE_NETWORK */
836 if (!HandleBootstrap()) {
842 VideoDriver::GetInstance()->ClaimMousePointer();
844 /* initialize screenshot formats */
845 InitializeScreenshotFormats();
847 BaseSounds::FindSets();
848 if (sounds_set
== NULL
&& BaseSounds::ini_set
!= NULL
) sounds_set
= stredup(BaseSounds::ini_set
);
849 if (!BaseSounds::SetSet(sounds_set
)) {
850 if (StrEmpty(sounds_set
) || !BaseSounds::SetSet(NULL
)) {
851 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
853 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND
);
854 msg
.SetDParamStr(0, sounds_set
);
855 ScheduleErrorMessage(msg
);
860 BaseMusic::FindSets();
861 if (music_set
== NULL
&& BaseMusic::ini_set
!= NULL
) music_set
= stredup(BaseMusic::ini_set
);
862 if (!BaseMusic::SetSet(music_set
)) {
863 if (StrEmpty(music_set
) || !BaseMusic::SetSet(NULL
)) {
864 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
866 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND
);
867 msg
.SetDParamStr(0, music_set
);
868 ScheduleErrorMessage(msg
);
873 if (sounddriver
== NULL
&& _ini_sounddriver
!= NULL
) sounddriver
= stredup(_ini_sounddriver
);
874 DriverFactoryBase::SelectDriver(sounddriver
, Driver::DT_SOUND
);
877 if (musicdriver
== NULL
&& _ini_musicdriver
!= NULL
) musicdriver
= stredup(_ini_musicdriver
);
878 DriverFactoryBase::SelectDriver(musicdriver
, Driver::DT_MUSIC
);
881 /* Take our initial lock on whatever we might want to do! */
882 _modal_progress_paint_mutex
->BeginCritical();
883 _modal_progress_work_mutex
->BeginCritical();
885 GenerateWorld(GWM_EMPTY
, 64, 64); // Make the viewport initialization happy
886 WaitTillGeneratedWorld();
888 LoadIntroGame(false);
890 CheckForMissingGlyphs();
892 /* ScanNewGRFFiles now has control over the scanner. */
893 ScanNewGRFFiles(scanner
);
896 VideoDriver::GetInstance()->MainLoop();
900 /* only save config if we have to */
903 SaveHotkeysToConfig();
904 WindowDesc::SaveToConfig();
908 /* Reset windowing system, stop drivers, free used memory, ... */
913 /* These three are normally freed before bootstrap. */
919 /* These are normally freed before exit, but after bootstrap. */
926 free(BaseGraphics::ini_set
);
927 free(BaseSounds::ini_set
);
928 free(BaseMusic::ini_set
);
930 free(_ini_musicdriver
);
931 free(_ini_sounddriver
);
932 free(_ini_videodriver
);
937 #ifdef ENABLE_NETWORK
938 extern FILE *_log_fd
;
939 if (_log_fd
!= NULL
) {
942 #endif /* ENABLE_NETWORK */
947 void HandleExitGameRequest()
949 if (_game_mode
== GM_MENU
|| _game_mode
== GM_BOOTSTRAP
) { // do not ask to quit on the main screen
951 } else if (_settings_client
.gui
.autosave_on_exit
) {
959 static void MakeNewGameDone()
961 SettingsDisableElrail(_settings_game
.vehicle
.disable_elrails
);
963 extern void PostCheckNewGRFLoadWarnings();
964 PostCheckNewGRFLoadWarnings();
966 /* In a dedicated server, the server does not play */
967 if (!VideoDriver::GetInstance()->HasGUI()) {
968 SetLocalCompany(COMPANY_SPECTATOR
);
969 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
970 IConsoleCmdExec("exec scripts/game_start.scr 0");
974 /* Create a single company */
975 DoStartupNewCompany(false);
977 Company
*c
= Company::Get(COMPANY_FIRST
);
978 c
->settings
= _settings_client
.company
;
980 IConsoleCmdExec("exec scripts/game_start.scr 0");
982 SetLocalCompany(COMPANY_FIRST
);
986 #ifdef ENABLE_NETWORK
987 /* We are the server, we start a new company (not dedicated),
988 * so set the default password *if* needed. */
989 if (_network_server
&& !StrEmpty(_settings_client
.network
.default_company_pass
)) {
990 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
992 #endif /* ENABLE_NETWORK */
994 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
998 MarkWholeScreenDirty();
1001 static void MakeNewGame(bool from_heightmap
, bool reset_settings
)
1003 _game_mode
= GM_NORMAL
;
1005 ResetGRFConfig(true);
1007 GenerateWorldSetCallback(&MakeNewGameDone
);
1008 GenerateWorld(from_heightmap
? GWM_HEIGHTMAP
: GWM_NEWGAME
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
, reset_settings
);
1011 static void MakeNewEditorWorldDone()
1013 SetLocalCompany(OWNER_NONE
);
1015 extern void PostCheckNewGRFLoadWarnings();
1016 PostCheckNewGRFLoadWarnings();
1019 static void MakeNewEditorWorld()
1021 _game_mode
= GM_EDITOR
;
1023 ResetGRFConfig(true);
1025 GenerateWorldSetCallback(&MakeNewEditorWorldDone
);
1026 GenerateWorld(GWM_EMPTY
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1030 * Load the specified savegame but on error do different things.
1031 * If loading fails due to corrupt savegame, bad version, etc. go back to
1032 * a previous correct state. In the menu for example load the intro game again.
1033 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1034 * @param newgm switch to this mode of loading fails due to some unknown error
1035 * @param filename file to be loaded
1036 * @param subdir default directory to look for filename, set to 0 if not needed
1037 * @param lf Load filter to use, if NULL: use filename + subdir.
1039 bool SafeLoad(const char *filename
, SaveLoadOperation fop
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= NULL
)
1041 assert(fop
== SLO_LOAD
);
1042 assert(dft
== DFT_GAME_FILE
|| (lf
== NULL
&& dft
== DFT_OLD_GAME_FILE
));
1043 GameMode ogm
= _game_mode
;
1047 switch (lf
== NULL
? SaveOrLoad(filename
, fop
, dft
, subdir
) : LoadWithFilter(lf
)) {
1048 case SL_OK
: return true;
1051 #ifdef ENABLE_NETWORK
1052 if (_network_dedicated
) {
1054 * We need to reinit a network map...
1055 * We can't simply load the intro game here as that game has many
1056 * special cases which make clients desync immediately. So we fall
1057 * back to just generating a new game with the current settings.
1059 DEBUG(net
, 0, "Loading game failed, so a new (random) game will be started!");
1060 MakeNewGame(false, true);
1063 if (_network_server
) {
1064 /* We can't load the intro game as server, so disconnect first. */
1065 NetworkDisconnect();
1067 #endif /* ENABLE_NETWORK */
1071 case GM_MENU
: LoadIntroGame(); break;
1072 case GM_EDITOR
: MakeNewEditorWorld(); break;
1082 void SwitchToMode(SwitchMode new_mode
)
1084 #ifdef ENABLE_NETWORK
1085 /* If we are saving something, the network stays in his current state */
1086 if (new_mode
!= SM_SAVE_GAME
) {
1087 /* If the network is active, make it not-active */
1089 if (_network_server
&& (new_mode
== SM_LOAD_GAME
|| new_mode
== SM_NEWGAME
|| new_mode
== SM_RESTARTGAME
)) {
1092 NetworkDisconnect();
1096 /* If we are a server, we restart the server */
1097 if (_is_network_server
) {
1098 /* But not if we are going to the menu */
1099 if (new_mode
!= SM_MENU
) {
1100 /* check if we should reload the config */
1101 if (_settings_client
.network
.reload_cfg
) {
1103 MakeNewgameSettingsLive();
1104 ResetGRFConfig(false);
1106 NetworkServerStart();
1108 /* This client no longer wants to be a network-server */
1109 _is_network_server
= false;
1113 #endif /* ENABLE_NETWORK */
1114 /* Make sure all AI controllers are gone at quitting game */
1115 if (new_mode
!= SM_SAVE_GAME
) AI::KillAll();
1118 case SM_EDITOR
: // Switch to scenario editor
1119 MakeNewEditorWorld();
1122 case SM_RESTARTGAME
: // Restart --> 'Random game' with current settings
1123 case SM_NEWGAME
: // New Game --> 'Random game'
1124 #ifdef ENABLE_NETWORK
1125 if (_network_server
) {
1126 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "Random Map");
1128 #endif /* ENABLE_NETWORK */
1129 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1132 case SM_LOAD_GAME
: { // Load game, Play Scenario
1133 ResetGRFConfig(true);
1134 ResetWindowSystem();
1136 if (!SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_NORMAL
, NO_DIRECTORY
)) {
1137 SetDParamStr(0, GetSaveLoadErrorString());
1138 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1140 if (_file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1141 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1142 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1144 /* Update the local company for a loaded game. It is either always
1145 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1146 SetLocalCompany(_network_dedicated
? COMPANY_SPECTATOR
: COMPANY_FIRST
);
1148 if (_ctrl_pressed
&& !_network_dedicated
) {
1149 DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
1152 /* Execute the game-start script */
1153 IConsoleCmdExec("exec scripts/game_start.scr 0");
1154 /* Decrease pause counter (was increased from opening load dialog) */
1155 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1156 #ifdef ENABLE_NETWORK
1157 if (_network_server
) {
1158 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Loaded game)", _file_to_saveload
.title
);
1160 #endif /* ENABLE_NETWORK */
1165 case SM_START_HEIGHTMAP
: // Load a heightmap and start a new game from it
1166 #ifdef ENABLE_NETWORK
1167 if (_network_server
) {
1168 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Heightmap)", _file_to_saveload
.title
);
1170 #endif /* ENABLE_NETWORK */
1171 MakeNewGame(true, true);
1174 case SM_LOAD_HEIGHTMAP
: // Load heightmap from scenario editor
1175 SetLocalCompany(OWNER_NONE
);
1177 GenerateWorld(GWM_HEIGHTMAP
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1178 MarkWholeScreenDirty();
1181 case SM_LOAD_SCENARIO
: { // Load scenario from scenario editor
1182 if (SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_EDITOR
, NO_DIRECTORY
)) {
1183 SetLocalCompany(OWNER_NONE
);
1184 _settings_newgame
.game_creation
.starting_year
= _cur_year
;
1185 /* Cancel the saveload pausing */
1186 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1188 SetDParamStr(0, GetSaveLoadErrorString());
1189 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1194 case SM_MENU
: // Switch to game intro menu
1196 if (BaseSounds::ini_set
== NULL
&& BaseSounds::GetUsedSet()->fallback
) {
1197 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET
, INVALID_STRING_ID
, WL_CRITICAL
);
1198 BaseSounds::ini_set
= stredup(BaseSounds::GetUsedSet()->name
);
1202 case SM_SAVE_GAME
: // Save game.
1203 /* Make network saved games on pause compatible to singleplayer */
1204 if (SaveOrLoad(_file_to_saveload
.name
, SLO_SAVE
, DFT_GAME_FILE
, NO_DIRECTORY
) != SL_OK
) {
1205 SetDParamStr(0, GetSaveLoadErrorString());
1206 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1208 DeleteWindowById(WC_SAVELOAD
, 0);
1212 case SM_SAVE_HEIGHTMAP
: // Save heightmap.
1213 MakeHeightmapScreenshot(_file_to_saveload
.name
);
1214 DeleteWindowById(WC_SAVELOAD
, 0);
1217 case SM_GENRANDLAND
: // Generate random land within scenario editor
1218 SetLocalCompany(OWNER_NONE
);
1219 GenerateWorld(GWM_RANDOM
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1221 MarkWholeScreenDirty();
1224 default: NOT_REACHED();
1227 SmallMapWindow::RebuildColourIndexIfNecessary();
1232 * Check the validity of some of the caches.
1233 * Especially in the sense of desyncs between
1234 * the cached value and what the value would
1235 * be when calculated from the 'base' data.
1237 void CheckCaches(bool force_check
)
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;
1245 /* Check the town caches. */
1246 SmallVector
<TownCache
, 4> old_town_caches
;
1249 MemCpyT(old_town_caches
.Append(), &t
->cache
);
1252 extern void RebuildTownCaches();
1253 RebuildTownCaches();
1254 RebuildSubsidisedSourceAndDestinationCache();
1258 if (MemCmpT(old_town_caches
.Get(i
), &t
->cache
) != 0) {
1259 DEBUG(desync
, 2, "town cache mismatch: town %i", (int)t
->index
);
1264 /* Check company infrastructure cache. */
1265 SmallVector
<CompanyInfrastructure
, 4> old_infrastructure
;
1267 FOR_ALL_COMPANIES(c
) MemCpyT(old_infrastructure
.Append(), &c
->infrastructure
);
1269 extern void AfterLoadCompanyStats();
1270 AfterLoadCompanyStats();
1273 FOR_ALL_COMPANIES(c
) {
1274 if (MemCmpT(old_infrastructure
.Get(i
), &c
->infrastructure
) != 0) {
1275 DEBUG(desync
, 2, "infrastructure cache mismatch: company %i", (int)c
->index
);
1277 old_infrastructure
.Get(i
)->Dump(buffer
, lastof(buffer
));
1278 DEBUG(desync
, 0, "Previous:\n%s", buffer
);
1279 c
->infrastructure
.Dump(buffer
, lastof(buffer
));
1280 DEBUG(desync
, 0, "Recalculated:\n%s", buffer
);
1285 /* Strict checking of the road stop cache entries */
1287 FOR_ALL_ROADSTOPS(rs
) {
1288 if (IsStandardRoadStopTile(rs
->xy
)) continue;
1290 assert(rs
->GetEntry(DIAGDIR_NE
) != rs
->GetEntry(DIAGDIR_NW
));
1291 rs
->GetEntry(DIAGDIR_NE
)->CheckIntegrity(rs
);
1292 rs
->GetEntry(DIAGDIR_NW
)->CheckIntegrity(rs
);
1296 FOR_ALL_VEHICLES(v
) {
1297 extern void FillNewGRFVehicleCache(const Vehicle
*v
);
1298 if (v
!= v
->First() || v
->vehstatus
& VS_CRASHED
|| !v
->IsPrimaryVehicle()) continue;
1301 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) length
++;
1303 NewGRFCache
*grf_cache
= CallocT
<NewGRFCache
>(length
);
1304 VehicleCache
*veh_cache
= CallocT
<VehicleCache
>(length
);
1305 GroundVehicleCache
*gro_cache
= CallocT
<GroundVehicleCache
>(length
);
1306 TrainCache
*tra_cache
= CallocT
<TrainCache
>(length
);
1309 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1310 FillNewGRFVehicleCache(u
);
1311 grf_cache
[length
] = u
->grf_cache
;
1312 veh_cache
[length
] = u
->vcache
;
1315 gro_cache
[length
] = Train::From(u
)->gcache
;
1316 tra_cache
[length
] = Train::From(u
)->tcache
;
1319 gro_cache
[length
] = RoadVehicle::From(u
)->gcache
;
1328 case VEH_TRAIN
: Train::From(v
)->ConsistChanged(CCF_TRACK
); break;
1329 case VEH_ROAD
: RoadVehUpdateCache(RoadVehicle::From(v
)); break;
1330 case VEH_AIRCRAFT
: UpdateAircraftCache(Aircraft::From(v
)); break;
1331 case VEH_SHIP
: Ship::From(v
)->UpdateCache(); break;
1336 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1337 FillNewGRFVehicleCache(u
);
1338 if (memcmp(&grf_cache
[length
], &u
->grf_cache
, sizeof(NewGRFCache
)) != 0) {
1339 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
);
1341 if (memcmp(&veh_cache
[length
], &u
->vcache
, sizeof(VehicleCache
)) != 0) {
1342 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
);
1346 if (memcmp(&gro_cache
[length
], &Train::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1347 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
);
1349 if (memcmp(&tra_cache
[length
], &Train::From(u
)->tcache
, sizeof(TrainCache
)) != 0) {
1350 DEBUG(desync
, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1354 if (memcmp(&gro_cache
[length
], &RoadVehicle::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1355 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
);
1370 /* Check whether the caches are still valid */
1371 FOR_ALL_VEHICLES(v
) {
1372 byte buff
[sizeof(VehicleCargoList
)];
1373 memcpy(buff
, &v
->cargo
, sizeof(VehicleCargoList
));
1374 v
->cargo
.InvalidateCache();
1375 assert(memcmp(&v
->cargo
, buff
, sizeof(VehicleCargoList
)) == 0);
1379 FOR_ALL_STATIONS(st
) {
1380 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
1381 byte buff
[sizeof(StationCargoList
)];
1382 memcpy(buff
, &st
->goods
[c
].cargo
, sizeof(StationCargoList
));
1383 st
->goods
[c
].cargo
.InvalidateCache();
1384 assert(memcmp(&st
->goods
[c
].cargo
, buff
, sizeof(StationCargoList
)) == 0);
1390 * Network-safe forced desync check.
1391 * @param tile unused
1392 * @param flags operation to perform
1395 * @param text unused
1396 * @return the cost of this operation or an error
1398 CommandCost
CmdDesyncCheck(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1400 if (flags
& DC_EXEC
) {
1404 return CommandCost();
1408 * State controlling game loop.
1409 * The state must not be changed from anywhere but here.
1410 * That check is enforced in DoCommand.
1412 void StateGameLoop()
1414 if (!_networking
|| _network_server
) {
1415 extern void StateGameLoop_LinkGraphPauseControl();
1416 StateGameLoop_LinkGraphPauseControl();
1419 /* don't execute the state loop during pause */
1420 if (_pause_mode
!= PM_UNPAUSED
) {
1421 UpdateLandscapingLimits();
1422 #ifndef DEBUG_DUMP_COMMANDS
1425 CallWindowTickEvent();
1428 if (HasModalProgress()) return;
1430 Layouter::ReduceLineCache();
1432 if (_game_mode
== GM_EDITOR
) {
1433 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1436 CallLandscapeTick();
1437 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1438 UpdateLandscapingLimits();
1440 CallWindowTickEvent();
1443 if (_debug_desync_level
> 2 && _date_fract
== 0 && (_date
& 0x1F) == 0) {
1444 /* Save the desync savegame if needed. */
1445 char name
[MAX_PATH
];
1446 seprintf(name
, lastof(name
), "dmp_cmds_%08x_%08x.sav", _settings_game
.game_creation
.generation_seed
, _date
);
1447 SaveOrLoad(name
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
, false);
1452 /* All these actions has to be done from OWNER_NONE
1453 * for multiplayer compatibility */
1454 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
1456 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1457 AnimateAnimatedTiles();
1461 CallLandscapeTick();
1462 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1464 #ifndef DEBUG_DUMP_COMMANDS
1468 UpdateLandscapingLimits();
1470 CallWindowTickEvent();
1472 cur_company
.Restore();
1475 assert(IsLocalCompany());
1479 * Create an autosave. The default name is "autosave#.sav". However with
1480 * the setting 'keep_all_autosave' the name defaults to company-name + date
1482 static void DoAutosave()
1487 /* Autosaving in networking is too time expensive for the PSP */
1488 if (_networking
) return;
1491 if (_settings_client
.gui
.keep_all_autosave
) {
1492 GenerateDefaultSaveName(buf
, lastof(buf
));
1493 strecat(buf
, ".sav", lastof(buf
));
1495 static int _autosave_ctr
= 0;
1497 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1498 seprintf(buf
, lastof(buf
), "autosave%d.sav", _autosave_ctr
);
1500 if (++_autosave_ctr
>= _settings_client
.gui
.max_num_autosaves
) _autosave_ctr
= 0;
1503 DEBUG(sl
, 2, "Autosaving to '%s'", buf
);
1504 if (SaveOrLoad(buf
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
) != SL_OK
) {
1505 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
1511 if (_game_mode
== GM_BOOTSTRAP
) {
1512 #ifdef ENABLE_NETWORK
1513 /* Check for UDP stuff */
1514 if (_network_available
) NetworkBackgroundLoop();
1520 ProcessAsyncSaveFinish();
1522 /* autosave game? */
1525 _do_autosave
= false;
1526 SetWindowDirty(WC_STATUS_BAR
, 0);
1529 /* switch game mode? */
1530 if (_switch_mode
!= SM_NONE
&& !HasModalProgress()) {
1531 SwitchToMode(_switch_mode
);
1532 _switch_mode
= SM_NONE
;
1535 IncreaseSpriteLRU();
1536 InteractiveRandom();
1538 extern int _caret_timer
;
1542 #ifdef ENABLE_NETWORK
1543 /* Check for UDP stuff */
1544 if (_network_available
) NetworkBackgroundLoop();
1546 if (_networking
&& !HasModalProgress()) {
1550 if (_network_reconnect
> 0 && --_network_reconnect
== 0) {
1551 /* This means that we want to reconnect to the last host
1552 * We do this here, because it means that the network is really closed */
1553 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), COMPANY_SPECTATOR
);
1559 /* Check chat messages roughly once a second. */
1560 static uint check_message
= 0;
1561 if (++check_message
> 1000 / MILLISECONDS_PER_TICK
) {
1563 NetworkChatMessageLoop();
1567 #endif /* ENABLE_NETWORK */
1569 if (!_pause_mode
&& HasBit(_display_opt
, DO_FULL_ANIMATION
)) DoPaletteAnimations();
1571 if (!_pause_mode
|| _game_mode
== GM_EDITOR
|| _settings_game
.construction
.command_pause_level
> CMDPL_NO_CONSTRUCTION
) MoveAllTextEffects();
1575 SoundDriver::GetInstance()->MainLoop();