56#include "table/strings.h"
84 static const SettingTable _generic_setting_tables[] = {
93 _news_display_settings,
94 _pathfinding_settings,
98 return _generic_setting_tables;
107 static const SettingTable _private_setting_tables[] = {
108 _network_private_settings,
110 return _private_setting_tables;
119 static const SettingTable _secrets_setting_tables[] = {
120 _network_secrets_settings,
122 return _secrets_setting_tables;
125using SettingDescProc = void(
IniFile &ini,
const SettingTable &desc, std::string_view grpname,
void *
object,
bool only_startup);
126using SettingDescProcList = void(
IniFile &ini, std::string_view grpname,
StringList &list);
128static bool IsSignedVarMemType(
VarType vt)
147 static inline const IniGroupNameList list_group_names = {
151 "server_bind_addresses",
152 "server_authorized_keys",
153 "rcon_authorized_keys",
154 "admin_authorized_keys"
158 ConfigIniFile(
const std::string &filename) :
IniFile(list_group_names)
202 if (!value.has_value())
return std::nullopt;
204 if (value < min || value >
max) {
221 if (digit.has_value())
return digit;
223 auto it = std::ranges::find(
many,
str);
224 if (it ==
many.end())
return std::nullopt;
225 return static_cast<uint32_t
>(it -
many.begin());
236 if (
str ==
"true" ||
str ==
"on" ||
str ==
"1")
return true;
237 if (
str ==
"false" ||
str ==
"off" ||
str ==
"0")
return false;
249static std::optional<uint32_t>
LookupManyOfMany(std::span<const std::string_view> many, std::string_view str)
251 static const std::string_view separators{
" \t|"};
260 if (value.empty())
break;
263 if (!r.has_value())
return r;
275static std::optional<std::vector<uint32_t>>
ParseIntList(std::string_view str)
278 std::vector<uint32_t> result;
284 if (comma && consumer.
ReadIf(
",")) {
290 if (!v.has_value())
return std::nullopt;
291 result.push_back(*v);
297 if (!result.empty() && !comma)
return std::nullopt;
313 std::byte *p =
static_cast<std::byte *
>(array);
314 if (!str.has_value()) {
315 std::fill_n(p, nelems * elem_size,
static_cast<std::byte
>(0));
320 if (!opt_items.has_value() || opt_items->size() != (
size_t)nelems)
return false;
322 for (
auto item : *opt_items) {
340 for (
size_t i = 0; i != this->
save.length; i++) {
342 switch (this->
save.conv.mem) {
350 default: NOT_REACHED();
352 if (i != 0) result +=
',';
353 format_append(result,
"{}", v);
358std::string OneOfManySettingDesc::FormatSingleValue(uint
id)
const
360 if (
id >= this->
many.size()) {
361 return fmt::format(
"{}",
id);
363 return std::string{this->
many[id]};
368 uint
id = (uint)this->
Read(
object);
369 return this->FormatSingleValue(
id);
374 uint bitmask = (uint)this->
Read(
object);
381 if (!result.empty()) result +=
'|';
382 result += this->FormatSingleValue(
id);
397 if (!value.has_value()) {
408 return static_cast<int32_t
>(*value);
416 if (!r.has_value() && this->many_cnvt !=
nullptr) r = this->
many_cnvt(str);
417 if (r.has_value())
return *r;
428 if (r.has_value())
return *r;
439 if (r.has_value())
return *r;
454 return this->get_title_cb !=
nullptr ? this->get_title_cb(*
this) : this->
str;
463 return this->get_help_cb !=
nullptr ? this->get_help_cb(*
this) : this->
str_help;
473 if (this->get_value_params_cb !=
nullptr) {
474 return this->get_value_params_cb(*
this, value);
478 return {value != 0 ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF, {}};
482 auto [min_val, _] = this->
GetRange();
483 return {this->
str_val - min_val + value, value};
504 return this->get_range_cb !=
nullptr ? this->get_range_cb(*
this) : std::tuple(this->
min, this->
max);
516 this->
Write(
object, val);
530 auto [min_val, max_val] = this->
GetRange();
536 switch (this->
save.conv.mem) {
548 val =
Clamp(val, min_val, max_val);
549 }
else if (val < min_val || val >
static_cast<int32_t
>(max_val)) {
558 uint32_t uval =
static_cast<uint32_t
>(val);
562 uval =
ClampU(uval, min_val, max_val);
563 }
else if (uval <
static_cast<uint32_t
>(min_val) || uval > max_val) {
568 val =
static_cast<int32_t
>(uval);
573 default: NOT_REACHED();
596 return static_cast<int32_t
>(
ReadValue(ptr, this->
save.conv.mem));
608 if (this->
max_length == 0 || str.size() < this->max_length)
return;
613 str.erase(this->
max_length - 1, std::string::npos);
646static void IniLoadSettings(
IniFile &ini,
const SettingTable &settings_table, std::string_view grpname,
void *
object,
bool only_startup)
651 for (
auto &desc : settings_table) {
654 if (sd->
startup != only_startup)
continue;
657 std::string s{ sd->
GetName() };
658 auto sc = s.find(
'.');
659 if (sc != std::string::npos) {
660 group = ini.
GetGroup(s.substr(0, sc));
661 if (group ==
nullptr) group = group_def;
662 s = s.substr(sc + 1);
668 if (group !=
nullptr) item = group->
GetItem(s);
669 if (item ==
nullptr && group != group_def && group_def !=
nullptr) {
674 if (item ==
nullptr) {
678 if (sc != std::string::npos) {
679 if (group = ini.
GetGroup(s.substr(0, sc)); group !=
nullptr) item = group->
GetItem(s.substr(sc + 1));
695 std::string str{(item ==
nullptr) ? this->
def : item->
value.value_or(
"")};
697 this->
Write(
object, str);
702 std::optional<std::string_view> str;
703 if (item !=
nullptr) {
705 }
else if (!this->
def.empty()) {
731static void IniSaveSettings(
IniFile &ini,
const SettingTable &settings_table, std::string_view grpname,
void *
object,
bool)
733 IniGroup *group_def =
nullptr, *group;
735 for (
auto &desc : settings_table) {
743 std::string s{ sd->
GetName() };
744 auto sc = s.find(
'.');
745 if (sc != std::string::npos) {
747 s = s.substr(sc + 1);
753 IniItem &item = group->GetOrCreateItem(s);
765 if (IsSignedVarMemType(this->
save.conv)) {
766 i = this->
Read(
object);
768 i = (uint32_t)this->
Read(
object);
770 return fmt::format(
"{}", i);
775 bool val = this->
Read(
object) != 0;
776 return val ?
"true" :
"false";
781 int32_t item_value =
static_cast<int32_t
>(this->
ParseValue(*item->
value));
782 int32_t object_value = this->
Read(
object);
783 return item_value == object_value;
788 int32_t object_value = this->
Read(
object);
799 const std::string &str = this->
Read(
object);
800 switch (this->
save.conv.mem) {
807 return fmt::format(
"\"{}\"", str);
809 default: NOT_REACHED();
819 const std::string &str = this->
Read(
object);
820 return item->
value->compare(str) == 0;
825 const std::string &str = this->
Read(
object);
826 return this->
def == str;
865 if (group ==
nullptr)
return;
870 if (!item.
name.empty()) list.push_back(item.
name);
888 for (
const auto &iter : list) {
977static void AILoadConfig(
const IniFile &ini, std::string_view grpname)
982 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
987 if (group ==
nullptr)
return;
989 CompanyID c = CompanyID::Begin();
995 if (item.
name !=
"none") {
996 Debug(script, 0,
"The AI by the name '{}' was no longer found, and removed from the list.", item.
name);
1002 if (c >= MAX_COMPANIES)
break;
1006static void GameLoadConfig(
const IniFile &ini, std::string_view grpname)
1014 if (group ==
nullptr || group->
items.empty())
return;
1022 if (item.
name !=
"none") {
1023 Debug(script, 0,
"The GameScript by the name '{}' was no longer found, and removed from the list.", item.
name);
1038 if (
const IniItem *item = group->
GetItem(
"graphicsset"); item !=
nullptr && item->
value) BaseGraphics::ini_data.name = *item->
value;
1041 if (
const IniGroup *group = ini.
GetGroup(
"graphicsset"); group !=
nullptr) {
1043 if (
const IniItem *item = group->
GetItem(
"name"); item !=
nullptr && item->
value) BaseGraphics::ini_data.name = *item->
value;
1045 if (
const IniItem *item = group->
GetItem(
"shortname"); item !=
nullptr && item->
value && item->
value->size() == 8) {
1047 if (val.has_value()) {
1056 if (
const IniItem *item = group->
GetItem(
"extra_version"); item !=
nullptr && item->
value) {
1058 if (val.has_value()) {
1059 BaseGraphics::ini_data.extra_version = *val;
1067 if (
const IniItem *item = group->
GetItem(
"extra_params"); item !=
nullptr && item->
value) {
1069 if (params.has_value()) {
1070 BaseGraphics::ini_data.extra_params = params.value();
1092 if (group ==
nullptr)
return list;
1096 std::unique_ptr<GRFConfig> c{};
1098 std::array<uint8_t, 4> grfid_buf;
1100 std::string_view item_name = item.
name;
1101 bool has_md5sum =
false;
1104 auto grfid_pos = item_name.find(
"|");
1105 if (grfid_pos != std::string_view::npos) {
1106 std::string_view grfid_str = item_name.substr(0, grfid_pos);
1109 item_name = item_name.substr(grfid_pos + 1);
1111 auto md5sum_pos = item_name.find(
"|");
1112 if (md5sum_pos != std::string_view::npos) {
1113 std::string_view md5sum_str = item_name.substr(0, md5sum_pos);
1116 if (has_md5sum) item_name = item_name.substr(md5sum_pos + 1);
1119 GrfID grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
1122 if (s !=
nullptr) c = std::make_unique<GRFConfig>(*s);
1126 if (s !=
nullptr) c = std::make_unique<GRFConfig>(*s);
1130 std::string filename = std::string(item_name);
1132 if (c ==
nullptr) c = std::make_unique<GRFConfig>(filename);
1135 if (item.
value.has_value() && !item.
value->empty()) {
1137 if (params.has_value()) {
1138 c->SetParams(params.value());
1150 reason = STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND;
1152 reason = STR_CONFIG_ERROR_INVALID_GRF_UNSAFE;
1154 reason = STR_CONFIG_ERROR_INVALID_GRF_SYSTEM;
1156 reason = STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE;
1158 reason = STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN;
1162 GetEncodedString(STR_CONFIG_ERROR_INVALID_GRF, filename.empty() ? item.
name : filename, reason),
1168 auto found = std::ranges::find_if(list, [&c](
const auto &gc) {
return gc->ident.grfid == c->ident.grfid; });
1169 if (found != std::end(list)) {
1171 GetEncodedString(STR_CONFIG_ERROR_DUPLICATE_GRFID, c->filename, (*found)->filename),
1187 list.push_back(std::move(c));
1196 if (group ==
nullptr)
return IFV_0;
1198 auto version_number = group->
GetItem(
"ini_version");
1200 if (version_number ==
nullptr || !version_number->value.has_value())
return IFV_0;
1202 uint32_t version = 0;
1203 std::from_chars(version_number->value->data(), version_number->value->data() + version_number->value->size(), version);
1208static void AISaveConfig(
IniFile &ini, std::string_view grpname)
1213 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
1228static void GameSaveConfig(
IniFile &ini, std::string_view grpname)
1265 if (used_set ==
nullptr)
return;
1273 const GRFConfig *extra_cfg = used_set->GetExtraConfig();
1274 if (extra_cfg !=
nullptr && !extra_cfg->
param.empty()) {
1281static void GRFSaveConfig(
IniFile &ini, std::string_view grpname,
const GRFConfigList &list)
1286 for (
const auto &c : list) {
1287 std::string key = fmt::format(
"{:08X}|{}|{}",
std::byteswap(c->ident.grfid),
1294static void HandleSettingDescs(
IniFile &generic_ini,
IniFile &private_ini,
IniFile &secrets_ini, SettingDescProc *proc, SettingDescProcList *proc_list,
bool only_startup =
false)
1296 proc(generic_ini, _misc_settings,
"misc",
nullptr, only_startup);
1297#if defined(_WIN32) && !defined(DEDICATED)
1298 proc(generic_ini, _win32_settings,
"win32",
nullptr, only_startup);
1313 proc(generic_ini, _currency_settings,
"currency", &
GetCustomCurrency(), only_startup);
1314 proc(generic_ini, _company_settings,
"company", &
_settings_client.company, only_startup);
1316 if (!only_startup) {
1320 proc_list(private_ini,
"server_authorized_keys",
_settings_client.network.server_authorized_keys);
1321 proc_list(private_ini,
"rcon_authorized_keys",
_settings_client.network.rcon_authorized_keys);
1322 proc_list(private_ini,
"admin_authorized_keys",
_settings_client.network.admin_authorized_keys);
1337 for (
auto &desc : table) {
1341 std::string s{ sd->
GetName() };
1342 auto sc = s.find(
'.');
1343 if (sc == std::string::npos)
continue;
1346 if (group ==
nullptr)
continue;
1347 s = s.substr(sc + 1);
1378 *old_item =
nullptr;
1382 if (igroup ==
nullptr)
return false;
1388 if (tmp_old_item ==
nullptr)
return false;
1394 if (new_item !=
nullptr)
return false;
1396 *old_item = tmp_old_item;
1413 IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1436 if (network !=
nullptr) {
1437 const IniItem *use_relay_service = network->
GetItem(
"use_relay_service");
1438 if (use_relay_service !=
nullptr) {
1439 if (use_relay_service->
value ==
"never") {
1441 }
else if (use_relay_service->
value ==
"ask") {
1443 }
else if (use_relay_service->
value ==
"allow") {
1458 static constexpr std::initializer_list<std::string_view> _old_autosave_interval{
"off"sv,
"monthly"sv,
"quarterly"sv,
"half year"sv,
"yearly"sv};
1461 switch (old_value) {
1474 _settings_client.gui.right_click_wnd_close = old_value.value_or(
false) ? RightClickClose::Yes : RightClickClose::No;
1484 AILoadConfig(generic_ini,
"ai_players");
1485 GameLoadConfig(generic_ini,
"game_scripts");
1510 IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1516 if (
IniGroup *group = private_ini.
GetGroup(
"private"); group !=
nullptr) group->
comment =
"; This file possibly contains private information which can identify you as person.\n";
1517 if (
IniGroup *group = secrets_ini.
GetGroup(
"secrets"); group !=
nullptr) group->
comment =
"; Do not share this file with others, not even if they claim to be technical support.\n; This file contains saved passwords and other secrets that should remain private to you!\n";
1519 if (generic_version ==
IFV_0) {
1541 if (game_creation !=
nullptr) {
1542 game_creation->
RemoveItem(
"generation_seed");
1549 if (network !=
nullptr) {
1558 AISaveConfig(generic_ini,
"ai_players");
1559 GameSaveConfig(generic_ini,
"game_scripts");
1584 if (group.
name.starts_with(
"preset-")) {
1585 list.push_back(group.
name.substr(7));
1600 std::string section(
"preset-");
1601 section += config_name;
1617 std::string section(
"preset-");
1618 section += config_name;
1621 GRFSaveConfig(ini, section, config);
1631 std::string section(
"preset-");
1632 section += config_name;
1647 int32_t oldval = this->
Read(
object);
1650 if (oldval == newval)
return;
1652 this->
Write(
object, newval);
1680 if (sd->
GetName() == name)
return sd;
1684 std::string short_name_suffix = std::string{
"." }.append(name);
1688 if (sd->
GetName().ends_with(short_name_suffix))
return sd;
1704 saveloads.push_back(sd->
save);
1715 static const SettingTable saveload_settings_tables[] = {
1716 _difficulty_settings,
1719 _linkgraph_settings,
1721 _pathfinding_settings,
1725 static std::vector<SettingVariant> settings_table;
1727 if (settings_table.empty()) {
1728 for (
auto &saveload_settings_table : saveload_settings_tables) {
1729 for (
auto &saveload_setting : saveload_settings_table) {
1730 settings_table.push_back(saveload_setting);
1735 return settings_table;
1746 static const std::string_view company_prefix =
"company.";
1747 if (name.starts_with(company_prefix)) name.remove_prefix(company_prefix.size());
1761 if (sd !=
nullptr)
return sd;
1765 if (sd !=
nullptr)
return sd;
1769 if (sd !=
nullptr)
return sd;
1782 std::vector<const SettingDesc *> collection;
1785 for (
const auto &desc : table) {
1787 if (!func(*sd))
continue;
1789 collection.push_back(sd);
1858 return Command<Commands::ChangeCompanySetting>::Post(setting->
GetName(), value);
1877 if (force_newgame) {
1884 return Command<Commands::ChangeSetting>::Post(setting->
GetName(), value);
1897 for (
auto &desc : _company_settings) {
1910 for (
auto &desc : _company_settings) {
1919 if (old_value != new_value) Command<Commands::ChangeCompanySetting>::SendNet(STR_NULL,
_local_company, sd->
GetName(), new_value);
1955 this->
Write(
object, newval);
1963void IConsoleSetSetting(std::string_view name, std::string_view value,
bool force_newgame)
1972 bool success =
true;
1995void IConsoleSetSetting(std::string_view name,
int value)
1998 assert(sd !=
nullptr);
2023 auto [min_val, max_val] = int_setting->
GetRange();
2030static void IConsoleListSettingsTable(
const SettingTable &table, std::string_view prefilter)
2032 for (
auto &desc : table) {
2035 if (!prefilter.empty() && sd->
GetName().find(prefilter) == std::string::npos)
continue;
2050 IConsoleListSettingsTable(table, prefilter);
2053 IConsoleListSettingsTable(table, prefilter);
2056 IConsoleListSettingsTable(table, prefilter);
2062ScriptConfigSettings::ScriptConfigSettings()
2080 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
2081 if (other.
ai[c] !=
nullptr) {
2082 this->
ai[c] = std::make_unique<AIConfig>(*other.
ai[c]);
2085 if (other.
game !=
nullptr) {
2086 this->
game = std::make_unique<GameConfig>(*other.
game);
AIConfig stores the configuration settings of every AI.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr enable_if_t< is_integral_v< T >, T > byteswap(T x) noexcept
Custom implementation of std::byteswap; remove once we build with C++23.
AI instantion of script configuration.
static AIConfig * GetConfig(CompanyID company, ScriptSettingSource source=ScriptSettingSource::Default)
Get the AI configuration of specific company.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Common return value for all commands.
IniFile to store a configuration.
Game script instantion of script configuration.
static GameConfig * GetConfig(ScriptSettingSource source=ScriptSettingSource::Default)
Get the script configuration.
@ ForceNewGame
Get the newgame Script config.
bool HasScript() const
Is this config attached to an Script?
void Change(std::optional< std::string_view > name, int version=-1, bool force_exact_match=false)
Set another Script to be loaded in this slot.
void StringToSettings(std::string_view value)
Convert a string which is stored in the config file or savegames to custom settings of this Script.
const std::string & GetName() const
Get the name of the Script.
std::string SettingsToString() const
Convert the custom settings to a string that can be stored in the config file or savegames.
Parse data from a string / buffer.
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
static const std::string_view WHITESPACE_NO_NEWLINE
ASCII whitespace characters, excluding new-line.
bool ReadIf(std::string_view str)
Check whether the next data matches 'str', and skip it.
void SkipUntilCharNotIn(std::string_view chars)
Skip 8-bit chars, while they are in 'chars', until they are not.
std::string_view ReadUntilCharIn(std::string_view chars)
Read 8-bit chars, while they are not in 'chars', until they are; and advance reader.
static constexpr int SECONDS_PER_DAY
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Execute
execute the given command
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
Configuration options of the network stuff.
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
void IConsolePrint(ExtendedTextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Console functions used outside of the console code.
static const TextColour CC_HELP
Colour for help lines.
static const TextColour CC_INFO
Colour for information lines.
static const TextColour CC_DEFAULT
Default colour of the console.
static const TextColour CC_ERROR
Colour for error lines.
void ResetCurrencies(bool preserve_custom)
Will fill _currency_specs array with default values from _origin_currency_specs Called only from newg...
Functions to handle different currencies.
CurrencySpec & GetCustomCurrency()
Get the custom currency.
void DebugReconsiderSendRemoteMessages()
Reconsider whether we need to send debug messages to either NetworkAdminConsole or IConsolePrint.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Functions related to errors.
std::list< ErrorMessageData > ErrorList
Define a queue with errors.
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
void ShowFirstError()
Show the first error of the queue.
bool FioCheckFileExists(std::string_view filename, Subdirectory subdir)
Check whether the given file exists.
std::string _config_file
Configuration file of OpenTTD.
Functions for standard in/out file operations.
@ NewGrf
Subdirectory for all NewGRFs.
@ None
A path without any base directory.
Declarations for savegames operations.
fluid_settings_t * settings
FluidSynth settings handle.
GameConfig stores the configuration settings of every Game.
Gamelog _gamelog
Gamelog instance.
Functions to be called to log fundamental changes to the game.
@ Setting
Setting changed.
Functions related to world/map generation.
@ LG_ORIGINAL
The original landscape generator.
static const uint CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
Value for custom sea level in difficulty settings.
static const uint CUSTOM_SEA_LEVEL_MIN_PERCENTAGE
Minimum percentage a user can specify for custom sea level.
Types related to reading/writing '*.ini' files.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
StringList _network_host_list
The servers we know.
bool _networking
are we in networking mode?
StringList _network_ban_list
The banned clients.
bool _network_server
network-server is active
StringList _network_bind_list
The addresses to bind on.
Basic functions/variables used all over the place.
Network functions used by other parts of OpenTTD.
@ Public
The game is publicly accessible.
@ Local
Do not communicate with the game coordinator.
void BadgeClassSaveConfig(IniFile &ini)
Save badge column preferences.
void BadgeClassLoadConfig(const IniFile &ini)
Load badge column preferences.
Functions related to NewGRF badge configuration.
GRFConfigList _grfconfig_static
First item in list of static GRF set up.
std::string GRFBuildParamList(const GRFConfig &c)
Build a string containing space separated parameter values.
GRFConfigList _grfconfig_newgame
First item in list of default GRF set up.
bool FillGRFDetails(GRFConfig &config, bool is_static, Subdirectory subdir)
Find the GRFID of a given grf, and calculate its md5sum.
const GRFConfig * FindGRFConfig(GrfID grfid, FindGRFConfigMode mode, const MD5Hash *md5sum, uint32_t desired_version)
Find a NewGRF in the scanned list.
Functions to find and configure NewGRFs.
@ NotFound
GRF file was not found in the local cache.
@ Invalid
GRF is unusable with this version of OpenTTD.
@ Static
GRF file is used statically (can be used in any MP game).
@ System
GRF file is an openttd-internal system grf.
@ Unsafe
GRF file is unsafe for static usage.
@ Exact
Only find Grfs matching md5sum.
@ NewestValid
Find newest Grf, ignoring Grfs with GRFConfigFlag::Invalid set.
uint32_t GrfID
The unique identifier of a NewGRF.
@ Editor
In the scenario editor.
void PickerSaveConfig(IniFile &ini)
Save favourites of all registered Pickers to config.
void PickerLoadConfig(const IniFile &ini)
Load favourites of all registered Pickers from config.
Declaration of OTTD revision dependent variables.
A number of safeguards to prevent using unsafe methods.
void WriteValue(void *ptr, VarMemType conv, int64_t val)
Write the value of a setting.
int64_t ReadValue(const void *ptr, VarMemType conv)
Return a signed-long version of the value of a setting.
VarMemType
The types/structures of data we have in memory.
@ U64
A 64 bit unsigned int.
@ U8
A 8 bit unsigned int.
@ StrQ
string pointer enclosed in quotes
@ Null
useful to write zeros in savegame.
@ I16
A 16 bit signed int.
@ U32
A 32 bit unsigned int.
@ I32
A 32 bit signed int.
@ I64
A 64 bit signed int.
@ U16
A 16 bit unsigned int.
void * GetVariableAddress(const void *object, const SaveLoad &sld)
Get the address of the variable.
bool SlIsObjectCurrentlyValid(SaveLoadVersion version_from, SaveLoadVersion version_to)
Checks if some version from/to combination falls within the range of the active savegame version.
constexpr size_t SlVarSize(VarMemType type)
Return expect size in bytes of a VarType.
static void GraphicsSetLoadConfig(IniFile &ini)
Load BaseGraphics set selection and configuration.
void HandleOldDiffCustom(bool savegame)
Reading of the old diff_custom array and transforming it to the new format.
static bool LoadIntList(std::optional< std::string_view > str, void *array, int nelems, VarMemType type)
Load parsed string-values into an integer-array (intlist).
void SyncCompanySettings()
Sync all company settings in a multiplayer game.
void IniLoadWindowSettings(IniFile &ini, std::string_view grpname, WindowDesc *desc)
Load a WindowDesc from config.
static void RemoveEntriesFromIni(IniFile &ini, const SettingTable &table)
Remove all entries from a settings table from an ini-file.
void SaveGRFPresetToConfig(std::string_view config_name, GRFConfigList &config)
Save a NewGRF configuration with a preset name.
StringList GetGRFPresetList()
Get the list of known NewGrf presets.
static void ValidateSettings()
Checks if any settings are set to incorrect values, and sets them to correct values in that case.
bool IsConversionNeeded(const ConfigIniFile &ini, const std::string &group, const std::string &old_var, const std::string &new_var, const IniItem **old_item)
Check whether a conversion should be done, and based on what old setting information.
void IConsoleGetSetting(std::string_view name, bool force_newgame)
Output value of a specific setting to the console.
std::string _secrets_file
Secrets configuration file of OpenTTD.
static GRFConfigList GRFLoadConfig(const IniFile &ini, std::string_view grpname, bool is_static)
Load a GRF configuration.
std::string _favs_file
Picker favourites configuration file of OpenTTD.
static ErrorList _settings_error_list
Errors while loading minimal settings.
void DeleteGRFPresetFromConfig(std::string_view config_name)
Delete a NewGRF configuration by preset name.
void SetDefaultCompanySettings(CompanyID cid)
Set the company settings for a new company to their default values.
static void IniLoadSettingList(IniFile &ini, std::string_view grpname, StringList &list)
Loads all items from a 'grpname' section into a list The list parameter can be a nullptr pointer,...
std::vector< const SettingDesc * > GetFilteredSettingCollection(std::function< bool(const SettingDesc &desc)> func)
Get a collection of settings matching a custom filter.
void LoadFromConfig(bool startup)
Load the values from the configuration files.
GRFConfigList LoadGRFPresetFromConfig(std::string_view config_name)
Load a NewGRF configuration by preset-name.
bool SetSettingValue(const IntSettingDesc *sd, int32_t value, bool force_newgame)
Top function to save the new value of an element of the Settings struct.
void SaveToConfig()
Save the values to the configuration file.
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
void PrepareOldDiffCustom()
Prepare for reading and old diff_custom by zero-ing the memory.
static void IniLoadSettings(IniFile &ini, const SettingTable &settings_table, std::string_view grpname, void *object, bool only_startup)
Load values from a group of an IniFile structure into the internal representation.
void GetSaveLoadFromSettingTable(SettingTable settings, std::vector< SaveLoad > &saveloads)
Get the SaveLoad for all settings in the settings table.
static void GraphicsSetSaveConfig(IniFile &ini)
Save BaseGraphics set selection and configuration.
static std::optional< std::vector< uint32_t > > ParseIntList(std::string_view str)
Parse a string into a vector of uint32s.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
CommandCost CmdChangeCompanySetting(DoCommandFlags flags, const std::string &name, int32_t value)
Change one of the per-company settings.
IniFileVersion
Ini-file versions.
@ IFV_0
0 All versions prior to introduction.
@ IFV_AUTOSAVE_RENAME
5 PR#11143 Renamed values of autosave to be in minutes.
@ IFV_LINKGRAPH_SECONDS
3 PR#10610 Store linkgraph update intervals in seconds instead of days.
@ IFV_REMOVE_GENERATION_SEED
7 PR#11927 Remove "generation_seed" from configuration.
@ IFV_MAX_VERSION
Highest possible ini-file version.
@ IFV_NETWORK_PRIVATE_SETTINGS
4 PR#10762 Move use_relay_service to private settings.
@ IFV_DEFAULT_RAIL_ROAD
8 PR#15585 Update default rail type setting to support road and tram tiles
@ IFV_GAME_TYPE
2 PR#9515 Convert server_advertise to server_game_type.
@ IFV_RIGHT_CLICK_CLOSE
6 PR#10204 Add alternative right click to close windows setting.
@ IFV_PRIVATE_SECRETS
1 PR#9298 Moving of settings from openttd.cfg to private.cfg / secrets.cfg.
SettingTable GetSaveLoadSettingTable()
Create a single table with all settings that should be stored/loaded in the savegame.
void IConsoleListSettings(std::string_view prefilter)
List all settings and their value to the console.
static void IniSaveSettingList(IniFile &ini, std::string_view grpname, StringList &list)
Saves all items from a list into the 'grpname' section The list parameter can be a nullptr pointer,...
const uint16_t INIFILE_VERSION
Current ini-file version of OpenTTD.
static void IniSaveSettings(IniFile &ini, const SettingTable &settings_table, std::string_view grpname, void *object, bool)
Save the values of settings to the inifile.
static auto & SecretSettingTables()
List of all the secrets setting tables.
std::string _private_file
Private configuration file of OpenTTD.
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
static auto & PrivateSettingTables()
List of all the private setting tables.
static void SaveVersionInConfig(IniFile &ini)
Save the version of OpenTTD to the ini file.
static std::optional< uint32_t > LookupManyOfMany(std::span< const std::string_view > many, std::string_view str)
Find the set-integer value MANYofMANY type in a string.
static const SettingDesc * GetSettingFromName(std::string_view name, const SettingTable &settings)
Given a name of setting, return a setting description from the table.
static auto & GenericSettingTables()
List of all the generic setting tables.
void IniSaveWindowSettings(IniFile &ini, std::string_view grpname, WindowDesc *desc)
Save a WindowDesc to config.
static const SettingDesc * GetCompanySettingFromName(std::string_view name)
Given a name of setting, return a company setting description of it.
CommandCost CmdChangeSetting(DoCommandFlags flags, const std::string &name, int32_t value)
Network-safe changing of settings (server-only).
ClientSettings _settings_client
The current settings for this game.
Command definitions related to settings.
Functions related to setting/changing the settings.
@ NotInSave
Do not save with savegame, basically client-based.
@ Sandbox
This setting is a sandbox setting.
@ SceneditOnly
This setting can only be changed in the scenario editor.
@ PerCompany
This setting can be different for each company (saved in company struct).
@ NewgameOnly
This setting cannot be changed in a game.
@ GuiZeroIsSpecial
A value of zero is possible and has a custom string (the one after "strval").
@ NoNetwork
This setting does not apply to network games; it may not be changed during the game.
@ NotInConfig
Do not save to config file.
@ GuiDropdown
The value represents a limited number of string-options (internally integer) presented as dropdown.
@ SceneditToo
This setting can be changed in the scenario editor (only makes sense when SettingFlag::NewgameOnly is...
@ NoNetworkSync
Do not synchronize over network (but it is saved if SettingFlag::NotInSave is not set).
@ NetworkOnly
This setting only applies to network games.
SettingType
Type of settings for filtering.
@ ST_CLIENT
Client setting.
@ ST_COMPANY
Company setting.
static constexpr const SettingDesc * GetSettingDesc(const SettingVariant &desc)
Helper to convert the type of the iterated settings description to a pointer to it.
Definition of the configuration tables of the settings.
GameSettings & GetGameSettings()
Get the settings-object applicable for the current situation: the newgame settings when we're in the ...
DefaultRailRoadType
How to select the default rail/road types.
Definition of base types and functions in a cross-platform compatible way.
bool ConvertHexToBytes(std::string_view hex, std::span< uint8_t > bytes)
Convert a hex-string to a byte-array, while validating it was actually hex.
void StrMakeValidInPlace(char *str, StringValidationSettings settings)
Scans the string for invalid characters and replaces them with a question mark '?
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
Functions related to low-level strings.
std::vector< std::string > StringList
Type for a list of strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
std::string name
The name of the base set.
uint32_t shortname
Four letter short variant of the name.
std::string FormatValue(const void *object) const override
Format the value of the setting associated with this object.
static std::optional< bool > ParseSingleValue(std::string_view str)
Find whether a string was a boolean true or a boolean false.
int32_t ParseValue(std::string_view str) const override
Convert a string representation (external) of an integer-like setting to an integer.
All settings that are only important for the local client.
CompanySettings settings
settings specific for each company
Information about GRF, used in the game and (part of it) in savegames.
uint32_t version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
std::vector< uint32_t > param
GRF parameters.
All settings together for the game.
All data of a graphics set.
Ini file that supports both loading and saving.
bool SaveToDisk(const std::string &filename)
Save the Ini file's data to the disk.
IniFile(const IniGroupNameList &list_group_names={})
Create a new ini file with given group names.
A group within an ini file.
const IniItem * GetItem(std::string_view name) const
Get the item with the given name.
std::string comment
comment for group
void Clear()
Clear all items in the group.
void RemoveItem(std::string_view name)
Remove the item with the given name.
std::string name
name of group
IniItem & CreateItem(std::string_view name)
Create an item with the given name.
IniItem & GetOrCreateItem(std::string_view name)
Get the item with the given name, and if it doesn't exist create a new item.
std::list< IniItem > items
all items in the group
A single "line" in an ini file.
std::optional< std::string > value
The value of this item.
std::string name
The name of this item.
void SetValue(std::string_view value)
Replace the current value with another value.
std::list< IniGroup > groups
all groups in the ini
void RemoveGroup(std::string_view name)
Remove the group with the given name.
const IniGroup * GetGroup(std::string_view name) const
Get the group with the given name.
void LoadFromDisk(std::string_view filename, Subdirectory subdir)
Load the Ini file's data from the disk.
IniGroup & GetOrCreateGroup(std::string_view name)
Get the group with the given name, and if it doesn't exist create a new group.
Base integer type, including boolean, settings.
static std::optional< int32_t > ParseSingleValue(std::string_view str, int32_t min, uint32_t max)
Find whether a string was a valid int setting.
StringID str_help
(Translated) string with help text; gui only.
StringID str_val
(Translated) first string describing the value.
void MakeValueValid(int32_t &value) const
Make the value valid given the limitations of this setting.
void ResetToDefault(void *object) const override
Reset the setting to its default value.
std::string FormatValue(const void *object) const override
Format the value of the setting associated with this object.
int32_t def
default value given when none is present
std::tuple< int32_t, uint32_t > GetRange() const
Get the min/max range for the setting.
StringID GetTitle() const
Get the title of the setting.
void ChangeValue(const void *object, int32_t newvalue) const
Handle changing a value.
uint32_t max
maximum values
GetDefaultValueCallback * get_def_cb
Callback to set the correct default value.
bool IsSameValue(const IniItem *item, void *object) const override
Check whether the value in the Ini item is the same as is saved in this setting in the object.
int32_t min
minimum values
PreChangeCheck * pre_check
Callback to check for the validity of the setting.
int32_t GetDefaultValue() const
Get the default value of the setting.
void Write(const void *object, int32_t value) const
Set the value of a setting.
StringID GetHelp() const
Get the help text of the setting.
virtual bool IsBoolSetting() const
Check whether this setting is a boolean type setting.
PostChangeCallback * post_callback
Callback when the setting has been changed.
StringID str
(translated) string with descriptive text; gui and console
void MakeValueValidAndWrite(const void *object, int32_t value) const
Make the value valid and then write it to the setting.
std::pair< StringParameter, StringParameter > GetValueParams(int32_t value) const
Get parameters for drawing the value of the setting.
int32_t Read(const void *object) const
Read the integer from the the actual setting.
virtual int32_t ParseValue(std::string_view str) const
Convert a string representation (external) of an integer-like setting to an integer.
bool IsDefaultValue(void *object) const override
Check whether the value is the same as the default value.
void ParseValue(const IniItem *item, void *object) const override
Parse/read the value from the Ini item into the setting associated with this object.
void ResetToDefault(void *object) const override
Reset the setting to its default value.
bool IsSameValue(const IniItem *item, void *object) const override
Check whether the value in the Ini item is the same as is saved in this setting in the object.
std::string_view def
default value given when none is present
std::string FormatValue(const void *object) const override
Convert a list to a string representation.
bool IsDefaultValue(void *object) const override
Check whether the value is the same as the default value.
int32_t ParseValue(std::string_view str) const override
Convert a string representation (external) of an integer-like setting to an integer.
std::string FormatValue(const void *object) const override
Format the value of the setting associated with this object.
OnConvert * many_cnvt
callback procedure when loading value mechanism fails
std::string FormatValue(const void *object) const override
Format the value of the setting associated with this object.
static std::optional< uint32_t > ParseSingleValue(std::string_view str, std::span< const std::string_view > many)
Find the index value of a ONEofMANY type in a string.
std::vector< std::string_view > many
possible values for this type
int32_t ParseValue(std::string_view str) const override
Convert a string representation (external) of an integer-like setting to an integer.
static Company * Get(auto index)
static bool IsValidID(auto index)
SaveLoadVersion version_to
Save/load the variable before this savegame version.
VarType conv
Type of the variable to be saved; this field combines both FileVarType and MemVarType.
SaveLoadVersion version_from
Save/load the variable starting from this savegame version.
Container for AI and Game script configuration.
std::unique_ptr< class GameConfig > game
settings for gamescript
TypedIndexContainer< std::array< std::unique_ptr< class AIConfig >, MAX_COMPANIES >, CompanyID > ai
settings per company
~ScriptConfigSettings()
Needs to be manually defined due to incomplete definition of types in the header.
Iterable ensemble of each set bit in a value.
Properties of config file settings.
virtual void ParseValue(const IniItem *item, void *object) const =0
Parse/read the value from the Ini item into the setting associated with this object.
bool IsEditable(bool do_command=false) const
Check whether the setting is editable in the current gamemode.
SettingFlags flags
Handles how a setting would show up in the GUI (text/currency, etc.).
virtual bool IsStringSetting() const
Check whether this setting is an string type setting.
SettingType GetType() const
Return the type of the setting.
constexpr const std::string & GetName() const
Get the name of this setting.
bool startup
Setting has to be loaded directly at startup?.
virtual std::string FormatValue(const void *object) const =0
Format the value of the setting associated with this object.
const struct StringSettingDesc * AsStringSetting() const
Get the setting description of this setting as a string setting.
virtual bool IsSameValue(const IniItem *item, void *object) const =0
Check whether the value in the Ini item is the same as is saved in this setting in the object.
SaveLoad save
Internal structure (going to savegame, parts to config).
virtual bool IsIntSetting() const
Check whether this setting is an integer type setting.
const struct IntSettingDesc * AsIntSetting() const
Get the setting description of this setting as an integer setting.
const std::string & Read(const void *object) const
Read the string from the the actual setting.
std::string_view def
Default value given when none is present.
void Write(const void *object, std::string_view str) const
Write a string to the actual setting.
uint32_t max_length
Maximum length of the string, 0 means no maximum length.
PreChangeCheck * pre_check
Callback to check for the validity of the setting.
void ChangeValue(const void *object, std::string &&newval) const
Handle changing a string value.
void MakeValueValid(std::string &str) const
Make the value valid given the limitations of this setting.
bool IsSameValue(const IniItem *item, void *object) const override
Check whether the value in the Ini item is the same as is saved in this setting in the object.
bool IsDefaultValue(void *object) const override
Check whether the value is the same as the default value.
PostChangeCallback * post_callback
Callback when the setting has been changed.
void ResetToDefault(void *object) const override
Reset the setting to its default value.
std::string FormatValue(const void *object) const override
Format the value of the setting associated with this object.
void ParseValue(const IniItem *item, void *object) const override
Parse/read the value from the Ini item into the setting associated with this object.
Container of a variable's characteristics about a variable's storage.
VarMemType mem
The way of storing data in memory.
Default settings for vehicles.
High level window description.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Window functions not directly related to making/drawing windows.