Go to the documentation of this file.
83 #include <system_error>
88 # include <emscripten.h>
89 # include <emscripten/html5.h>
92 void CallLandscapeTick();
93 void DoPaletteAnimations();
100 extern void OSOpenBrowser(
const std::string &url);
102 extern void ShowOSErrorBox(
const char *buf,
bool system);
105 bool _save_config =
false;
106 bool _request_newgrf_scan =
false;
116 ShowOSErrorBox(str.c_str(),
false);
119 #ifdef __EMSCRIPTEN__
120 emscripten_exit_pointerlock();
124 EM_ASM(
if (window[
"openttd_abort"]) openttd_abort());
138 ShowOSErrorBox(str.c_str(),
true);
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"
220 fmt::print(
"{}\n", str);
226 static void WriteSavegameInfo(
const std::string &
name)
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";
249 fmt::format_to(std::back_inserter(message),
"{:08X} {} {}\n",
BSWAP32(c->ident.grfid),
257 fmt::print(
"{}\n", message);
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);
320 _game_mode = GM_MENU;
345 void MakeNewgameSettingsLive()
373 void OpenBrowser(
const std::string &url)
376 if (url.starts_with(
"http://") || url.starts_with(
"https://")) {
478 extern void DedicatedFork();
523 std::string musicdriver;
524 std::string sounddriver;
525 std::string videodriver;
527 std::string graphics_set;
528 std::string sounds_set;
529 std::string music_set;
532 bool dedicated =
false;
533 bool only_local_path =
false;
535 extern bool _dedicated_forks;
536 _dedicated_forks =
false;
538 _game_mode = GM_MENU;
545 while ((i = mgo.
GetOpt()) != -1) {
547 case 'I': graphics_set = mgo.
opt;
break;
548 case 'S': sounds_set = mgo.
opt;
break;
549 case 'M': music_set = mgo.
opt;
break;
550 case 'm': musicdriver = mgo.
opt;
break;
551 case 's': sounddriver = mgo.
opt;
break;
552 case 'v': videodriver = mgo.
opt;
break;
553 case 'b': blitter = mgo.
opt;
break;
555 musicdriver =
"null";
556 sounddriver =
"null";
557 videodriver =
"dedicated";
561 if (mgo.
opt !=
nullptr) {
565 case 'f': _dedicated_forks =
true;
break;
567 scanner->connection_string = mgo.
opt;
570 scanner->join_server_password = mgo.
opt;
573 scanner->join_company_password = mgo.
opt;
576 case 't': scanner->startyear = atoi(mgo.
opt);
break;
594 if (mgo.
opt !=
nullptr) {
599 if (ft == FIOS_TYPE_INVALID) {
602 if (ft == FIOS_TYPE_INVALID) {
621 scanner->generation_seed = InteractiveRandom();
637 fmt::print(stderr,
"Failed to open savegame\n");
646 WriteSavegameInfo(title);
654 case 'G': scanner->generation_seed = std::strtoul(mgo.
opt,
nullptr, 10);
break;
656 case 'x': scanner->save_config =
false;
break;
657 case 'X': only_local_path =
true;
break;
665 if (i == -2 || mgo.
numleft > 0) {
683 if (dedicated)
Debug(net, 3,
"Starting dedicated server, version {}", _openttd_revision);
684 if (_dedicated_forks && !dedicated) _dedicated_forks =
false;
688 if (_dedicated_forks) DedicatedFork();
718 bool valid_graphics_set;
719 if (!graphics_set.empty()) {
721 }
else if (BaseGraphics::ini_data.shortname != 0) {
722 graphics_set = BaseGraphics::ini_data.name;
724 if (valid_graphics_set && !BaseGraphics::ini_data.extra_params.empty()) {
727 extra_cfg.SetParams(BaseGraphics::ini_data.extra_params);
730 }
else if (!BaseGraphics::ini_data.name.empty()) {
731 graphics_set = BaseGraphics::ini_data.name;
734 valid_graphics_set =
true;
737 if (!valid_graphics_set) {
740 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
748 Debug(misc, 1,
"Loading blitter...");
762 UserError(
"Failed to autoprobe blitter") :
763 UserError(
"Failed to select requested blitter '{}'; does it exist?", blitter);
795 UserError(
"Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
797 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
807 UserError(
"Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
809 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
835 void HandleExitGameRequest()
837 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) {
878 static void MakeNewGameDone()
932 static void MakeNewGame(
bool from_heightmap,
bool reset_settings)
934 _game_mode = GM_NORMAL;
935 if (!from_heightmap) {
946 static void MakeNewEditorWorldDone()
951 static void MakeNewEditorWorld()
953 _game_mode = GM_EDITOR;
982 if (result ==
SL_OK)
return true;
991 Debug(net, 0,
"Loading requested map failed; closing server.");
1010 Debug(net, 0,
"Loading game failed, so a new (random) game will be started");
1011 MakeNewGame(
false,
true);
1023 case GM_EDITOR: MakeNewEditorWorld();
break;
1028 static void UpdateSocialIntegration(
GameMode game_mode)
1030 switch (game_mode) {
1070 MakeNewgameSettingsLive();
1073 NetworkServerStart();
1098 MakeNewEditorWorld();
1101 UpdateSocialIntegration(GM_EDITOR);
1120 UpdateSocialIntegration(GM_NORMAL);
1128 UpdateSocialIntegration(GM_NORMAL);
1147 UpdateSocialIntegration(GM_NORMAL);
1156 UpdateSocialIntegration(GM_NORMAL);
1162 _game_mode = GM_EDITOR;
1168 UpdateSocialIntegration(GM_EDITOR);
1183 UpdateSocialIntegration(GM_EDITOR);
1202 static bool asked_once =
false;
1209 UpdateSocialIntegration(GM_MENU);
1234 default: NOT_REACHED();
1249 if (_debug_desync_level <= 1)
return;
1252 std::vector<TownCache> old_town_caches;
1254 old_town_caches.push_back(t->cache);
1262 if (
MemCmpT(old_town_caches.data() + i, &t->cache) != 0) {
1263 Debug(desync, 2,
"warning: town cache mismatch: town {}", t->index);
1269 std::vector<CompanyInfrastructure> old_infrastructure;
1277 Debug(desync, 2,
"warning: infrastructure cache mismatch: company {}", c->
index);
1287 rs->GetEntry(
DIAGDIR_NE)->CheckIntegrity(rs);
1288 rs->GetEntry(
DIAGDIR_NW)->CheckIntegrity(rs);
1292 if (v != v->First() || v->vehstatus &
VS_CRASHED || !v->IsPrimaryVehicle())
continue;
1295 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) length++;
1297 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1298 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1300 TrainCache *tra_cache = CallocT<TrainCache>(length);
1303 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) {
1305 grf_cache[length] = u->grf_cache;
1306 veh_cache[length] = u->vcache;
1330 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) {
1332 if (memcmp(&grf_cache[length], &u->grf_cache,
sizeof(
NewGRFCache)) != 0) {
1333 Debug(desync, 2,
"warning: newgrf cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->type, v->index, v->owner, v->unitnumber, length);
1335 if (memcmp(&veh_cache[length], &u->vcache,
sizeof(
VehicleCache)) != 0) {
1336 Debug(desync, 2,
"warning: vehicle cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->type, v->index, v->owner, v->unitnumber, length);
1341 Debug(desync, 2,
"warning: train ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1344 Debug(desync, 2,
"warning: train cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1349 Debug(desync, 2,
"warning: road vehicle ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1368 v->cargo.InvalidateCache();
1373 std::vector<StationList> old_town_stations_near;
1374 for (
Town *t :
Town::Iterate()) old_town_stations_near.push_back(t->stations_near);
1376 std::vector<StationList> old_industry_stations_near;
1389 std::map<TileIndex, bool> docking_tiles;
1390 for (
TileIndex tile : st->docking_station) {
1394 UpdateStationDockingTiles(st);
1395 if (ta.
tile != st->docking_station.tile || ta.
w != st->docking_station.w || ta.
h != st->docking_station.h) {
1396 Debug(desync, 2,
"warning: station docking mismatch: station {}, company {}", st->index, st->owner);
1400 Debug(desync, 2,
"warning: docking tile mismatch: tile {}", tile);
1405 IndustryList industries_near = st->industries_near;
1406 st->RecomputeCatchment();
1407 if (st->industries_near != industries_near) {
1408 Debug(desync, 2,
"warning: station industries near mismatch: station {}", st->index);
1415 if (t->stations_near != old_town_stations_near[i]) {
1416 Debug(desync, 2,
"warning: town stations near mismatch: town {}", t->index);
1422 if (ind->stations_near != old_industry_stations_near[i]) {
1423 Debug(desync, 2,
"warning: industry stations near mismatch: industry {}", ind->index);
1451 #ifndef DEBUG_DUMP_COMMANDS
1462 if (_game_mode == GM_EDITOR) {
1466 CallLandscapeTick();
1494 CallLandscapeTick();
1497 #ifndef DEBUG_DUMP_COMMANDS
1555 if (_request_newgrf_scan)
return false;
1557 _request_newgrf_scan =
true;
1558 _request_newgrf_scan_callback = callback;
1564 if (_game_mode == GM_BOOTSTRAP) {
1570 if (_request_newgrf_scan) {
1572 _request_newgrf_scan =
false;
1573 _request_newgrf_scan_callback =
nullptr;
1575 if (_exit_game)
return;
1580 if (_game_mode == GM_NORMAL) {
1581 static auto last_time = std::chrono::steady_clock::now();
1582 auto now = std::chrono::steady_clock::now();
1583 auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time);
1584 if (delta_ms.count() != 0) {
1594 if (_exit_game)
return;
1597 IncreaseSpriteLRU();
@ VEH_AIRCRAFT
Aircraft vehicle type.
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
@ WC_SAVELOAD
Saveload window; Window numbers:
int openttd_main(int argc, char *argv[])
Main entry point for this lovely game.
bool save_config
The save config setting.
static void Clear()
Clear all link graphs and jobs from the schedule.
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
TimerGameCalendar::Year startyear
The start year.
void DeterminePaths(const char *exe, bool only_local_path)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir,...
static void ShutdownDrivers()
Shuts down all active drivers.
SwitchMode
Mode which defines what mode we're switching to.
void CheckEngines()
Check for engines that have an appropriate availability.
std::string FormatArrayAsHex(std::span< const byte > data)
Format a byte array into a continuous hex string.
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
class AIConfig * ai_config[MAX_COMPANIES]
settings per company
@ FT_SCENARIO
old or new scenario
static Titem * Get(size_t index)
Returns Titem with given index.
void SettingsDisableElrail(int32_t new_value)
_settings_game.disable_elrail callback
std::string error_msg
Data to pass to SetDParamStr when displaying error.
@ SAVE_DIR
Base directory for all savegames.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
void ShowNetworkAskSurvey()
Show a modal confirmation window with "no" / "preview" / "yes" buttons.
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
@ SM_LOAD_GAME
Load game, Play Scenario.
Dimensions (a width and height) of a rectangle in 2D.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
void SetDParamStr(uint n, const char *str)
Set a rawstring parameter.
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
std::string join_server_password
The password to join the server with.
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
std::string _config_file
Configuration file of OpenTTD.
Class to backup a specific variable and restore it later.
static constexpr TimerGame< struct Calendar >::Year INVALID_YEAR
Representation of an invalid year.
Vehicle * Next() const
Get the next vehicle of this vehicle.
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?...
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
Gamelog _gamelog
Gamelog instance.
static IntervalTimer< TimerGameRealtime > _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE}, [](auto) { _pause_mode &=~PM_COMMAND_DURING_PAUSE;_do_autosave=true;SetWindowDirty(WC_STATUS_BAR, 0);static FiosNumberedSaveName _autosave_ctr("autosave");DoAutoOrNetsave(_autosave_ctr);_do_autosave=false;SetWindowDirty(WC_STATUS_BAR, 0);})
Interval for regular autosaves.
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
virtual void SetVolume(byte vol)=0
Set the volume, if possible.
virtual void MainLoop()
Called once every tick.
@ SM_EDITOR
Switch to scenario editor.
std::string default_company_pass
default password for new companies in encrypted form
bool _network_server
network-server is active
std::string name
The name of the base set.
SaveLoadOperation
Operation performed on the file.
std::string name
Name of the file.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
An interval timer will fire every interval, and will continue to fire until it is deleted.
void SaveToConfig()
Save the values to the configuration file.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
void InitWindowSystem()
(re)initialize the windowing system
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Tindex index
Index of this pool item.
uint16_t dedicated_port
Port for the dedicated server.
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
int _skip_all_newgrf_scanning
Set this flag to prevent any NewGRF scanning from being done.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
static Blitter * SelectBlitter(const std::string &name)
Find the requested blitter and return its class.
static void GetDriversInfo(std::back_insert_iterator< std::string > &output_iterator)
Build a human readable list of available drivers, grouped by type.
@ SLO_CHECK
Load file for checking and/or preview.
void ChangeNetworkRestartTime(bool reset)
Reset the automatic network restart time interval.
bool _do_autosave
are we doing an autosave at the moment?
VehicleDefaultSettings vehicle
default settings for vehicles
void Info(uint32_t *last_ottd_rev, byte *ever_modified, bool *removed_newgrfs)
Get some basic information from the given gamelog.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
void UnInitWindowSystem()
Close down the windowing system.
@ DFT_GAME_FILE
Save game or scenario file.
class GameConfig * game_config
settings for gamescript
void DumpDebugFacilityNames(std::back_insert_iterator< std::string > &output_iterator)
Dump the available debug facility names in the help text.
GRFConfig * grfconfig
NewGrf configuration from save.
CargoList that is used for stations.
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
static void EventEnterSingleplayer(uint map_width, uint map_height)
Event: user entered a singleplayer game.
static DateFract date_fract
Fractional part of the day.
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
ClientSettings _settings_client
The current settings for this game.
StringList _network_bind_list
The addresses to bind on.
DetailedFileType GetDetailedFileType(FiosType fios_type)
Extract the detailed file type from a FiosType.
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
void SetDebugString(const char *s, void(*error_func)(const std::string &))
Set debugging levels by parsing the text in s.
void LoadFromHighScore()
Initialize the highscore table to 0 and if any file exists, load in values.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Templated helper to make a type-safe 'typedef' representing a single POD value.
void RunVehicleCalendarDayProc()
Age all vehicles, spreading out the action using the current TimerGameCalendar::date_fract.
bool HasErrors()
Check whether loading the game resulted in errors.
void Reset()
Resets and frees all memory allocated - used before loading or starting a new game.
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
uint64_t used_liveries
Bitmask of LiveryScheme used by the defined engines.
byte _display_opt
What do we want to draw/do?
#define GETOPT_SHORT_NOVAL(shortname)
Short option without value.
@ VEH_ROAD
Road vehicle type.
Defines the internal data of a functional industry.
AfterNewGRFScan()
Create a new callback.
@ SM_LOAD_SCENARIO
Load scenario from scenario editor.
Owner
Enum for all companies/owners.
bool StrEmpty(const char *s)
Check if a string buffer is empty.
static void CheckCaches()
Check the validity of some of the caches.
bool MakeHeightmapScreenshot(const char *filename)
Make a heightmap of the current map.
uint16_t h
The height of the area.
void InitializeScreenshotFormats()
Initialize screenshot format information on startup, with _screenshot_format_name filled from the loa...
@ PFE_GL_LANDSCAPE
Time spent processing other world features.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
@ GCF_COMPATIBLE
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
std::string _ini_musicdriver
The music driver a stored in the configuration file.
GameCreationSettings game_creation
settings used during the creation of a game (map)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
@ PFE_GL_TRAINS
Time spent processing trains.
void UninitFontCache()
Free everything allocated w.r.t.
std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password)
Change the company password of a given company.
CargoList that is used for vehicles.
#define GETOPT_SHORT_OPTVAL(shortname)
Short option with optional value.
@ PM_UNPAUSED
A normal unpaused game.
void UpdateCache()
Update the caches of this ship.
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
@ COMPANY_FIRST
First company, same as owner.
@ DO_FULL_ANIMATION
Perform palette animation.
void NetworkClientJoinGame()
Actually perform the joining to the server.
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Colours _company_colours[MAX_COMPANIES]
NOSAVE: can be determined from company structs.
static void OnStartGame(bool dedicated_server)
Triggers everything that should be triggered when starting a game.
void RebuildTownCaches()
Rebuild all the cached variables of towns.
@ COMPANY_NEW_COMPANY
The client wants a new company.
std::chrono::steady_clock::time_point start_time
Time when the current game was started.
@ SLO_LOAD
File is being loaded.
Cached, frequently calculated values.
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
std::string last_joined
Last joined server.
@ SLO_SAVE
File is being saved.
Information about GRF, used in the game and (part of it) in savegames.
@ PM_PAUSED_SAVELOAD
A game paused for saving/loading.
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
@ SM_NEWGAME
New Game --> 'Random game'.
@ S8BPP_NONE
No support for 8bpp by OS or hardware, force 32bpp blitters.
void free(const void *ptr)
Version of the standard free that accepts const pointers.
@ SM_SAVE_HEIGHTMAP
Save heightmap.
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count)
Execute a given command passed to us.
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
static void GetConsoleList(std::back_insert_iterator< std::string > &output_iterator, bool newest_only)
Wrapper function for GameScanner::GetConsoleList.
@ VS_CRASHED
Vehicle is crashed.
@ GWM_RANDOM
Generate a random map for SE.
Colours colour
Company colour.
static void ShowHelp()
Show the help message when someone passed a wrong parameter.
@ PFE_GL_SHIPS
Time spent processing ships.
#define GETOPT_END()
Option terminator.
void InitFontCache(bool monospace)
(Re)initialize the font cache related things, i.e.
static void ParseResolution(Dimension *res, const char *s)
Extract the resolution from the given string and store it in the 'res' parameter.
bool pause_on_newgame
whether to start new games paused or not
void InvalidateCache()
Invalidates the cached data and rebuilds it.
@ SL_REINIT
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
static void OnStartScenario()
Triggers everything required to set up a saved scenario for a new game.
GroundVehicleCache gcache
Cache of often calculated values.
Represents the covered area of e.g.
PauseMode _pause_mode
The current pause mode.
static void Initialize()
Initialize the AI system.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
CompanySettings settings
settings specific for each company
bool HasModalProgress()
Check if we are currently in a modal progress state.
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
std::optional< size_t > savegame_size
Size of the last saved savegame in bytes, or std::nullopt if not saved yet.
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ...
Cached often queried values common to all vehicles.
@ MAX_COMPANIES
Maximum number of companies.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
int MemCmpT(const T *ptr1, const T *ptr2, size_t num=1)
Type-safe version of memcmp().
TimerGameCalendar::Year starting_year
starting date
std::tuple< FiosType, std::string > FiosGetSavegameListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
Callback for FiosGetFileList.
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
static void Clean(PoolType)
Clean all pools of given type.
@ FT_INVALID
Invalid or unknown file type.
void NetworkShutDown()
This shuts the network down.
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
void OnNewGRFsScanned() override
Called whenever the NewGRF scan completed.
uint32_t generation_seed
Seed for the new game.
bool _networking
are we in networking mode?
void ChangeAutosaveFrequency(bool reset)
Reset the interval of the autosave.
char * opt
Option value, if available (else nullptr).
bool IsCompatible(uint32_t old_version) const
Return whether this NewGRF can replace an older version of the same NewGRF.
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
The data of the error message.
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
The TimerManager manages a single Timer-type.
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
static bool Elapsed(TElapsed value)
Called when time for this timer elapsed.
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
bool _network_dedicated
are we a dedicated server?
static void GameLoop()
Called every game-tick to let AIs do something.
static void Shutdown()
Shutdown the social integration system, and all social integration plugins that are loaded.
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
@ FT_SAVEGAME
old or new savegame
GameMode
Mode which defines the state of the game.
@ SM_GENRANDLAND
Generate random land within scenario editor.
static std::string ini_set
The set as saved in the config file.
void Transmit(Reason reason, bool blocking=false)
Transmit the survey.
GameSessionStats _game_session_stats
Statistics about the current session.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
static void EventEnterMultiplayer(uint map_width, uint map_height)
Event: user entered a multiplayer game.
Data storage for parsing command line options.
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
StringID error
Error message from loading. INVALID_STRING_ID if no error.
uint16_t server_port
port the server listens on
static void ReduceLineCache()
Reduce the size of linecache if necessary to prevent infinite growth.
std::string join_company_password
The password to join the company with.
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
StringID name
The name for this object.
GRFConfig & GetOrCreateExtraConfig() const
Return configuration for the extra GRF, or lazily create it.
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
@ SM_LOAD_HEIGHTMAP
Load heightmap from scenario editor.
static debug_inline uint SizeX()
Get the size of the map along the X.
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr< LoadFilter > lf=nullptr)
Load the specified savegame but on error do different things.
bool _blitter_autodetected
Was the blitter autodetected or specified by the user?
@ DFT_INVALID
Unknown or invalid file.
SwitchMode _switch_mode
The next mainloop command.
static void EventEnterScenarioEditor(uint map_width, uint map_height)
Event: user entered the Scenario Editor.
Stores station stats for a single cargo.
CompanyID _current_company
Company currently doing an action.
void UpdateNewGRFConfigPalette(int32_t)
Update the palettes of the graphics from the config file.
static void GameLoop()
Called every game-tick to let Game do something.
@ DT_SOUND
A sound driver.
@ SCENARIO
Scan for scenarios and heightmaps.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static Year year
Current year, starting at 0.
static void EventJoiningMultiplayer()
Event: user is joining a multiplayer game.
@ PFE_GAMELOOP
Speed of gameloop processing.
A savegame name automatically numbered.
static void KillAll()
Kill any and all AIs we manage.
DetailedFileType
Kinds of files in each AbstractFileType.
void Clear()
Reset read data.
uint32_t generation_seed
noise seed for world generation
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
@ PFE_GL_ECONOMY
Time spent processing cargo movement.
void SaveToHighScore()
Save HighScore table to file.
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
void FillNewGRFVehicleCache(const Vehicle *v)
Fill the grf_cache of the given vehicle.
static void EventEnterMainMenu()
Event: user entered the main menu.
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
uint8_t map_y
Y size of map.
void Restore()
Restore the variable.
uint8_t map_x
X size of map.
@ LEAVE
User is leaving the game (but not exiting the application).
std::string _ini_blitter
The blitter as stored in the configuration file.
uint32_t extra_version
version of the extra GRF
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
static void SetErrorMessage(const std::string &message)
Sets a message for the error message handler.
@ NO_DIRECTORY
A path without any base directory.
@ COMPANY_SPECTATOR
The client is spectating.
uint32_t autosave_interval
how often should we do autosaves?
TileIndex tile
The base tile of the area.
@ DT_VIDEO
A video driver.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
void GenerateSavegameId()
Generate an unique savegame ID.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
std::string _ini_sounddriver
The sound driver a stored in the configuration file.
@ OWNER_NONE
The tile has no ownership.
@ PM_PAUSED_NORMAL
A game normally paused.
static const OptionData _options[]
Options of OpenTTD.
@ GWM_EMPTY
Generate an empty map (sea-level)
void FatalErrorI(const std::string &str)
Error handling for fatal non-user errors.
std::tuple< FiosType, std::string > FiosGetScenarioListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
Callback for FiosGetFileList.
static void RunCallbacks()
Allow any social integration library to handle their own events.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
@ SM_RESTART_HEIGHTMAP
Load a heightmap and start a new game from it with current settings.
@ PFE_ALLSCRIPTS
Sum of all GS/AI scripts.
bool disable_elrails
when true, the elrails are disabled
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
@ FT_HEIGHTMAP
heightmap file
Subdirectory
The different kinds of subdirectories OpenTTD uses.
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
void ResetNewGRFData()
Reset all NewGRF loaded data.
SaveOrLoadResult
Save or load result codes.
@ WL_ERROR
Errors (eg. saving/loading failed)
@ SM_RELOADGAME
Reload the savegame / scenario / heightmap you started the game with.
@ SM_MENU
Switch to game intro menu.
static void Initialize()
Initialize the social integration system, loading any social integration plugins that are available.
Colours starting_colour
default color scheme for the company to start a new game with
uint32_t last_newgrf_count
the numbers of NewGRFs we found during the last scan
uint16_t w
The width of the area.
void AnimateAnimatedTiles()
Animate all tiles in the animated tile list, i.e. call AnimateTile on them.
@ GWM_NEWGAME
Generate a map for a new game.
int GetOpt()
Find the next option.
static void SelectDriver(const std::string &name, Driver::Type type)
Find the requested driver and return its class.
Callback structure of statements to be executed after the NewGRF scan.
void MusicLoop()
Check music playback status and start/stop/song-finished.
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
Join a client to the server at with the given connection string.
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
@ SLO_INVALID
Unknown file operation.
Callback for NewGRF scanning.
Variables that are cached to improve performance and such.
byte effect_vol
The requested effects volume.
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
SaveOrLoadResult LoadWithFilter(std::shared_ptr< LoadFilter > reader)
Load the game using a (reader) filter.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
NetworkSettings network
settings related to the network
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
virtual void MainLoop()=0
Perform the actual drawing.
Colours starting_colour_secondary
default secondary color scheme for the company to start a new game with
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
@ BASESET
Scan for base sets.
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
static SoundDriver * GetInstance()
Get the currently active instance of the sound driver.
void UserErrorI(const std::string &str)
Error handling for fatal user errors.
AbstractFileType GetAbstractFileType(FiosType fios_type)
Extract the abstract file type from a FiosType.
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
@ INVALID_COMPANY
An invalid company.
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
static void GetBlittersInfo(std::back_insert_iterator< std::string > &output_iterator)
Fill a buffer with information about the blitters.
void ProcessAsyncSaveFinish()
Handle async save finishes.
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
@ ZOOM_LVL_NORMAL
The normal zoom level.
std::string connection_string
Information about the server to connect to.
CompanySettings company
default values for per-company settings
@ CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
VehicleSettings vehicle
options for vehicles
static void GetConsoleList(std::back_insert_iterator< std::string > &output_iterator, bool newest_only)
Wrapper function for AIScanner::GetAIConsoleList.
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
static std::string ini_set
The set as saved in the config file.
@ VEH_TRAIN
Train vehicle type.
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
A Stop for a Road Vehicle.
void StateGameLoop()
State controlling game loop.
void NetworkStartUp()
This tries to launch the network for a given OS.
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
@ DT_MUSIC
A music driver, needs to be before sound to properly shut down extmidi forked music players.
std::string dedicated_host
Hostname for the dedicated server.
bool _network_available
is network mode available?
void InitializeRoadGUI()
I really don't know why rail_gui.cpp has this too, shouldn't be included in the other one?
void SetMode(FiosType ft)
Set the mode and file type of the file to save or load based on the type of file entry at the file sy...
bool reload_cfg
reload the config file before restarting
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ VEH_SHIP
Ship vehicle type.
#define GETOPT_SHORT_VALUE(shortname)
Short option with value.
bool IsLocalCompany()
Is the current company the local company?
@ SM_JOIN_GAME
Join a network game.
virtual void Stop()=0
Stop this driver.
bool in_window
mouse inside this window, determines drawing logic
MusicSettings music
settings related to music/sound
@ SL_OK
completed successfully
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
void LoadFromConfig(bool startup)
Load the values from the configuration files.
@ PM_COMMAND_DURING_PAUSE
A game paused, and a command executed during the pause; resets on autosave.
byte music_vol
The requested music volume.
SaveLoadVersion _sl_version
the major savegame version identifier
void UpdateLandscapingLimits()
Update the landscaping limits per company.
Dimension _cur_resolution
The current resolution.
bool _is_network_server
Does this client wants to be a network-server?
int numleft
Number of arguments left in argv.
@ EXIT
User is exiting the application.
uint8_t _network_reconnect
Reconnect timeout.
std::string _ini_videodriver
The video driver a stored in the configuration file.
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
static uint SizeY()
Get the size of the map along the Y.
GUISettings gui
settings related to the GUI
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
void InitializeLanguagePacks()
Make a list of the available language packs.
Cached often queried (NewGRF) values.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
SaveLoadOperation file_op
File operation to perform.
void StateGameLoop_LinkGraphPauseControl()
Pause the game if in 2 TimerGameEconomy::date_fract ticks, we would do a join with the next link grap...
@ AUTOSAVE
Only run when not paused or there was a Command executed recently.
static Year year
Current year, starting at 0.
ParticipateSurvey participate_survey
Participate in the automated survey.
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks.
@ SM_RESTARTGAME
Restart --> 'Random game' with current settings.
static Date date
Current date in days (day counter).
static void Initialize()
Initialize the Game system.
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.