Go to the documentation of this file.
73 #include <system_error>
78 # include <emscripten.h>
79 # include <emscripten/html5.h>
82 void CallLandscapeTick();
84 void DoPaletteAnimations();
91 extern void ShowOSErrorBox(
const char *buf,
bool system);
94 bool _save_config =
false;
95 bool _request_newgrf_scan =
false;
112 ShowOSErrorBox(buf,
false);
115 #ifdef __EMSCRIPTEN__
116 emscripten_exit_pointerlock();
120 EM_ASM(
if (window[
"openttd_syncfs"]) openttd_syncfs());
121 EM_ASM(
if (window[
"openttd_abort"]) openttd_abort());
132 void CDECL
error(
const char *s, ...)
142 ShowOSErrorBox(buf,
true);
176 "Command line options:\n"
177 " -v drv = Set video driver (see below)\n"
178 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
179 " -m drv = Set music driver (see below)\n"
180 " -b drv = Set the blitter to use (see below)\n"
181 " -r res = Set resolution (for instance 800x600)\n"
182 " -h = Display this help text\n"
183 " -t year = Set starting year\n"
184 " -d [[fac=]lvl[,...]]= Debug mode\n"
185 " -e = Start Editor\n"
186 " -g [savegame] = Start new/save game immediately\n"
187 " -G seed = Set random seed\n"
188 " -n [ip:port#company]= Join network game\n"
189 " -p password = Password to join server\n"
190 " -P password = Password to join company\n"
191 " -D [ip][:port] = Start dedicated server\n"
192 " -l ip[:port] = Redirect DEBUG()\n"
194 " -f = Fork into the background (dedicated only)\n"
196 " -I graphics_set = Force the graphics set (see below)\n"
197 " -S sounds_set = Force the sounds set (see below)\n"
198 " -M music_set = Force the music set (see below)\n"
199 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
200 " -x = Never save configuration changes to disk\n"
201 " -q savegame = Write some information about the savegame and exit\n"
243 static void WriteSavegameInfo(
const char *
name)
246 uint32 last_ottd_rev = 0;
247 byte ever_modified = 0;
248 bool removed_newgrfs =
false;
256 p +=
seprintf(p,
lastof(buf),
"NewGRF ver: 0x%08X\n", last_ottd_rev);
259 if (removed_newgrfs) {
268 p +=
seprintf(p,
lastof(buf),
"%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
290 const char *t = strchr(s,
'x');
296 res->width = std::max(strtoul(s,
nullptr, 0), 64UL);
297 res->height = std::max(strtoul(t + 1,
nullptr, 0), 64UL);
340 _game_mode = GM_MENU;
365 void MakeNewgameSettingsLive()
396 void OpenBrowser(
const char *url)
399 if (strstr(url,
"http://") != url && strstr(url,
"https://") != url)
return;
401 extern void OSOpenBrowser(
const char *url);
477 const char *port =
nullptr;
478 const char *company =
nullptr;
484 if (company !=
nullptr) {
495 if (port !=
nullptr) rport = atoi(port);
508 extern void DedicatedFork();
549 std::string musicdriver;
550 std::string sounddriver;
551 std::string videodriver;
553 std::string graphics_set;
554 std::string sounds_set;
555 std::string music_set;
558 bool dedicated =
false;
559 char *debuglog_conn =
nullptr;
561 extern bool _dedicated_forks;
562 _dedicated_forks =
false;
564 _game_mode = GM_MENU;
571 while ((i = mgo.
GetOpt()) != -1) {
573 case 'I': graphics_set = mgo.
opt;
break;
574 case 'S': sounds_set = mgo.
opt;
break;
575 case 'M': music_set = mgo.
opt;
break;
576 case 'm': musicdriver = mgo.
opt;
break;
577 case 's': sounddriver = mgo.
opt;
break;
578 case 'v': videodriver = mgo.
opt;
break;
579 case 'b': blitter = mgo.
opt;
break;
581 musicdriver =
"null";
582 sounddriver =
"null";
583 videodriver =
"dedicated";
587 if (mgo.
opt !=
nullptr) {
590 const char *temp =
nullptr;
591 const char *port =
nullptr;
594 if (port !=
nullptr) scanner->dedicated_port = atoi(port);
597 case 'f': _dedicated_forks =
true;
break;
599 scanner->network_conn = mgo.
opt;
602 debuglog_conn = mgo.
opt;
605 scanner->join_server_password = mgo.
opt;
608 scanner->join_company_password = mgo.
opt;
611 case 't': scanner->startyear = atoi(mgo.
opt);
break;
621 if (mgo.
opt !=
nullptr) {
629 if (t != std::string::npos) {
640 scanner->generation_seed = InteractiveRandom();
657 fprintf(stderr,
"Failed to open savegame\n");
662 fprintf(stderr,
"%s\n", buf);
667 WriteSavegameInfo(title);
670 case 'G': scanner->generation_seed = strtoul(mgo.
opt,
nullptr, 10);
break;
672 case 'x': scanner->save_config =
false;
break;
680 if (i == -2 || mgo.
numleft > 0) {
698 if (dedicated)
DEBUG(net, 0,
"Starting dedicated version %s", _openttd_revision);
699 if (_dedicated_forks && !dedicated) _dedicated_forks =
false;
703 if (_dedicated_forks) DedicatedFork();
735 if (!graphics_set.empty()) {
738 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
739 msg.SetDParamStr(0, graphics_set.c_str());
747 DEBUG(misc, 1,
"Loading blitter...");
761 usererror(
"Failed to autoprobe blitter") :
762 usererror(
"Failed to select requested blitter '%s'; does it exist?", blitter.c_str());
778 const char *not_used =
nullptr;
779 const char *port =
nullptr;
785 if (port !=
nullptr) rport = atoi(port);
787 NetworkStartDebugLog(debuglog_conn, rport);
804 usererror(
"Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
806 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
816 usererror(
"Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
818 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
855 void HandleExitGameRequest()
857 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) {
867 static void MakeNewGameDone()
913 static void MakeNewGame(
bool from_heightmap,
bool reset_settings)
915 _game_mode = GM_NORMAL;
916 if (!from_heightmap) {
927 static void MakeNewEditorWorldDone()
932 static void MakeNewEditorWorld()
934 _game_mode = GM_EDITOR;
963 case SL_OK:
return true;
973 DEBUG(net, 0,
"Loading game failed, so a new (random) game will be started!");
974 MakeNewGame(
false,
true);
985 case GM_EDITOR: MakeNewEditorWorld();
break;
1015 MakeNewgameSettingsLive();
1018 NetworkServerStart();
1031 MakeNewEditorWorld();
1147 default: NOT_REACHED();
1162 if (_debug_desync_level <= 1)
return;
1165 std::vector<TownCache> old_town_caches;
1167 old_town_caches.push_back(t->cache);
1176 if (
MemCmpT(old_town_caches.data() + i, &t->cache) != 0) {
1177 DEBUG(desync, 2,
"town cache mismatch: town %i", (
int)t->index);
1183 std::vector<CompanyInfrastructure> old_infrastructure;
1192 DEBUG(desync, 2,
"infrastructure cache mismatch: company %i", (
int)c->
index);
1202 rs->GetEntry(
DIAGDIR_NE)->CheckIntegrity(rs);
1203 rs->GetEntry(
DIAGDIR_NW)->CheckIntegrity(rs);
1211 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) length++;
1213 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1214 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1216 TrainCache *tra_cache = CallocT<TrainCache>(length);
1219 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) {
1221 grf_cache[length] = u->grf_cache;
1222 veh_cache[length] = u->vcache;
1246 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) {
1248 if (memcmp(&grf_cache[length], &u->grf_cache,
sizeof(
NewGRFCache)) != 0) {
1249 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);
1251 if (memcmp(&veh_cache[length], &u->vcache,
sizeof(
VehicleCache)) != 0) {
1252 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);
1257 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);
1260 DEBUG(desync, 2,
"train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->
index, (
int)v->
owner, v->
unitnumber, length);
1265 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);
1284 v->cargo.InvalidateCache();
1289 std::vector<StationList> old_town_stations_near;
1290 for (
Town *t :
Town::Iterate()) old_town_stations_near.push_back(t->stations_near);
1292 std::vector<StationList> old_industry_stations_near;
1299 st->goods[c].cargo.InvalidateCache();
1305 std::map<TileIndex, bool> docking_tiles;
1310 UpdateStationDockingTiles(st);
1311 if (ta.
tile != st->docking_station.tile || ta.
w != st->docking_station.w || ta.
h != st->docking_station.h) {
1312 DEBUG(desync, 2,
"station docking mismatch: station %i, company %i", st->index, (
int)st->owner);
1316 DEBUG(desync, 2,
"docking tile mismatch: tile %i", (
int)tile);
1321 IndustryList industries_near = st->industries_near;
1322 st->RecomputeCatchment();
1323 if (st->industries_near != industries_near) {
1324 DEBUG(desync, 2,
"station industries near mismatch: station %i", st->index);
1331 if (t->stations_near != old_town_stations_near[i]) {
1332 DEBUG(desync, 2,
"town stations near mismatch: town %i", t->index);
1338 if (ind->stations_near != old_industry_stations_near[i]) {
1339 DEBUG(desync, 2,
"industry stations near mismatch: industry %i", ind->index);
1367 #ifndef DEBUG_DUMP_COMMANDS
1378 if (_game_mode == GM_EDITOR) {
1382 CallLandscapeTick();
1391 char name[MAX_PATH];
1407 CallLandscapeTick();
1410 #ifndef DEBUG_DUMP_COMMANDS
1439 static int _autosave_ctr = 0;
1447 DEBUG(sl, 2,
"Autosaving to '%s'", buf);
1463 if (_request_newgrf_scan)
return false;
1465 _request_newgrf_scan =
true;
1466 _request_newgrf_scan_callback = callback;
1472 if (_game_mode == GM_BOOTSTRAP) {
1478 if (_request_newgrf_scan) {
1480 _request_newgrf_scan =
false;
1481 _request_newgrf_scan_callback =
nullptr;
1483 if (_exit_game)
return;
1501 IncreaseSpriteLRU();
@ VEH_AIRCRAFT
Aircraft vehicle type.
char title[255]
Internal name of the game.
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.
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.
uint32 generation_seed
noise seed for world generation
void SetDebugString(const char *s)
Set debugging levels by parsing the text in s.
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
class AIConfig * ai_config[MAX_COMPANIES]
settings per company
static const uint16 NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
@ FT_SCENARIO
old or new scenario
static Titem * Get(size_t index)
Returns Titem with given index.
@ SAVE_DIR
Base directory for all savegames.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
@ SM_LOAD_GAME
Load game, Play Scenario.
Dimensions (a width and height) of a rectangle in 2D.
const char * join_company_password
The password to join the company with.
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.
uint8 map_y
Y size of map.
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
struct LoggedAction * gamelog_action
Gamelog actions.
std::string _config_file
Configuration file of OpenTTD.
Class to backup a specific variable and restore it later.
uint16 server_port
port the server listens on
Vehicle * Next() const
Get the next vehicle of this vehicle.
Year _cur_year
Current year, starting at 0.
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.
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
@ 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.
DateFract _date_fract
Fractional part of the day.
@ SM_EDITOR
Switch to scenario editor.
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 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.
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
char * dedicated_host
Hostname for the dedicated server.
static Blitter * SelectBlitter(const std::string &name)
Find the requested blitter and return his class.
char map_name[NETWORK_NAME_LENGTH]
Map which is played ["random" for a randomized map].
@ SLO_CHECK
Load file for checking and/or preview.
void DeterminePaths(const char *exe)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir,...
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool _do_autosave
are we doing an autosave at the moment?
VehicleDefaultSettings vehicle
default settings for vehicles
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
GRFConfig * grfconfig
NewGrf configuration from save.
CargoList that is used for stations.
void SetName(const char *name)
Set the name of the file.
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
static const Year INVALID_YEAR
Representation of an invalid year.
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
char * network_conn
Information about the server to connect to, or nullptr.
@ 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.
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
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.
bool HasErrors()
Check whether loading the game resulted in errors.
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
byte _display_opt
What do we want to draw/do?
SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
Load the game using a (reader) filter.
#define GETOPT_SHORT_NOVAL(shortname)
Short option without value.
@ VEH_ROAD
Road vehicle type.
NetworkServerGameInfo _network_game_info
Information about our game.
Defines the internal data of a functional industry.
AfterNewGRFScan()
Create a new callback.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
@ SM_LOAD_SCENARIO
Load scenario from scenario editor.
Owner owner
Which company owns the vehicle?
Owner
Enum for all companies/owners.
static bool IsLocalCompany()
Is the current company the local company?
static void CheckCaches()
Check the validity of some of the caches.
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
bool MakeHeightmapScreenshot(const char *filename)
Make a heightmap of the current map.
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.
@ 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.
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
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.
CargoList that is used for vehicles.
void RebuildTownCaches()
Rebuild all the cached variables of towns.
#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 UpdateNewGRFConfigPalette(int32 p1)
Update the palettes of the graphics from the config file.
@ 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.
@ COMPANY_NEW_COMPANY
The client wants a new company.
@ SLO_LOAD
File is being loaded.
Cached, frequently calculated values.
char * DumpDebugFacilityNames(char *buf, char *last)
Dump the available debug facility names in the help text.
uint32 generation_seed
Seed for the new game.
byte colour
Company colour.
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
Date _date
Current date in days (day counter)
@ SLO_SAVE
File is being saved.
#define TILE_AREA_LOOP(var, ta)
A loop which iterates over the tiles of a TileArea.
Information about GRF, used in the game and (part of it) in savegames.
@ PM_PAUSED_SAVELOAD
A game paused for saving/loading.
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
char last_host[NETWORK_HOSTNAME_LENGTH]
IP address of the last joined server.
@ CMD_PAUSE
pause the game
@ SM_NEWGAME
New Game --> 'Random game'.
static char * GetDriversInfo(char *p, const char *last)
Build a human readable list of available drivers, grouped by type.
byte starting_colour
default color scheme for the company to start a new game with
@ S8BPP_NONE
No support for 8bpp by OS or hardware, force 32bpp blitters.
Year startyear
The start year.
#define DEBUG(name, level,...)
Output a line of debugging information.
@ SM_SAVE_HEIGHTMAP
Save heightmap.
char * error_data
Data to pass to SetDParamStr when displaying error.
uint gamelog_actions
Number of gamelog actions.
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
@ VS_CRASHED
Vehicle is crashed.
@ GWM_RANDOM
Generate a random map for SE.
static void SetErrorMessage(const char *message)
Sets a message for the error message handler.
char default_company_pass[NETWORK_PASSWORD_LENGTH]
default password for new companies in encrypted form
uint16 w
The width of the area.
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 FioCloseAll()
Close all slotted open files.
static void ParseResolution(Dimension *res, const char *s)
Extract the resolution from the given string and store it in the 'res' parameter.
bool SettingsDisableElrail(int32 p1)
_settings_game.disable_elrail callback
bool pause_on_newgame
whether to start new games paused or not
static AIConfig * GetConfig(CompanyID company, ScriptSettingSource source=SSS_DEFAULT)
Get the config of a company.
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
void ParseConnectionString(const char **company, const char **port, char *connection_string)
Converts a string to ip/port/company Format: IP:port::company.
@ SL_REINIT
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
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.
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ...
static void DoAutosave()
Create an autosave.
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.
bool keep_all_autosave
name the autosave in a different way
void NetworkDisconnect(bool blocking, bool close_admins)
We want to disconnect from the host/clients.
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
void UninitFreeType()
Free everything allocated w.r.t.
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.
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
bool _networking
are we in networking mode?
uint16 last_port
port of the last joined server
char * opt
Option value, if available (else nullptr).
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
The data of the error message.
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
byte max_num_autosaves
controls how many autosavegames are made before the game starts to overwrite (names them 0 to max_num...
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
uint8 _network_reconnect
Reconnect timeout.
bool _network_dedicated
are we a dedicated server?
static void GameLoop()
Called every game-tick to let AIs do something.
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 VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Data storage for parsing command line options.
StringID error
Error message from loading. INVALID_STRING_ID if no error.
void GenerateDefaultSaveName(char *buf, const char *last)
Fill the buffer with the default name for a savegame or screenshot.
static void ReduceLineCache()
Reduce the size of linecache if necessary to prevent infinite growth.
static char * GetConsoleList(char *p, const char *last, bool newest_only=false)
Wrapper function for AIScanner::GetAIConsoleList.
uint16 h
The height of the area.
StringID name
The name for this object.
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
@ SM_LOAD_HEIGHTMAP
Load heightmap from scenario editor.
void IncreaseDate()
Increases the tick counter, increases date and possibly calls procedures that have to be called daily...
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.
CompanyID _current_company
Company currently doing an action.
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.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
@ PFE_GAMELOOP
Speed of gameloop processing.
static void KillAll()
Kill any and all AIs we manage.
DetailedFileType
Kinds of files in each AbstractFileType.
void Clear()
Reset read data.
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.
void Restore()
Restore the variable.
uint16 dedicated_port
Port for the dedicated server.
std::string _ini_blitter
The blitter as stored in the configuration file.
FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const std::string &file, const char *ext, char *title, const char *last)
Callback for FiosGetFileList.
uint8 map_x
X size of map.
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.
@ NO_DIRECTORY
A path without any base directory.
@ COMPANY_SPECTATOR
The client is spectating.
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.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
std::string _ini_sounddriver
The sound driver a stored in the configuration file.
static const uint16 NETWORK_DEFAULT_DEBUGLOG_PORT
The default port debug-log is sent to (TCP)
void ScheduleErrorMessage(const ErrorMessageData &data)
Schedule an error.
@ 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)
@ SM_RESTART_HEIGHTMAP
Load a heightmap and start a new game from it with current settings.
@ NUM_CARGO
Maximal number of cargo types in a game.
@ PFE_ALLSCRIPTS
Sum of all GS/AI scripts.
bool disable_elrails
when true, the elrails are disabled
void CDECL ShowInfoF(const char *str,...)
Shows some information on the console/a popup box depending on the OS.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
@ FT_HEIGHTMAP
heightmap file
Subdirectory
The different kinds of subdirectories OpenTTD uses.
void ResetNewGRFData()
Reset all NewGRF loaded data.
Year starting_year
starting date
UnitID unitnumber
unit number, for display purposes only
SaveOrLoadResult
Save or load result codes.
@ WL_ERROR
Errors (eg. saving/loading failed)
void GamelogReset()
Resets and frees all memory allocated - used before loading or starting a new game.
@ SM_RELOADGAME
Reload the savegame / scenario / heightmap you started the game with.
FiosType
Elements of a file system that are recognized.
@ SM_MENU
Switch to game intro menu.
void InitFreeType(bool monospace)
(Re)initialize the freetype related things, i.e.
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.
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Callback structure of statements to be executed after the NewGRF scan.
void MusicLoop()
Check music playback status and start/stop/song-finished.
const char * NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
Change the company password of a given company.
static bool IsDockingTile(TileIndex t)
Checks whether the tile is marked as a dockling tile.
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.
Interface for filtering a savegame till it is loaded.
Variables that are cached to improve performance and such.
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
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.
byte CargoID
Cargo slots to indicate a cargo type within a game.
@ 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.
@ 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...
void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
void Change(const char *name, int version=-1, bool force_exact_match=false, bool is_random=false)
Set another Script to be loaded in this slot.
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.
CompanySettings company
default values for per-company settings
uint32 last_newgrf_count
the numbers of NewGRFs we found during the last scan
@ CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
VehicleSettings vehicle
options for vehicles
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
@ 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.
VehicleType type
Type of vehicle.
void StateGameLoop()
State controlling game loop.
void NetworkStartUp()
This tries to launch the network for a given OS.
static bool HasModalProgress()
Check if we are currently in a modal progress state.
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.
bool _network_available
is network mode available?
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
void InitializeRoadGUI()
I really don't know why rail_gui.cpp has this too, shouldn't be included in the other one?
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
static int MemCmpT(const T *ptr1, const T *ptr2, size_t num=1)
Type-safe version of memcmp().
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
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.
@ SM_JOIN_GAME
Join a network game.
virtual void Stop()=0
Stop this driver.
@ SSS_FORCE_GAME
Get the Script config from the current game.
bool in_window
mouse inside this window, determines drawing logic
MusicSettings music
settings related to music/sound
#define lastof(x)
Get the last element of an fixed size array.
@ SL_OK
completed successfully
void LoadFromConfig(bool startup)
Load the values from the configuration files.
CompanySettings settings
settings specific for each company
void UpdateGUIZoom()
Resolve GUI zoom level, if auto-suggestion is requested.
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.
void GamelogInfo(LoggedAction *gamelog_action, uint gamelog_actions, uint32 *last_ottd_rev, byte *ever_modified, bool *removed_newgrfs)
Get some basic information from the given gamelog.
const char * join_server_password
The password to join the server with.
std::string _ini_videodriver
The video driver a stored in the configuration file.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
static char * GetBlittersInfo(char *p, const char *last)
Fill a buffer with information about the blitters.
static char * GetConsoleList(char *p, const char *last, bool newest_only=false)
Wrapper function for GameScanner::GetConsoleList.
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.
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 _date_fract ticks, we would do a join with the next link graph job,...
virtual void OnNewGRFsScanned()
Called whenever the NewGRF scan completed.
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 void Initialize()
Initialize the Game system.