OpenTTD Source  13.2.1
settings.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
24 #include "stdafx.h"
25 #include <charconv>
26 #include "settings_table.h"
27 #include "debug.h"
28 #include "currency.h"
29 #include "network/network.h"
30 #include "network/network_func.h"
31 #include "network/core/config.h"
32 #include "command_func.h"
33 #include "console_func.h"
34 #include "genworld.h"
35 #include "window_func.h"
36 #include "company_func.h"
37 #include "rev.h"
38 #include "error.h"
39 #include "gamelog.h"
40 #include "settings_func.h"
41 #include "ini_type.h"
42 #include "ai/ai_config.hpp"
43 #include "game/game_config.hpp"
44 #include "newgrf_config.h"
45 #include "fios.h"
46 #include "fileio_func.h"
47 #include "settings_cmd.h"
48 
49 #include "table/strings.h"
50 
51 #include "safeguards.h"
52 
57 std::string _config_file;
58 std::string _private_file;
59 std::string _secrets_file;
60 
61 typedef std::list<ErrorMessageData> ErrorList;
63 
74 static auto &GenericSettingTables()
75 {
76  static const SettingTable _generic_setting_tables[] = {
77  _difficulty_settings,
78  _economy_settings,
79  _game_settings,
80  _gui_settings,
81  _linkgraph_settings,
82  _locale_settings,
83  _multimedia_settings,
84  _network_settings,
85  _news_display_settings,
86  _pathfinding_settings,
87  _script_settings,
88  _world_settings,
89  };
90  return _generic_setting_tables;
91 }
92 
96 static auto &PrivateSettingTables()
97 {
98  static const SettingTable _private_setting_tables[] = {
99  _network_private_settings,
100  };
101  return _private_setting_tables;
102 }
103 
107 static auto &SecretSettingTables()
108 {
109  static const SettingTable _secrets_setting_tables[] = {
110  _network_secrets_settings,
111  };
112  return _secrets_setting_tables;
113 }
114 
115 typedef void SettingDescProc(IniFile &ini, const SettingTable &desc, const char *grpname, void *object, bool only_startup);
116 typedef void SettingDescProcList(IniFile &ini, const char *grpname, StringList &list);
117 
118 static bool IsSignedVarMemType(VarType vt)
119 {
120  switch (GetVarMemType(vt)) {
121  case SLE_VAR_I8:
122  case SLE_VAR_I16:
123  case SLE_VAR_I32:
124  case SLE_VAR_I64:
125  return true;
126  }
127  return false;
128 }
129 
133 class ConfigIniFile : public IniFile {
134 private:
135  inline static const char * const list_group_names[] = {
136  "bans",
137  "newgrf",
138  "servers",
139  "server_bind_addresses",
140  nullptr,
141  };
142 
143 public:
144  ConfigIniFile(const std::string &filename) : IniFile(list_group_names)
145  {
146  this->LoadFromDisk(filename, NO_DIRECTORY);
147  }
148 };
149 
157 enum IniFileVersion : uint32 {
161 
163 };
164 
166 
174 size_t OneOfManySettingDesc::ParseSingleValue(const char *str, size_t len, const std::vector<std::string> &many)
175 {
176  /* check if it's an integer */
177  if (isdigit(*str)) return strtoul(str, nullptr, 0);
178 
179  size_t idx = 0;
180  for (auto one : many) {
181  if (one.size() == len && strncmp(one.c_str(), str, len) == 0) return idx;
182  idx++;
183  }
184 
185  return (size_t)-1;
186 }
187 
195 static size_t LookupManyOfMany(const std::vector<std::string> &many, const char *str)
196 {
197  const char *s;
198  size_t r;
199  size_t res = 0;
200 
201  for (;;) {
202  /* skip "whitespace" */
203  while (*str == ' ' || *str == '\t' || *str == '|') str++;
204  if (*str == 0) break;
205 
206  s = str;
207  while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
208 
209  r = OneOfManySettingDesc::ParseSingleValue(str, s - str, many);
210  if (r == (size_t)-1) return r;
211 
212  SetBit(res, (uint8)r); // value found, set it
213  if (*s == 0) break;
214  str = s + 1;
215  }
216  return res;
217 }
218 
227 template<typename T>
228 static int ParseIntList(const char *p, T *items, int maxitems)
229 {
230  int n = 0; // number of items read so far
231  bool comma = false; // do we accept comma?
232 
233  while (*p != '\0') {
234  switch (*p) {
235  case ',':
236  /* Do not accept multiple commas between numbers */
237  if (!comma) return -1;
238  comma = false;
239  FALLTHROUGH;
240 
241  case ' ':
242  p++;
243  break;
244 
245  default: {
246  if (n == maxitems) return -1; // we don't accept that many numbers
247  char *end;
248  unsigned long v = strtoul(p, &end, 0);
249  if (p == end) return -1; // invalid character (not a number)
250  if (sizeof(T) < sizeof(v)) v = Clamp<unsigned long>(v, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
251  items[n++] = v;
252  p = end; // first non-number
253  comma = true; // we accept comma now
254  break;
255  }
256  }
257  }
258 
259  /* If we have read comma but no number after it, fail.
260  * We have read comma when (n != 0) and comma is not allowed */
261  if (n != 0 && !comma) return -1;
262 
263  return n;
264 }
265 
274 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
275 {
276  unsigned long items[64];
277  int i, nitems;
278 
279  if (str == nullptr) {
280  memset(items, 0, sizeof(items));
281  nitems = nelems;
282  } else {
283  nitems = ParseIntList(str, items, lengthof(items));
284  if (nitems != nelems) return false;
285  }
286 
287  switch (type) {
288  case SLE_VAR_BL:
289  case SLE_VAR_I8:
290  case SLE_VAR_U8:
291  for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
292  break;
293 
294  case SLE_VAR_I16:
295  case SLE_VAR_U16:
296  for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
297  break;
298 
299  case SLE_VAR_I32:
300  case SLE_VAR_U32:
301  for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
302  break;
303 
304  default: NOT_REACHED();
305  }
306 
307  return true;
308 }
309 
319 void ListSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
320 {
321  const byte *p = static_cast<const byte *>(GetVariableAddress(object, this->save));
322  int i, v = 0;
323 
324  for (i = 0; i != this->save.length; i++) {
325  switch (GetVarMemType(this->save.conv)) {
326  case SLE_VAR_BL:
327  case SLE_VAR_I8: v = *(const int8 *)p; p += 1; break;
328  case SLE_VAR_U8: v = *(const uint8 *)p; p += 1; break;
329  case SLE_VAR_I16: v = *(const int16 *)p; p += 2; break;
330  case SLE_VAR_U16: v = *(const uint16 *)p; p += 2; break;
331  case SLE_VAR_I32: v = *(const int32 *)p; p += 4; break;
332  case SLE_VAR_U32: v = *(const uint32 *)p; p += 4; break;
333  default: NOT_REACHED();
334  }
335  if (IsSignedVarMemType(this->save.conv)) {
336  buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
337  } else {
338  buf += seprintf(buf, last, (i == 0) ? "%u" : ",%u", v);
339  }
340  }
341 }
342 
343 char *OneOfManySettingDesc::FormatSingleValue(char *buf, const char *last, uint id) const
344 {
345  if (id >= this->many.size()) {
346  return buf + seprintf(buf, last, "%d", id);
347  }
348  return strecpy(buf, this->many[id].c_str(), last);
349 }
350 
351 void OneOfManySettingDesc::FormatValue(char *buf, const char *last, const void *object) const
352 {
353  uint id = (uint)this->Read(object);
354  this->FormatSingleValue(buf, last, id);
355 }
356 
357 void ManyOfManySettingDesc::FormatValue(char *buf, const char *last, const void *object) const
358 {
359  uint bitmask = (uint)this->Read(object);
360  if (bitmask == 0) {
361  buf[0] = '\0';
362  return;
363  }
364  bool first = true;
365  for (uint id : SetBitIterator(bitmask)) {
366  if (!first) buf = strecpy(buf, "|", last);
367  buf = this->FormatSingleValue(buf, last, id);
368  first = false;
369  }
370 }
371 
377 size_t IntSettingDesc::ParseValue(const char *str) const
378 {
379  char *end;
380  size_t val = strtoul(str, &end, 0);
381  if (end == str) {
382  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
383  msg.SetDParamStr(0, str);
384  msg.SetDParamStr(1, this->GetName());
385  _settings_error_list.push_back(msg);
386  return this->def;
387  }
388  if (*end != '\0') {
389  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_TRAILING_CHARACTERS);
390  msg.SetDParamStr(0, this->GetName());
391  _settings_error_list.push_back(msg);
392  }
393  return val;
394 }
395 
396 size_t OneOfManySettingDesc::ParseValue(const char *str) const
397 {
398  size_t r = OneOfManySettingDesc::ParseSingleValue(str, strlen(str), this->many);
399  /* if the first attempt of conversion from string to the appropriate value fails,
400  * look if we have defined a converter from old value to new value. */
401  if (r == (size_t)-1 && this->many_cnvt != nullptr) r = this->many_cnvt(str);
402  if (r != (size_t)-1) return r; // and here goes converted value
403 
404  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
405  msg.SetDParamStr(0, str);
406  msg.SetDParamStr(1, this->GetName());
407  _settings_error_list.push_back(msg);
408  return this->def;
409 }
410 
411 size_t ManyOfManySettingDesc::ParseValue(const char *str) const
412 {
413  size_t r = LookupManyOfMany(this->many, str);
414  if (r != (size_t)-1) return r;
415  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
416  msg.SetDParamStr(0, str);
417  msg.SetDParamStr(1, this->GetName());
418  _settings_error_list.push_back(msg);
419  return this->def;
420 }
421 
422 size_t BoolSettingDesc::ParseValue(const char *str) const
423 {
424  if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0) return true;
425  if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return false;
426 
427  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
428  msg.SetDParamStr(0, str);
429  msg.SetDParamStr(1, this->GetName());
430  _settings_error_list.push_back(msg);
431  return this->def;
432 }
433 
440 void IntSettingDesc::MakeValueValidAndWrite(const void *object, int32 val) const
441 {
442  this->MakeValueValid(val);
443  this->Write(object, val);
444 }
445 
455 void IntSettingDesc::MakeValueValid(int32 &val) const
456 {
457  /* We need to take special care of the uint32 type as we receive from the function
458  * a signed integer. While here also bail out on 64-bit settings as those are not
459  * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
460  * 32-bit variable
461  * TODO: Support 64-bit settings/variables; requires 64 bit over command protocol! */
462  switch (GetVarMemType(this->save.conv)) {
463  case SLE_VAR_NULL: return;
464  case SLE_VAR_BL:
465  case SLE_VAR_I8:
466  case SLE_VAR_U8:
467  case SLE_VAR_I16:
468  case SLE_VAR_U16:
469  case SLE_VAR_I32: {
470  /* Override the minimum value. No value below this->min, except special value 0 */
471  if (!(this->flags & SF_GUI_0_IS_SPECIAL) || val != 0) {
472  if (!(this->flags & SF_GUI_DROPDOWN)) {
473  /* Clamp value-type setting to its valid range */
474  val = Clamp(val, this->min, this->max);
475  } else if (val < this->min || val > (int32)this->max) {
476  /* Reset invalid discrete setting (where different values change gameplay) to its default value */
477  val = this->def;
478  }
479  }
480  break;
481  }
482  case SLE_VAR_U32: {
483  /* Override the minimum value. No value below this->min, except special value 0 */
484  uint32 uval = (uint32)val;
485  if (!(this->flags & SF_GUI_0_IS_SPECIAL) || uval != 0) {
486  if (!(this->flags & SF_GUI_DROPDOWN)) {
487  /* Clamp value-type setting to its valid range */
488  uval = ClampU(uval, this->min, this->max);
489  } else if (uval < (uint)this->min || uval > this->max) {
490  /* Reset invalid discrete setting to its default value */
491  uval = (uint32)this->def;
492  }
493  }
494  val = (int32)uval;
495  return;
496  }
497  case SLE_VAR_I64:
498  case SLE_VAR_U64:
499  default: NOT_REACHED();
500  }
501 }
502 
508 void IntSettingDesc::Write(const void *object, int32 val) const
509 {
510  void *ptr = GetVariableAddress(object, this->save);
511  WriteValue(ptr, this->save.conv, (int64)val);
512 }
513 
519 int32 IntSettingDesc::Read(const void *object) const
520 {
521  void *ptr = GetVariableAddress(object, this->save);
522  return (int32)ReadValue(ptr, this->save.conv);
523 }
524 
532 void StringSettingDesc::MakeValueValid(std::string &str) const
533 {
534  if (this->max_length == 0 || str.size() < this->max_length) return;
535 
536  /* In case a maximum length is imposed by the setting, the length
537  * includes the '\0' termination for network transfer purposes.
538  * Also ensure the string is valid after chopping of some bytes. */
539  std::string stdstr(str, this->max_length - 1);
540  str.assign(StrMakeValid(stdstr, SVS_NONE));
541 }
542 
548 void StringSettingDesc::Write(const void *object, const std::string &str) const
549 {
550  reinterpret_cast<std::string *>(GetVariableAddress(object, this->save))->assign(str);
551 }
552 
558 const std::string &StringSettingDesc::Read(const void *object) const
559 {
560  return *reinterpret_cast<std::string *>(GetVariableAddress(object, this->save));
561 }
562 
572 static void IniLoadSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool only_startup)
573 {
574  IniGroup *group;
575  IniGroup *group_def = ini.GetGroup(grpname);
576 
577  for (auto &desc : settings_table) {
578  const SettingDesc *sd = GetSettingDesc(desc);
579  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
580  if (sd->startup != only_startup) continue;
581 
582  /* For settings.xx.yy load the settings from [xx] yy = ? */
583  std::string s{ sd->GetName() };
584  auto sc = s.find('.');
585  if (sc != std::string::npos) {
586  group = ini.GetGroup(s.substr(0, sc));
587  s = s.substr(sc + 1);
588  } else {
589  group = group_def;
590  }
591 
592  IniItem *item = group->GetItem(s, false);
593  if (item == nullptr && group != group_def) {
594  /* For settings.xx.yy load the settings from [settings] yy = ? in case the previous
595  * did not exist (e.g. loading old config files with a [settings] section */
596  item = group_def->GetItem(s, false);
597  }
598  if (item == nullptr) {
599  /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
600  * did not exist (e.g. loading old config files with a [yapf] section */
601  sc = s.find('.');
602  if (sc != std::string::npos) item = ini.GetGroup(s.substr(0, sc))->GetItem(s.substr(sc + 1), false);
603  }
604 
605  sd->ParseValue(item, object);
606  }
607 }
608 
609 void IntSettingDesc::ParseValue(const IniItem *item, void *object) const
610 {
611  size_t val = (item == nullptr) ? this->def : this->ParseValue(item->value.has_value() ? item->value->c_str() : "");
612  this->MakeValueValidAndWrite(object, (int32)val);
613 }
614 
615 void StringSettingDesc::ParseValue(const IniItem *item, void *object) const
616 {
617  std::string str = (item == nullptr) ? this->def : item->value.value_or("");
618  this->MakeValueValid(str);
619  this->Write(object, str);
620 }
621 
622 void ListSettingDesc::ParseValue(const IniItem *item, void *object) const
623 {
624  const char *str = (item == nullptr) ? this->def : item->value.has_value() ? item->value->c_str() : nullptr;
625  void *ptr = GetVariableAddress(object, this->save);
626  if (!LoadIntList(str, ptr, this->save.length, GetVarMemType(this->save.conv))) {
627  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY);
628  msg.SetDParamStr(0, this->GetName());
629  _settings_error_list.push_back(msg);
630 
631  /* Use default */
632  LoadIntList(this->def, ptr, this->save.length, GetVarMemType(this->save.conv));
633  }
634 }
635 
648 static void IniSaveSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool)
649 {
650  IniGroup *group_def = nullptr, *group;
651  IniItem *item;
652  char buf[512];
653 
654  for (auto &desc : settings_table) {
655  const SettingDesc *sd = GetSettingDesc(desc);
656  /* If the setting is not saved to the configuration
657  * file, just continue with the next setting */
658  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
659  if (sd->flags & SF_NOT_IN_CONFIG) continue;
660 
661  /* XXX - wtf is this?? (group override?) */
662  std::string s{ sd->GetName() };
663  auto sc = s.find('.');
664  if (sc != std::string::npos) {
665  group = ini.GetGroup(s.substr(0, sc));
666  s = s.substr(sc + 1);
667  } else {
668  if (group_def == nullptr) group_def = ini.GetGroup(grpname);
669  group = group_def;
670  }
671 
672  item = group->GetItem(s, true);
673 
674  if (!item->value.has_value() || !sd->IsSameValue(item, object)) {
675  /* Value has changed, get the new value and put it into a buffer */
676  sd->FormatValue(buf, lastof(buf), object);
677 
678  /* The value is different, that means we have to write it to the ini */
679  item->value.emplace(buf);
680  }
681  }
682 }
683 
684 void IntSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
685 {
686  uint32 i = (uint32)this->Read(object);
687  seprintf(buf, last, IsSignedVarMemType(this->save.conv) ? "%d" : "%u", i);
688 }
689 
690 void BoolSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
691 {
692  bool val = this->Read(object) != 0;
693  strecpy(buf, val ? "true" : "false", last);
694 }
695 
696 bool IntSettingDesc::IsSameValue(const IniItem *item, void *object) const
697 {
698  int32 item_value = (int32)this->ParseValue(item->value->c_str());
699  int32 object_value = this->Read(object);
700  return item_value == object_value;
701 }
702 
703 void StringSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
704 {
705  const std::string &str = this->Read(object);
706  switch (GetVarMemType(this->save.conv)) {
707  case SLE_VAR_STR: strecpy(buf, str.c_str(), last); break;
708 
709  case SLE_VAR_STRQ:
710  if (str.empty()) {
711  buf[0] = '\0';
712  } else {
713  seprintf(buf, last, "\"%s\"", str.c_str());
714  }
715  break;
716 
717  default: NOT_REACHED();
718  }
719 }
720 
721 bool StringSettingDesc::IsSameValue(const IniItem *item, void *object) const
722 {
723  /* The ini parsing removes the quotes, which are needed to retain the spaces in STRQs,
724  * so those values are always different in the parsed ini item than they should be. */
725  if (GetVarMemType(this->save.conv) == SLE_VAR_STRQ) return false;
726 
727  const std::string &str = this->Read(object);
728  return item->value->compare(str) == 0;
729 }
730 
731 bool ListSettingDesc::IsSameValue(const IniItem *item, void *object) const
732 {
733  /* Checking for equality is way more expensive than just writing the value. */
734  return false;
735 }
736 
746 static void IniLoadSettingList(IniFile &ini, const char *grpname, StringList &list)
747 {
748  IniGroup *group = ini.GetGroup(grpname);
749 
750  if (group == nullptr) return;
751 
752  list.clear();
753 
754  for (const IniItem *item = group->item; item != nullptr; item = item->next) {
755  if (!item->name.empty()) list.push_back(item->name);
756  }
757 }
758 
768 static void IniSaveSettingList(IniFile &ini, const char *grpname, StringList &list)
769 {
770  IniGroup *group = ini.GetGroup(grpname);
771 
772  if (group == nullptr) return;
773  group->Clear();
774 
775  for (const auto &iter : list) {
776  group->GetItem(iter, true)->SetValue("");
777  }
778 }
779 
786 void IniLoadWindowSettings(IniFile &ini, const char *grpname, void *desc)
787 {
788  IniLoadSettings(ini, _window_settings, grpname, desc, false);
789 }
790 
797 void IniSaveWindowSettings(IniFile &ini, const char *grpname, void *desc)
798 {
799  IniSaveSettings(ini, _window_settings, grpname, desc, false);
800 }
801 
807 bool SettingDesc::IsEditable(bool do_command) const
808 {
809  if (!do_command && !(this->flags & SF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->flags & SF_PER_COMPANY)) return false;
810  if ((this->flags & SF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
811  if ((this->flags & SF_NO_NETWORK) && _networking) return false;
812  if ((this->flags & SF_NEWGAME_ONLY) &&
813  (_game_mode == GM_NORMAL ||
814  (_game_mode == GM_EDITOR && !(this->flags & SF_SCENEDIT_TOO)))) return false;
815  if ((this->flags & SF_SCENEDIT_ONLY) && _game_mode != GM_EDITOR) return false;
816  return true;
817 }
818 
824 {
825  if (this->flags & SF_PER_COMPANY) return ST_COMPANY;
826  return (this->flags & SF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
827 }
828 
834 {
835  assert(this->IsIntSetting());
836  return static_cast<const IntSettingDesc *>(this);
837 }
838 
844 {
845  assert(this->IsStringSetting());
846  return static_cast<const StringSettingDesc *>(this);
847 }
848 
849 void PrepareOldDiffCustom();
850 void HandleOldDiffCustom(bool savegame);
851 
852 
854 static void ValidateSettings()
855 {
856  /* Do not allow a custom sea level with the original land generator. */
860  }
861 }
862 
863 static void AILoadConfig(IniFile &ini, const char *grpname)
864 {
865  IniGroup *group = ini.GetGroup(grpname);
866  IniItem *item;
867 
868  /* Clean any configured AI */
869  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
871  }
872 
873  /* If no group exists, return */
874  if (group == nullptr) return;
875 
877  for (item = group->item; c < MAX_COMPANIES && item != nullptr; c++, item = item->next) {
879 
880  config->Change(item->name.c_str());
881  if (!config->HasScript()) {
882  if (item->name != "none") {
883  Debug(script, 0, "The AI by the name '{}' was no longer found, and removed from the list.", item->name);
884  continue;
885  }
886  }
887  if (item->value.has_value()) config->StringToSettings(*item->value);
888  }
889 }
890 
891 static void GameLoadConfig(IniFile &ini, const char *grpname)
892 {
893  IniGroup *group = ini.GetGroup(grpname);
894  IniItem *item;
895 
896  /* Clean any configured GameScript */
898 
899  /* If no group exists, return */
900  if (group == nullptr) return;
901 
902  item = group->item;
903  if (item == nullptr) return;
904 
906 
907  config->Change(item->name.c_str());
908  if (!config->HasScript()) {
909  if (item->name != "none") {
910  Debug(script, 0, "The GameScript by the name '{}' was no longer found, and removed from the list.", item->name);
911  return;
912  }
913  }
914  if (item->value.has_value()) config->StringToSettings(*item->value);
915 }
916 
922 static int DecodeHexNibble(char c)
923 {
924  if (c >= '0' && c <= '9') return c - '0';
925  if (c >= 'A' && c <= 'F') return c + 10 - 'A';
926  if (c >= 'a' && c <= 'f') return c + 10 - 'a';
927  return -1;
928 }
929 
938 static bool DecodeHexText(const char *pos, uint8 *dest, size_t dest_size)
939 {
940  while (dest_size > 0) {
941  int hi = DecodeHexNibble(pos[0]);
942  int lo = (hi >= 0) ? DecodeHexNibble(pos[1]) : -1;
943  if (lo < 0) return false;
944  *dest++ = (hi << 4) | lo;
945  pos += 2;
946  dest_size--;
947  }
948  return *pos == '|';
949 }
950 
957 static GRFConfig *GRFLoadConfig(IniFile &ini, const char *grpname, bool is_static)
958 {
959  IniGroup *group = ini.GetGroup(grpname);
960  IniItem *item;
961  GRFConfig *first = nullptr;
962  GRFConfig **curr = &first;
963 
964  if (group == nullptr) return nullptr;
965 
966  uint num_grfs = 0;
967  for (item = group->item; item != nullptr; item = item->next) {
968  GRFConfig *c = nullptr;
969 
970  uint8 grfid_buf[4], md5sum[16];
971  const char *filename = item->name.c_str();
972  bool has_grfid = false;
973  bool has_md5sum = false;
974 
975  /* Try reading "<grfid>|" and on success, "<md5sum>|". */
976  has_grfid = DecodeHexText(filename, grfid_buf, lengthof(grfid_buf));
977  if (has_grfid) {
978  filename += 1 + 2 * lengthof(grfid_buf);
979  has_md5sum = DecodeHexText(filename, md5sum, lengthof(md5sum));
980  if (has_md5sum) filename += 1 + 2 * lengthof(md5sum);
981 
982  uint32 grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
983  if (has_md5sum) {
984  const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, md5sum);
985  if (s != nullptr) c = new GRFConfig(*s);
986  }
987  if (c == nullptr && !FioCheckFileExists(filename, NEWGRF_DIR)) {
988  const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
989  if (s != nullptr) c = new GRFConfig(*s);
990  }
991  }
992  if (c == nullptr) c = new GRFConfig(filename);
993 
994  /* Parse parameters */
995  if (item->value.has_value() && !item->value->empty()) {
996  int count = ParseIntList(item->value->c_str(), c->param, lengthof(c->param));
997  if (count < 0) {
998  SetDParamStr(0, filename);
999  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
1000  count = 0;
1001  }
1002  c->num_params = count;
1003  }
1004 
1005  /* Check if item is valid */
1006  if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
1007  if (c->status == GCS_NOT_FOUND) {
1008  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND);
1009  } else if (HasBit(c->flags, GCF_UNSAFE)) {
1010  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE);
1011  } else if (HasBit(c->flags, GCF_SYSTEM)) {
1012  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM);
1013  } else if (HasBit(c->flags, GCF_INVALID)) {
1014  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE);
1015  } else {
1016  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN);
1017  }
1018 
1019  SetDParamStr(0, StrEmpty(filename) ? item->name.c_str() : filename);
1020  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_GRF, WL_CRITICAL);
1021  delete c;
1022  continue;
1023  }
1024 
1025  /* Check for duplicate GRFID (will also check for duplicate filenames) */
1026  bool duplicate = false;
1027  for (const GRFConfig *gc = first; gc != nullptr; gc = gc->next) {
1028  if (gc->ident.grfid == c->ident.grfid) {
1029  SetDParamStr(0, c->filename);
1030  SetDParamStr(1, gc->filename);
1031  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_DUPLICATE_GRFID, WL_CRITICAL);
1032  duplicate = true;
1033  break;
1034  }
1035  }
1036  if (duplicate) {
1037  delete c;
1038  continue;
1039  }
1040 
1041  if (is_static) {
1042  /* Mark file as static to avoid saving in savegame. */
1043  SetBit(c->flags, GCF_STATIC);
1044  } else if (++num_grfs > NETWORK_MAX_GRF_COUNT) {
1045  /* Check we will not load more non-static NewGRFs than allowed. This could trigger issues for game servers. */
1046  ShowErrorMessage(STR_CONFIG_ERROR, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED, WL_CRITICAL);
1047  break;
1048  }
1049 
1050  /* Add item to list */
1051  *curr = c;
1052  curr = &c->next;
1053  }
1054 
1055  return first;
1056 }
1057 
1058 static IniFileVersion LoadVersionFromConfig(IniFile &ini)
1059 {
1060  IniGroup *group = ini.GetGroup("version");
1061 
1062  auto version_number = group->GetItem("ini_version", false);
1063  /* Older ini-file versions don't have this key yet. */
1064  if (version_number == nullptr || !version_number->value.has_value()) return IFV_0;
1065 
1066  uint32 version = 0;
1067  std::from_chars(version_number->value->data(), version_number->value->data() + version_number->value->size(), version);
1068 
1069  return static_cast<IniFileVersion>(version);
1070 }
1071 
1072 static void AISaveConfig(IniFile &ini, const char *grpname)
1073 {
1074  IniGroup *group = ini.GetGroup(grpname);
1075 
1076  if (group == nullptr) return;
1077  group->Clear();
1078 
1079  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1081  const char *name;
1082  std::string value = config->SettingsToString();
1083 
1084  if (config->HasScript()) {
1085  name = config->GetName();
1086  } else {
1087  name = "none";
1088  }
1089 
1090  IniItem *item = new IniItem(group, name);
1091  item->SetValue(value);
1092  }
1093 }
1094 
1095 static void GameSaveConfig(IniFile &ini, const char *grpname)
1096 {
1097  IniGroup *group = ini.GetGroup(grpname);
1098 
1099  if (group == nullptr) return;
1100  group->Clear();
1101 
1103  const char *name;
1104  std::string value = config->SettingsToString();
1105 
1106  if (config->HasScript()) {
1107  name = config->GetName();
1108  } else {
1109  name = "none";
1110  }
1111 
1112  IniItem *item = new IniItem(group, name);
1113  item->SetValue(value);
1114 }
1115 
1120 static void SaveVersionInConfig(IniFile &ini)
1121 {
1122  IniGroup *group = ini.GetGroup("version");
1123  group->GetItem("version_string", true)->SetValue(_openttd_revision);
1124  group->GetItem("version_number", true)->SetValue(fmt::format("{:08X}", _openttd_newgrf_version));
1125  group->GetItem("ini_version", true)->SetValue(std::to_string(INIFILE_VERSION));
1126 }
1127 
1128 /* Save a GRF configuration to the given group name */
1129 static void GRFSaveConfig(IniFile &ini, const char *grpname, const GRFConfig *list)
1130 {
1131  ini.RemoveGroup(grpname);
1132  IniGroup *group = ini.GetGroup(grpname);
1133  const GRFConfig *c;
1134 
1135  for (c = list; c != nullptr; c = c->next) {
1136  /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1137  char key[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH];
1138  char params[512];
1139  GRFBuildParamList(params, c, lastof(params));
1140 
1141  char *pos = key + seprintf(key, lastof(key), "%08X|", BSWAP32(c->ident.grfid));
1142  pos = md5sumToString(pos, lastof(key), c->ident.md5sum);
1143  seprintf(pos, lastof(key), "|%s", c->filename);
1144  group->GetItem(key, true)->SetValue(params);
1145  }
1146 }
1147 
1148 /* Common handler for saving/loading variables to the configuration file */
1149 static void HandleSettingDescs(IniFile &generic_ini, IniFile &private_ini, IniFile &secrets_ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool only_startup = false)
1150 {
1151  proc(generic_ini, _misc_settings, "misc", nullptr, only_startup);
1152 #if defined(_WIN32) && !defined(DEDICATED)
1153  proc(generic_ini, _win32_settings, "win32", nullptr, only_startup);
1154 #endif /* _WIN32 */
1155 
1156  /* The name "patches" is a fallback, as every setting should sets its own group. */
1157 
1158  for (auto &table : GenericSettingTables()) {
1159  proc(generic_ini, table, "patches", &_settings_newgame, only_startup);
1160  }
1161  for (auto &table : PrivateSettingTables()) {
1162  proc(private_ini, table, "patches", &_settings_newgame, only_startup);
1163  }
1164  for (auto &table : SecretSettingTables()) {
1165  proc(secrets_ini, table, "patches", &_settings_newgame, only_startup);
1166  }
1167 
1168  proc(generic_ini, _currency_settings, "currency", &_custom_currency, only_startup);
1169  proc(generic_ini, _company_settings, "company", &_settings_client.company, only_startup);
1170 
1171  if (!only_startup) {
1172  proc_list(private_ini, "server_bind_addresses", _network_bind_list);
1173  proc_list(private_ini, "servers", _network_host_list);
1174  proc_list(private_ini, "bans", _network_ban_list);
1175  }
1176 }
1177 
1187 static void RemoveEntriesFromIni(IniFile &ini, const SettingTable &table)
1188 {
1189  for (auto &desc : table) {
1190  const SettingDesc *sd = GetSettingDesc(desc);
1191 
1192  /* For settings.xx.yy load the settings from [xx] yy = ? */
1193  std::string s{ sd->GetName() };
1194  auto sc = s.find('.');
1195  if (sc == std::string::npos) continue;
1196 
1197  IniGroup *group = ini.GetGroup(s.substr(0, sc));
1198  s = s.substr(sc + 1);
1199 
1200  group->RemoveItem(s);
1201  }
1202 }
1203 
1208 void LoadFromConfig(bool startup)
1209 {
1210  ConfigIniFile generic_ini(_config_file);
1211  ConfigIniFile private_ini(_private_file);
1212  ConfigIniFile secrets_ini(_secrets_file);
1213 
1214  if (!startup) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1215 
1216  IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1217 
1218  /* Before the split of private/secrets, we have to look in the generic for these settings. */
1219  if (generic_version < IFV_PRIVATE_SECRETS) {
1220  HandleSettingDescs(generic_ini, generic_ini, generic_ini, IniLoadSettings, IniLoadSettingList, startup);
1221  } else {
1222  HandleSettingDescs(generic_ini, private_ini, secrets_ini, IniLoadSettings, IniLoadSettingList, startup);
1223  }
1224 
1225  /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1226  if (!startup) {
1227  /* Convert network.server_advertise to network.server_game_type, but only if network.server_game_type is set to default value. */
1228  if (generic_version < IFV_GAME_TYPE) {
1229  if (_settings_client.network.server_game_type == SERVER_GAME_TYPE_LOCAL) {
1230  IniGroup *network = generic_ini.GetGroup("network", false);
1231  if (network != nullptr) {
1232  IniItem *server_advertise = network->GetItem("server_advertise", false);
1233  if (server_advertise != nullptr && server_advertise->value == "true") {
1234  _settings_client.network.server_game_type = SERVER_GAME_TYPE_PUBLIC;
1235  }
1236  }
1237  }
1238  }
1239 
1240  _grfconfig_newgame = GRFLoadConfig(generic_ini, "newgrf", false);
1241  _grfconfig_static = GRFLoadConfig(generic_ini, "newgrf-static", true);
1242  AILoadConfig(generic_ini, "ai_players");
1243  GameLoadConfig(generic_ini, "game_scripts");
1244 
1246  IniLoadSettings(generic_ini, _old_gameopt_settings, "gameopt", &_settings_newgame, false);
1247  HandleOldDiffCustom(false);
1248 
1249  ValidateSettings();
1251 
1252  /* Display scheduled errors */
1253  extern void ScheduleErrorMessage(ErrorList &datas);
1255  if (FindWindowById(WC_ERRMSG, 0) == nullptr) ShowFirstError();
1256  }
1257 }
1258 
1261 {
1262  ConfigIniFile generic_ini(_config_file);
1263  ConfigIniFile private_ini(_private_file);
1264  ConfigIniFile secrets_ini(_secrets_file);
1265 
1266  IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1267 
1268  /* If we newly create the private/secrets file, add a dummy group on top
1269  * just so we can add a comment before it (that is how IniFile works).
1270  * This to explain what the file is about. After doing it once, never touch
1271  * it again, as otherwise we might be reverting user changes. */
1272  if (!private_ini.GetGroup("private", false)) private_ini.GetGroup("private")->comment = "; This file possibly contains private information which can identify you as person.\n";
1273  if (!secrets_ini.GetGroup("secrets", false)) secrets_ini.GetGroup("secrets")->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";
1274 
1275  if (generic_version == IFV_0) {
1276  /* Remove some obsolete groups. These have all been loaded into other groups. */
1277  generic_ini.RemoveGroup("patches");
1278  generic_ini.RemoveGroup("yapf");
1279  generic_ini.RemoveGroup("gameopt");
1280 
1281  /* Remove all settings from the generic ini that are now in the private ini. */
1282  generic_ini.RemoveGroup("server_bind_addresses");
1283  generic_ini.RemoveGroup("servers");
1284  generic_ini.RemoveGroup("bans");
1285  for (auto &table : PrivateSettingTables()) {
1286  RemoveEntriesFromIni(generic_ini, table);
1287  }
1288 
1289  /* Remove all settings from the generic ini that are now in the secrets ini. */
1290  for (auto &table : SecretSettingTables()) {
1291  RemoveEntriesFromIni(generic_ini, table);
1292  }
1293  }
1294 
1295  /* Remove network.server_advertise. */
1296  if (generic_version < IFV_GAME_TYPE) {
1297  IniGroup *network = generic_ini.GetGroup("network", false);
1298  if (network != nullptr) {
1299  network->RemoveItem("server_advertise");
1300  }
1301  }
1302 
1303  HandleSettingDescs(generic_ini, private_ini, secrets_ini, IniSaveSettings, IniSaveSettingList);
1304  GRFSaveConfig(generic_ini, "newgrf", _grfconfig_newgame);
1305  GRFSaveConfig(generic_ini, "newgrf-static", _grfconfig_static);
1306  AISaveConfig(generic_ini, "ai_players");
1307  GameSaveConfig(generic_ini, "game_scripts");
1308 
1309  SaveVersionInConfig(generic_ini);
1310  SaveVersionInConfig(private_ini);
1311  SaveVersionInConfig(secrets_ini);
1312 
1313  generic_ini.SaveToDisk(_config_file);
1314  private_ini.SaveToDisk(_private_file);
1315  secrets_ini.SaveToDisk(_secrets_file);
1316 }
1317 
1323 {
1324  StringList list;
1325 
1327  for (IniGroup *group = ini.group; group != nullptr; group = group->next) {
1328  if (group->name.compare(0, 7, "preset-") == 0) {
1329  list.push_back(group->name.substr(7));
1330  }
1331  }
1332 
1333  return list;
1334 }
1335 
1342 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1343 {
1344  size_t len = strlen(config_name) + 8;
1345  char *section = (char*)alloca(len);
1346  seprintf(section, section + len - 1, "preset-%s", config_name);
1347 
1349  GRFConfig *config = GRFLoadConfig(ini, section, false);
1350 
1351  return config;
1352 }
1353 
1360 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1361 {
1362  size_t len = strlen(config_name) + 8;
1363  char *section = (char*)alloca(len);
1364  seprintf(section, section + len - 1, "preset-%s", config_name);
1365 
1367  GRFSaveConfig(ini, section, config);
1368  ini.SaveToDisk(_config_file);
1369 }
1370 
1375 void DeleteGRFPresetFromConfig(const char *config_name)
1376 {
1377  size_t len = strlen(config_name) + 8;
1378  char *section = (char*)alloca(len);
1379  seprintf(section, section + len - 1, "preset-%s", config_name);
1380 
1382  ini.RemoveGroup(section);
1383  ini.SaveToDisk(_config_file);
1384 }
1385 
1392 void IntSettingDesc::ChangeValue(const void *object, int32 newval) const
1393 {
1394  int32 oldval = this->Read(object);
1395  this->MakeValueValid(newval);
1396  if (this->pre_check != nullptr && !this->pre_check(newval)) return;
1397  if (oldval == newval) return;
1398 
1399  this->Write(object, newval);
1400  if (this->post_callback != nullptr) this->post_callback(newval);
1401 
1402  if (this->flags & SF_NO_NETWORK) {
1404  GamelogSetting(this->GetName(), oldval, newval);
1406  }
1407 
1409 
1410  if (_save_config) SaveToConfig();
1411 }
1412 
1420 static const SettingDesc *GetSettingFromName(const std::string_view name, const SettingTable &settings)
1421 {
1422  /* First check all full names */
1423  for (auto &desc : settings) {
1424  const SettingDesc *sd = GetSettingDesc(desc);
1425  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1426  if (sd->GetName() == name) return sd;
1427  }
1428 
1429  /* Then check the shortcut variant of the name. */
1430  std::string short_name_suffix = std::string{ "." }.append(name);
1431  for (auto &desc : settings) {
1432  const SettingDesc *sd = GetSettingDesc(desc);
1433  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1434  if (StrEndsWith(sd->GetName(), short_name_suffix)) return sd;
1435  }
1436 
1437  return nullptr;
1438 }
1439 
1445 void GetSaveLoadFromSettingTable(SettingTable settings, std::vector<SaveLoad> &saveloads)
1446 {
1447  for (auto &desc : settings) {
1448  const SettingDesc *sd = GetSettingDesc(desc);
1449  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1450  saveloads.push_back(sd->save);
1451  }
1452 }
1453 
1460 static const SettingDesc *GetCompanySettingFromName(std::string_view name)
1461 {
1462  static const std::string_view company_prefix = "company.";
1463  if (StrStartsWith(name, company_prefix)) name.remove_prefix(company_prefix.size());
1464  return GetSettingFromName(name, _company_settings);
1465 }
1466 
1473 const SettingDesc *GetSettingFromName(const std::string_view name)
1474 {
1475  for (auto &table : GenericSettingTables()) {
1476  auto sd = GetSettingFromName(name, table);
1477  if (sd != nullptr) return sd;
1478  }
1479  for (auto &table : PrivateSettingTables()) {
1480  auto sd = GetSettingFromName(name, table);
1481  if (sd != nullptr) return sd;
1482  }
1483  for (auto &table : SecretSettingTables()) {
1484  auto sd = GetSettingFromName(name, table);
1485  if (sd != nullptr) return sd;
1486  }
1487 
1488  return GetCompanySettingFromName(name);
1489 }
1490 
1500 CommandCost CmdChangeSetting(DoCommandFlag flags, const std::string &name, int32 value)
1501 {
1502  if (name.empty()) return CMD_ERROR;
1503  const SettingDesc *sd = GetSettingFromName(name);
1504 
1505  if (sd == nullptr) return CMD_ERROR;
1507  if (!sd->IsIntSetting()) return CMD_ERROR;
1508 
1509  if (!sd->IsEditable(true)) return CMD_ERROR;
1510 
1511  if (flags & DC_EXEC) {
1512  sd->AsIntSetting()->ChangeValue(&GetGameSettings(), value);
1513  }
1514 
1515  return CommandCost();
1516 }
1517 
1526 CommandCost CmdChangeCompanySetting(DoCommandFlag flags, const std::string &name, int32 value)
1527 {
1528  if (name.empty()) return CMD_ERROR;
1529  const SettingDesc *sd = GetCompanySettingFromName(name);
1530 
1531  if (sd == nullptr) return CMD_ERROR;
1532  if (!sd->IsIntSetting()) return CMD_ERROR;
1533 
1534  if (flags & DC_EXEC) {
1536  }
1537 
1538  return CommandCost();
1539 }
1540 
1548 bool SetSettingValue(const IntSettingDesc *sd, int32 value, bool force_newgame)
1549 {
1550  const IntSettingDesc *setting = sd->AsIntSetting();
1551  if ((setting->flags & SF_PER_COMPANY) != 0) {
1552  if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
1553  return Command<CMD_CHANGE_COMPANY_SETTING>::Post(setting->GetName(), value);
1554  }
1555 
1556  setting->ChangeValue(&_settings_client.company, value);
1557  return true;
1558  }
1559 
1560  /* If an item is company-based, we do not send it over the network
1561  * (if any) to change. Also *hack*hack* we update the _newgame version
1562  * of settings because changing a company-based setting in a game also
1563  * changes its defaults. At least that is the convention we have chosen */
1564  if (setting->flags & SF_NO_NETWORK_SYNC) {
1565  if (_game_mode != GM_MENU) {
1566  setting->ChangeValue(&_settings_newgame, value);
1567  }
1568  setting->ChangeValue(&GetGameSettings(), value);
1569  return true;
1570  }
1571 
1572  if (force_newgame) {
1573  setting->ChangeValue(&_settings_newgame, value);
1574  return true;
1575  }
1576 
1577  /* send non-company-based settings over the network */
1578  if (!_networking || (_networking && _network_server)) {
1579  return Command<CMD_CHANGE_SETTING>::Post(setting->GetName(), value);
1580  }
1581  return false;
1582 }
1583 
1588 {
1589  Company *c = Company::Get(cid);
1590  for (auto &desc : _company_settings) {
1591  const IntSettingDesc *int_setting = GetSettingDesc(desc)->AsIntSetting();
1592  int_setting->MakeValueValidAndWrite(&c->settings, int_setting->def);
1593  }
1594 }
1595 
1600 {
1601  const void *old_object = &Company::Get(_current_company)->settings;
1602  const void *new_object = &_settings_client.company;
1603  for (auto &desc : _company_settings) {
1604  const SettingDesc *sd = GetSettingDesc(desc);
1605  uint32 old_value = (uint32)sd->AsIntSetting()->Read(old_object);
1606  uint32 new_value = (uint32)sd->AsIntSetting()->Read(new_object);
1607  if (old_value != new_value) Command<CMD_CHANGE_COMPANY_SETTING>::SendNet(STR_NULL, _local_company, sd->GetName(), new_value);
1608  }
1609 }
1610 
1618 bool SetSettingValue(const StringSettingDesc *sd, std::string value, bool force_newgame)
1619 {
1620  assert(sd->flags & SF_NO_NETWORK_SYNC);
1621 
1622  if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ && value.compare("(null)") == 0) {
1623  value.clear();
1624  }
1625 
1626  const void *object = (_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game;
1627  sd->AsStringSetting()->ChangeValue(object, value);
1628  return true;
1629 }
1630 
1637 void StringSettingDesc::ChangeValue(const void *object, std::string &newval) const
1638 {
1639  this->MakeValueValid(newval);
1640  if (this->pre_check != nullptr && !this->pre_check(newval)) return;
1641 
1642  this->Write(object, newval);
1643  if (this->post_callback != nullptr) this->post_callback(newval);
1644 
1645  if (_save_config) SaveToConfig();
1646 }
1647 
1648 /* Those 2 functions need to be here, else we have to make some stuff non-static
1649  * and besides, it is also better to keep stuff like this at the same place */
1650 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
1651 {
1652  const SettingDesc *sd = GetSettingFromName(name);
1653  if (sd == nullptr) {
1654  IConsolePrint(CC_ERROR, "'{}' is an unknown setting.", name);
1655  return;
1656  }
1657 
1658  bool success = true;
1659  if (sd->IsStringSetting()) {
1660  success = SetSettingValue(sd->AsStringSetting(), value, force_newgame);
1661  } else if (sd->IsIntSetting()) {
1662  const IntSettingDesc *isd = sd->AsIntSetting();
1663  size_t val = isd->ParseValue(value);
1664  if (!_settings_error_list.empty()) {
1665  IConsolePrint(CC_ERROR, "'{}' is not a valid value for this setting.", value);
1666  _settings_error_list.clear();
1667  return;
1668  }
1669  success = SetSettingValue(isd, (int32)val, force_newgame);
1670  }
1671 
1672  if (!success) {
1673  if (_network_server) {
1674  IConsolePrint(CC_ERROR, "This command/variable is not available during network games.");
1675  } else {
1676  IConsolePrint(CC_ERROR, "This command/variable is only available to a network server.");
1677  }
1678  }
1679 }
1680 
1681 void IConsoleSetSetting(const char *name, int value)
1682 {
1683  const SettingDesc *sd = GetSettingFromName(name);
1684  assert(sd != nullptr);
1685  SetSettingValue(sd->AsIntSetting(), value);
1686 }
1687 
1693 void IConsoleGetSetting(const char *name, bool force_newgame)
1694 {
1695  const SettingDesc *sd = GetSettingFromName(name);
1696  if (sd == nullptr) {
1697  IConsolePrint(CC_ERROR, "'{}' is an unknown setting.", name);
1698  return;
1699  }
1700 
1701  const void *object = (_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game;
1702 
1703  if (sd->IsStringSetting()) {
1704  IConsolePrint(CC_INFO, "Current value for '{}' is '{}'.", sd->GetName(), sd->AsStringSetting()->Read(object));
1705  } else if (sd->IsIntSetting()) {
1706  char value[20];
1707  sd->FormatValue(value, lastof(value), object);
1708  const IntSettingDesc *int_setting = sd->AsIntSetting();
1709  IConsolePrint(CC_INFO, "Current value for '{}' is '{}' (min: {}{}, max: {}).",
1710  sd->GetName(), value, (sd->flags & SF_GUI_0_IS_SPECIAL) ? "(0) " : "", int_setting->min, int_setting->max);
1711  }
1712 }
1713 
1714 static void IConsoleListSettingsTable(const SettingTable &table, const char *prefilter)
1715 {
1716  for (auto &desc : table) {
1717  const SettingDesc *sd = GetSettingDesc(desc);
1718  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1719  if (prefilter != nullptr && sd->GetName().find(prefilter) == std::string::npos) continue;
1720  char value[80];
1721  sd->FormatValue(value, lastof(value), &GetGameSettings());
1722  IConsolePrint(CC_DEFAULT, "{} = {}", sd->GetName(), value);
1723  }
1724 }
1725 
1731 void IConsoleListSettings(const char *prefilter)
1732 {
1733  IConsolePrint(CC_HELP, "All settings with their current value:");
1734 
1735  for (auto &table : GenericSettingTables()) {
1736  IConsoleListSettingsTable(table, prefilter);
1737  }
1738  for (auto &table : PrivateSettingTables()) {
1739  IConsoleListSettingsTable(table, prefilter);
1740  }
1741  for (auto &table : SecretSettingTables()) {
1742  IConsoleListSettingsTable(table, prefilter);
1743  }
1744 
1745  IConsolePrint(CC_HELP, "Use 'setting' command to change a value.");
1746 }
GamelogSetting
void GamelogSetting(const std::string &name, int32 oldval, int32 newval)
Logs change in game settings.
Definition: gamelog.cpp:486
IniLoadFile::RemoveGroup
void RemoveGroup(const char *name)
Remove the group with the given name.
Definition: ini_load.cpp:182
ShowFirstError
void ShowFirstError()
Show the first error of the queue.
Definition: error_gui.cpp:342
OneOfManySettingDesc::FormatValue
void FormatValue(char *buf, const char *last, const void *object) const override
Format the value of the setting associated with this object.
Definition: settings.cpp:351
ErrorList
std::list< ErrorMessageData > ErrorList
Define a queue with errors.
Definition: error_gui.cpp:178
SaveLoad::version_to
SaveLoadVersion version_to
Save/load the variable before this savegame version.
Definition: saveload.h:665
StringSettingDesc::FormatValue
void FormatValue(char *buf, const char *last, const void *object) const override
Format the value of the setting associated with this object.
Definition: settings.cpp:703
CC_INFO
static const TextColour CC_INFO
Colour for information lines.
Definition: console_type.h:27
IntSettingDesc::MakeValueValid
void MakeValueValid(int32 &value) const
Make the value valid given the limitations of this setting.
Definition: settings.cpp:455
SF_PER_COMPANY
@ SF_PER_COMPANY
This setting can be different for each company (saved in company struct).
Definition: settings_internal.h:27
ClientSettings
All settings that are only important for the local client.
Definition: settings_type.h:603
AIConfig
Definition: ai_config.hpp:16
SF_NOT_IN_SAVE
@ SF_NOT_IN_SAVE
Do not save with savegame, basically client-based.
Definition: settings_internal.h:28
SF_GUI_0_IS_SPECIAL
@ SF_GUI_0_IS_SPECIAL
A value of zero is possible and has a custom string (the one after "strval").
Definition: settings_internal.h:18
Pool::PoolItem<&_company_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
StringSettingDesc::MakeValueValid
void MakeValueValid(std::string &str) const
Make the value valid given the limitations of this setting.
Definition: settings.cpp:532
RemoveEntriesFromIni
static void RemoveEntriesFromIni(IniFile &ini, const SettingTable &table)
Remove all entries from a settings table from an ini-file.
Definition: settings.cpp:1187
IFV_GAME_TYPE
@ IFV_GAME_TYPE
2 PR#9515 Convert server_advertise to server_game_type.
Definition: settings.cpp:160
SLE_VAR_STR
@ SLE_VAR_STR
string pointer
Definition: saveload.h:595
command_func.h
FindGRFConfig
const GRFConfig * FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
Find a NewGRF in the scanned list.
Definition: newgrf_config.cpp:745
IniItem::SetValue
void SetValue(const std::string_view value)
Replace the current value with another value.
Definition: ini_load.cpp:41
StringSettingDesc::pre_check
PreChangeCheck * pre_check
Callback to check for the validity of the setting.
Definition: settings_internal.h:271
ErrorMessageData::SetDParamStr
void SetDParamStr(uint n, const char *str)
Set a rawstring parameter.
Definition: error_gui.cpp:161
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
IniItem::next
IniItem * next
The next item in this group.
Definition: ini_type.h:26
GRFLoadConfig
static GRFConfig * GRFLoadConfig(IniFile &ini, const char *grpname, bool is_static)
Load a GRF configuration.
Definition: settings.cpp:957
GetSettingFromName
static const SettingDesc * GetSettingFromName(const std::string_view name, const SettingTable &settings)
Given a name of setting, return a setting description from the table.
Definition: settings.cpp:1420
ValidateSettings
static void ValidateSettings()
Checks if any settings are set to incorrect values, and sets them to correct values in that case.
Definition: settings.cpp:854
SetDefaultCompanySettings
void SetDefaultCompanySettings(CompanyID cid)
Set the company settings for a new company to their default values.
Definition: settings.cpp:1587
StringSettingDesc::IsSameValue
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.
Definition: settings.cpp:721
CUSTOM_SEA_LEVEL_MIN_PERCENTAGE
static const uint CUSTOM_SEA_LEVEL_MIN_PERCENTAGE
Minimum percentage a user can specify for custom sea level.
Definition: genworld.h:48
SF_NOT_IN_CONFIG
@ SF_NOT_IN_CONFIG
Do not save to config file.
Definition: settings_internal.h:29
IntSettingDesc::min
int32 min
minimum values
Definition: settings_internal.h:161
IniLoadWindowSettings
void IniLoadWindowSettings(IniFile &ini, const char *grpname, void *desc)
Load a WindowDesc from config.
Definition: settings.cpp:786
currency.h
GRFConfig::num_params
uint8 num_params
Number of used parameters.
Definition: newgrf_config.h:177
ManyOfManySettingDesc::FormatValue
void FormatValue(char *buf, const char *last, const void *object) const override
Format the value of the setting associated with this object.
Definition: settings.cpp:357
ST_GAME
@ ST_GAME
Game setting.
Definition: settings_internal.h:62
_network_server
bool _network_server
network-server is active
Definition: network.cpp:59
IntSettingDesc::MakeValueValidAndWrite
void MakeValueValidAndWrite(const void *object, int32 value) const
Make the value valid and then write it to the setting.
Definition: settings.cpp:440
IniItem
A single "line" in an ini file.
Definition: ini_type.h:25
SettingDesc::save
SaveLoad save
Internal structure (going to savegame, parts to config).
Definition: settings_internal.h:79
SettingDesc::GetType
SettingType GetType() const
Return the type of the setting.
Definition: settings.cpp:823
SaveToConfig
void SaveToConfig()
Save the values to the configuration file.
Definition: settings.cpp:1260
PrepareOldDiffCustom
void PrepareOldDiffCustom()
Prepare for reading and old diff_custom by zero-ing the memory.
Definition: settings_sl.cpp:25
_old_vds
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition: settings.cpp:56
SettingDesc::IsEditable
bool IsEditable(bool do_command=false) const
Check whether the setting is editable in the current gamemode.
Definition: settings.cpp:807
IniGroup
A group within an ini file.
Definition: ini_type.h:38
ST_CLIENT
@ ST_CLIENT
Client setting.
Definition: settings_internal.h:64
LG_ORIGINAL
@ LG_ORIGINAL
The original landscape generator.
Definition: genworld.h:20
FindWindowById
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition: window.cpp:1161
ClampU
static uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:148
HandleOldDiffCustom
void HandleOldDiffCustom(bool savegame)
Reading of the old diff_custom array and transforming it to the new format.
Definition: settings_sl.cpp:36
SettingDesc::FormatValue
virtual void FormatValue(char *buf, const char *last, const void *object) const =0
Format the value of the setting associated with this object.
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:586
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
IniGroup::RemoveItem
void RemoveItem(const std::string &name)
Remove the item with the given name.
Definition: ini_load.cpp:107
SLE_VAR_NULL
@ SLE_VAR_NULL
useful to write zeros in savegame.
Definition: saveload.h:593
IntSettingDesc::ChangeValue
void ChangeValue(const void *object, int32 newvalue) const
Handle changing a value.
Definition: settings.cpp:1392
LookupManyOfMany
static size_t LookupManyOfMany(const std::vector< std::string > &many, const char *str)
Find the set-integer value MANYofMANY type in a string.
Definition: settings.cpp:195
SF_NO_NETWORK_SYNC
@ SF_NO_NETWORK_SYNC
Do not synchronize over network (but it is saved if SF_NOT_IN_SAVE is not set).
Definition: settings_internal.h:30
fileio_func.h
ST_COMPANY
@ ST_COMPANY
Company setting.
Definition: settings_internal.h:63
GCS_NOT_FOUND
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:37
SaveLoad::length
uint16 length
(Conditional) length of the variable (eg. arrays) (max array size is 65536 elements).
Definition: saveload.h:663
GRFConfig::ident
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
Definition: newgrf_config.h:163
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
_network_bind_list
StringList _network_bind_list
The addresses to bind on.
Definition: network.cpp:67
StringSettingDesc::Read
const std::string & Read(const void *object) const
Read the string from the the actual setting.
Definition: settings.cpp:558
GRFConfig::status
GRFStatus status
NOSAVE: GRFStatus, enum.
Definition: newgrf_config.h:174
StringSettingDesc::post_callback
PostChangeCallback * post_callback
Callback when the setting has been changed.
Definition: settings_internal.h:272
SettingDesc::flags
SettingFlag flags
Handles how a setting would show up in the GUI (text/currency, etc.).
Definition: settings_internal.h:77
SaveLoad::conv
VarType conv
Type of the variable to be saved; this field combines both FileVarType and MemVarType.
Definition: saveload.h:662
_private_file
std::string _private_file
Private configuration file of OpenTTD.
Definition: settings.cpp:58
newgrf_config.h
IFV_PRIVATE_SECRETS
@ IFV_PRIVATE_SECRETS
1 PR#9298 Moving of settings from openttd.cfg to private.cfg / secrets.cfg.
Definition: settings.cpp:159
gamelog.h
fios.h
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
GLAT_SETTING
@ GLAT_SETTING
Setting changed.
Definition: gamelog.h:21
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:357
SettingDesc::IsSameValue
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.
GRFIdentifier::md5sum
uint8 md5sum[16]
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
Definition: newgrf_config.h:85
IntSettingDesc::pre_check
PreChangeCheck * pre_check
Callback to check for the validity of the setting.
Definition: settings_internal.h:168
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
StringSettingDesc::max_length
uint32 max_length
Maximum length of the string, 0 means no maximum length.
Definition: settings_internal.h:270
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:355
genworld.h
SettingDesc::AsStringSetting
const struct StringSettingDesc * AsStringSetting() const
Get the setting description of this setting as a string setting.
Definition: settings.cpp:843
CC_DEFAULT
static const TextColour CC_DEFAULT
Default colour of the console.
Definition: console_type.h:23
ManyOfManySettingDesc::ParseValue
size_t ParseValue(const char *str) const override
Convert a string representation (external) of an integer-like setting to an integer.
Definition: settings.cpp:411
ConfigIniFile
IniFile to store a configuration.
Definition: settings.cpp:133
GRFIdentifier::grfid
uint32 grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:84
IniGroup::Clear
void Clear()
Clear all items in the group.
Definition: ini_load.cpp:130
IFV_MAX_VERSION
@ IFV_MAX_VERSION
Highest possible ini-file version.
Definition: settings.cpp:162
ShowErrorMessage
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.
Definition: error_gui.cpp:377
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:587
GCF_INVALID
@ GCF_INVALID
GRF is unusable with this version of OpenTTD.
Definition: newgrf_config.h:30
GetGameSettings
static GameSettings & GetGameSettings()
Get the settings-object applicable for the current situation: the newgame settings when we're in the ...
Definition: settings_type.h:628
IniSaveSettings
static void IniSaveSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool)
Save the values of settings to the inifile.
Definition: settings.cpp:648
SettingDesc::ParseValue
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.
StringSettingDesc
String settings.
Definition: settings_internal.h:247
GRFBuildParamList
char * GRFBuildParamList(char *dst, const GRFConfig *c, const char *last)
Build a string containing space separated parameter values, and terminate.
Definition: newgrf_config.cpp:784
ListSettingDesc::ParseValue
void ParseValue(const IniItem *item, void *object) const override
Parse/read the value from the Ini item into the setting associated with this object.
Definition: settings.cpp:622
COMPANY_FIRST
@ COMPANY_FIRST
First company, same as owner.
Definition: company_type.h:22
SettingType
SettingType
Type of settings for filtering.
Definition: settings_internal.h:61
NETWORK_MAX_GRF_COUNT
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition: config.h:95
CmdChangeCompanySetting
CommandCost CmdChangeCompanySetting(DoCommandFlag flags, const std::string &name, int32 value)
Change one of the per-company settings.
Definition: settings.cpp:1526
DecodeHexText
static bool DecodeHexText(const char *pos, uint8 *dest, size_t dest_size)
Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
Definition: settings.cpp:938
StringSettingDesc::ChangeValue
void ChangeValue(const void *object, std::string &newval) const
Handle changing a string value.
Definition: settings.cpp:1637
GetGRFPresetList
StringList GetGRFPresetList()
Get the list of known NewGrf presets.
Definition: settings.cpp:1322
CommandCost
Common return value for all commands.
Definition: command_type.h:24
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:329
IniFile::IniFile
IniFile(const char *const *list_group_names=nullptr)
Create a new ini file with given group names.
Definition: ini.cpp:37
settings_func.h
SF_NETWORK_ONLY
@ SF_NETWORK_ONLY
This setting only applies to network games.
Definition: settings_internal.h:22
GCF_UNSAFE
@ GCF_UNSAFE
GRF file is unsafe for static usage.
Definition: newgrf_config.h:24
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:155
ParseIntList
static int ParseIntList(const char *p, T *items, int maxitems)
Parse an integerlist string and set each found value.
Definition: settings.cpp:228
CC_HELP
static const TextColour CC_HELP
Colour for help lines.
Definition: console_type.h:26
span
A trimmed down version of what std::span will be in C++20.
Definition: span_type.hpp:60
SettingDesc::startup
bool startup
Setting has to be loaded directly at startup?.
Definition: settings_internal.h:78
GCF_SYSTEM
@ GCF_SYSTEM
GRF file is an openttd-internal system grf.
Definition: newgrf_config.h:23
IntSettingDesc
Base integer type, including boolean, settings.
Definition: settings_internal.h:136
SettingDesc::GetName
constexpr const std::string & GetName() const
Get the name of this setting.
Definition: settings_internal.h:88
IniItem::value
std::optional< std::string > value
The value of this item.
Definition: ini_type.h:28
GRFConfig::flags
uint8 flags
NOSAVE: GCF_Flags, bitset.
Definition: newgrf_config.h:173
GameConfig
Definition: game_config.hpp:15
IniLoadSettingList
static void IniLoadSettingList(IniFile &ini, const char *grpname, StringList &list)
Loads all items from a 'grpname' section into a list The list parameter can be a nullptr pointer,...
Definition: settings.cpp:746
ScriptConfig::GetName
const char * GetName() const
Get the name of the Script.
Definition: script_config.cpp:175
SF_NEWGAME_ONLY
@ SF_NEWGAME_ONLY
This setting cannot be changed in a game.
Definition: settings_internal.h:24
IniFile::SaveToDisk
bool SaveToDisk(const std::string &filename)
Save the Ini file's data to the disk.
Definition: ini.cpp:46
AIConfig::GetConfig
static AIConfig * GetConfig(CompanyID company, ScriptSettingSource source=SSS_DEFAULT)
Get the config of a company.
Definition: ai_config.cpp:45
SecretSettingTables
static auto & SecretSettingTables()
List of all the secrets setting tables.
Definition: settings.cpp:107
StringSettingDesc::ParseValue
void ParseValue(const IniItem *item, void *object) const override
Parse/read the value from the Ini item into the setting associated with this object.
Definition: settings.cpp:615
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
StrStartsWith
bool StrStartsWith(const std::string_view str, const std::string_view prefix)
Check whether the given string starts with the given prefix.
Definition: string.cpp:385
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:106
GamelogStartAction
void GamelogStartAction(GamelogActionType at)
Stores information about new action, but doesn't allocate it Action is allocated only when there is a...
Definition: gamelog.cpp:69
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
StringList
std::vector< std::string > StringList
Type for a list of strings.
Definition: string_type.h:59
SyncCompanySettings
void SyncCompanySettings()
Sync all company settings in a multiplayer game.
Definition: settings.cpp:1599
safeguards.h
IniLoadSettings
static void IniLoadSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool only_startup)
Load values from a group of an IniFile structure into the internal representation.
Definition: settings.cpp:572
ScriptConfig::StringToSettings
void StringToSettings(const std::string &value)
Convert a string which is stored in the config file or savegames to custom settings of this Script.
Definition: script_config.cpp:185
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:67
DifficultySettings::quantity_sea_lakes
byte quantity_sea_lakes
the amount of seas/lakes
Definition: settings_type.h:90
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
GameSettings
All settings together for the game.
Definition: settings_type.h:585
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:58
OneOfManySettingDesc::many_cnvt
OnConvert * many_cnvt
callback procedure when loading value mechanism fails
Definition: settings_internal.h:223
IFV_0
@ IFV_0
0 All versions prior to introduction.
Definition: settings.cpp:158
ListSettingDesc::FormatValue
void FormatValue(char *buf, const char *last, const void *object) const override
Convert an integer-array (intlist) to a string representation.
Definition: settings.cpp:319
GetSettingDesc
static constexpr const SettingDesc * GetSettingDesc(const SettingVariant &desc)
Helper to convert the type of the iterated settings description to a pointer to it.
Definition: settings_internal.h:318
DeleteGRFPresetFromConfig
void DeleteGRFPresetFromConfig(const char *config_name)
Delete a NewGRF configuration by preset name.
Definition: settings.cpp:1375
ErrorMessageData
The data of the error message.
Definition: error.h:29
VehicleDefaultSettings
Default settings for vehicles.
Definition: settings_type.h:567
error.h
ResetCurrencies
void ResetCurrencies(bool preserve_custom)
Will fill _currency_specs array with default values from origin_currency_specs Called only from newgr...
Definition: currency.cpp:157
IniSaveSettingList
static void IniSaveSettingList(IniFile &ini, const char *grpname, StringList &list)
Saves all items from a list into the 'grpname' section The list parameter can be a nullptr pointer,...
Definition: settings.cpp:768
stdafx.h
settings_table.h
BSWAP32
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:390
IntSettingDesc::Write
void Write(const void *object, int32 value) const
Set the value of a setting.
Definition: settings.cpp:508
NEWGRF_DIR
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
Definition: fileio_type.h:117
_grfconfig_static
GRFConfig * _grfconfig_static
First item in list of static GRF set up.
Definition: newgrf_config.cpp:173
GamelogStopAction
void GamelogStopAction()
Stops logging of any changes.
Definition: gamelog.cpp:78
StrEndsWith
bool StrEndsWith(const std::string_view str, const std::string_view suffix)
Check whether the given string ends with the given suffix.
Definition: string.cpp:398
SlIsObjectCurrentlyValid
static bool SlIsObjectCurrentlyValid(SaveLoadVersion version_from, SaveLoadVersion version_to)
Checks if some version from/to combination falls within the range of the active savegame version.
Definition: saveload.h:1057
LoadGRFPresetFromConfig
GRFConfig * LoadGRFPresetFromConfig(const char *config_name)
Load a NewGRF configuration by preset-name.
Definition: settings.cpp:1342
OneOfManySettingDesc::ParseValue
size_t ParseValue(const char *str) const override
Convert a string representation (external) of an integer-like setting to an integer.
Definition: settings.cpp:396
WriteValue
void WriteValue(void *ptr, VarType conv, int64 val)
Write the value of a setting.
Definition: saveload.cpp:829
SettingDesc::IsStringSetting
virtual bool IsStringSetting() const
Check whether this setting is an string type setting.
Definition: settings_internal.h:103
OneOfManySettingDesc::many
std::vector< std::string > many
possible values for this type
Definition: settings_internal.h:222
_secrets_file
std::string _secrets_file
Secrets configuration file of OpenTTD.
Definition: settings.cpp:59
GenericSettingTables
static auto & GenericSettingTables()
List of all the generic setting tables.
Definition: settings.cpp:74
BoolSettingDesc::ParseValue
size_t ParseValue(const char *str) const override
Convert a string representation (external) of an integer-like setting to an integer.
Definition: settings.cpp:422
NetworkSettings::server_game_type
ServerGameType server_game_type
Server type: local / public / invite-only.
Definition: settings_type.h:285
IniLoadFile::group
IniGroup * group
the first group in the ini
Definition: ini_type.h:56
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
rev.h
WC_GAME_OPTIONS
@ WC_GAME_OPTIONS
Game options window; Window numbers:
Definition: window_type.h:606
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
IConsoleListSettings
void IConsoleListSettings(const char *prefilter)
List all settings and their value to the console.
Definition: settings.cpp:1731
IniGroup::comment
std::string comment
comment for group
Definition: ini_type.h:44
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:108
IniGroup::name
std::string name
name of group
Definition: ini_type.h:43
StrMakeValid
std::string StrMakeValid(const std::string &str, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:299
IniFile
Ini file that supports both loading and saving.
Definition: ini_type.h:89
IntSettingDesc::IsSameValue
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.
Definition: settings.cpp:696
SettingDesc
Properties of config file settings.
Definition: settings_internal.h:72
PrivateSettingTables
static auto & PrivateSettingTables()
List of all the private setting tables.
Definition: settings.cpp:96
GameCreationSettings::land_generator
byte land_generator
the landscape generator
Definition: settings_type.h:317
SetSettingValue
bool SetSettingValue(const IntSettingDesc *sd, int32 value, bool force_newgame)
Top function to save the new value of an element of the Settings struct.
Definition: settings.cpp:1548
NO_DIRECTORY
@ NO_DIRECTORY
A path without any base directory.
Definition: fileio_type.h:125
GetVarMemType
static VarType GetVarMemType(VarType type)
Get the NumberType of a setting.
Definition: saveload.h:1069
ScriptConfig::SettingsToString
std::string SettingsToString() const
Convert the custom settings to a string that can be stored in the config file or savegames.
Definition: script_config.cpp:211
IntSettingDesc::str
StringID str
(translated) string with descriptive text; gui and console
Definition: settings_internal.h:164
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:183
GameConfig::GetConfig
static GameConfig * GetConfig(ScriptSettingSource source=SSS_DEFAULT)
Get the config of a company.
Definition: game_config.cpp:18
ScheduleErrorMessage
void ScheduleErrorMessage(const ErrorMessageData &data)
Schedule an error.
Definition: error_gui.cpp:451
IniSaveWindowSettings
void IniSaveWindowSettings(IniFile &ini, const char *grpname, void *desc)
Save a WindowDesc to config.
Definition: settings.cpp:797
DecodeHexNibble
static int DecodeHexNibble(char c)
Convert a character to a hex nibble value, or -1 otherwise.
Definition: settings.cpp:922
ListSettingDesc::def
const char * def
default value given when none is present
Definition: settings_internal.h:293
ScriptConfig::SSS_FORCE_NEWGAME
@ SSS_FORCE_NEWGAME
Get the newgame Script config.
Definition: script_config.hpp:109
SF_SCENEDIT_ONLY
@ SF_SCENEDIT_ONLY
This setting can only be changed in the scenario editor.
Definition: settings_internal.h:26
FGCM_NEWEST_VALID
@ FGCM_NEWEST_VALID
Find newest Grf, ignoring Grfs with GCF_INVALID set.
Definition: newgrf_config.h:202
settings_cmd.h
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:554
SF_GUI_DROPDOWN
@ SF_GUI_DROPDOWN
The value represents a limited number of string-options (internally integer) presented as dropdown.
Definition: settings_internal.h:20
SaveLoad::version_from
SaveLoadVersion version_from
Save/load the variable starting from this savegame version.
Definition: saveload.h:664
IntSettingDesc::Read
int32 Read(const void *object) const
Read the integer from the the actual setting.
Definition: settings.cpp:519
company_func.h
CC_ERROR
static const TextColour CC_ERROR
Colour for error lines.
Definition: console_type.h:24
SLE_VAR_STRQ
@ SLE_VAR_STRQ
string pointer enclosed in quotes
Definition: saveload.h:596
ListSettingDesc::IsSameValue
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.
Definition: settings.cpp:731
SVS_NONE
@ SVS_NONE
Allow nothing and replace nothing.
Definition: string_type.h:50
IntSettingDesc::ParseValue
virtual size_t ParseValue(const char *str) const
Convert a string representation (external) of an integer-like setting to an integer.
Definition: settings.cpp:377
StringSettingDesc::Write
void Write(const void *object, const std::string &str) const
Write a string to the actual setting.
Definition: settings.cpp:548
IConsoleGetSetting
void IConsoleGetSetting(const char *name, bool force_newgame)
Output value of a specific setting to the console.
Definition: settings.cpp:1693
network.h
IntSettingDesc::max
uint32 max
maximum values
Definition: settings_internal.h:162
CommandHelper
Definition: command_func.h:94
window_func.h
IniItem::name
std::string name
The name of this item.
Definition: ini_type.h:27
SF_SCENEDIT_TOO
@ SF_SCENEDIT_TOO
This setting can be changed in the scenario editor (only makes sense when SF_NEWGAME_ONLY is set).
Definition: settings_internal.h:25
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
StringSettingDesc::def
std::string def
Default value given when none is present.
Definition: settings_internal.h:269
_network_ban_list
StringList _network_ban_list
The banned clients.
Definition: network.cpp:69
ClientSettings::network
NetworkSettings network
settings related to the network
Definition: settings_type.h:605
SaveVersionInConfig
static void SaveVersionInConfig(IniFile &ini)
Save the version of OpenTTD to the ini file.
Definition: settings.cpp:1120
IniGroup::item
IniItem * item
the first item in the group
Definition: ini_type.h:41
GetVariableAddress
static void * GetVariableAddress(const void *object, const SaveLoad &sld)
Get the address of the variable.
Definition: saveload.h:1100
IntSettingDesc::post_callback
PostChangeCallback * post_callback
Callback when the setting has been changed.
Definition: settings_internal.h:169
config.h
GetCompanySettingFromName
static const SettingDesc * GetCompanySettingFromName(std::string_view name)
Given a name of setting, return a company setting description of it.
Definition: settings.cpp:1460
ScriptConfig::Change
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.
Definition: script_config.cpp:19
ReadValue
int64 ReadValue(const void *ptr, VarType conv)
Return a signed-long version of the value of a setting.
Definition: saveload.cpp:805
ClientSettings::company
CompanySettings company
default values for per-company settings
Definition: settings_type.h:606
md5sumToString
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:572
Pool::PoolItem<&_company_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:326
INIFILE_VERSION
const uint16 INIFILE_VERSION
Current ini-file version of OpenTTD.
Definition: settings.cpp:165
FGCM_EXACT
@ FGCM_EXACT
Only find Grfs matching md5sum.
Definition: newgrf_config.h:199
IniGroup::GetItem
IniItem * GetItem(const std::string &name, bool create)
Get the item with the given name, and if it doesn't exist and create is true it creates a new item.
Definition: ini_load.cpp:91
SettingDesc::IsIntSetting
virtual bool IsIntSetting() const
Check whether this setting is an integer type setting.
Definition: settings_internal.h:97
_network_host_list
StringList _network_host_list
The servers we know.
Definition: network.cpp:68
GRFConfig::filename
char * filename
Filename - either with or without full path.
Definition: newgrf_config.h:165
console_func.h
BoolSettingDesc::FormatValue
void FormatValue(char *buf, const char *last, const void *object) const override
Format the value of the setting associated with this object.
Definition: settings.cpp:690
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:113
_config_file
std::string _config_file
Configuration file of OpenTTD.
Definition: settings.cpp:57
WC_ERRMSG
@ WC_ERRMSG
Error message; Window numbers:
Definition: window_type.h:103
CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
static const uint CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
Value for custom sea level in difficulty settings.
Definition: genworld.h:47
IniLoadFile::LoadFromDisk
void LoadFromDisk(const std::string &filename, Subdirectory subdir)
Load the Ini file's data from the disk.
Definition: ini_load.cpp:215
Company
Definition: company_base.h:117
game_config.hpp
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3182
SF_NO_NETWORK
@ SF_NO_NETWORK
This setting does not apply to network games; it may not be changed during the game.
Definition: settings_internal.h:23
IniFileVersion
IniFileVersion
Ini-file versions.
Definition: settings.cpp:157
FillGRFDetails
bool FillGRFDetails(GRFConfig *config, bool is_static, Subdirectory subdir)
Find the GRFID of a given grf, and calculate its md5sum.
Definition: newgrf_config.cpp:368
ini_type.h
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
_settings_error_list
static ErrorList _settings_error_list
Errors while loading minimal settings.
Definition: settings.cpp:62
LoadFromConfig
void LoadFromConfig(bool startup)
Load the values from the configuration files.
Definition: settings.cpp:1208
SaveGRFPresetToConfig
void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
Save a NewGRF configuration with a preset name.
Definition: settings.cpp:1360
DebugReconsiderSendRemoteMessages
void DebugReconsiderSendRemoteMessages()
Reconsider whether we need to send debug messages to either NetworkAdminConsole or IConsolePrint.
Definition: debug.cpp:294
network_func.h
GetSaveLoadFromSettingTable
void GetSaveLoadFromSettingTable(SettingTable settings, std::vector< SaveLoad > &saveloads)
Get the SaveLoad for all settings in the settings table.
Definition: settings.cpp:1445
ScriptConfig::HasScript
bool HasScript() const
Is this config attached to an Script? In other words, is there a Script that is assigned to this slot...
Definition: script_config.cpp:165
IntSettingDesc::def
int32 def
default value given when none is present
Definition: settings_internal.h:160
CmdChangeSetting
CommandCost CmdChangeSetting(DoCommandFlag flags, const std::string &name, int32 value)
Network-safe changing of settings (server-only).
Definition: settings.cpp:1500
LoadIntList
static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
Load parsed string-values into an integer-array (intlist)
Definition: settings.cpp:274
SetDParamStr
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:297
_settings_newgame
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:55
GCF_STATIC
@ GCF_STATIC
GRF file is used statically (can be used in any MP game)
Definition: newgrf_config.h:25
OneOfManySettingDesc::ParseSingleValue
static size_t ParseSingleValue(const char *str, size_t len, const std::vector< std::string > &many)
Find the index value of a ONEofMANY type in a string separated by |.
Definition: settings.cpp:174
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
debug.h
GRFConfig::param
uint32 param[0x80]
GRF parameters.
Definition: newgrf_config.h:176
_grfconfig_newgame
GRFConfig * _grfconfig_newgame
First item in list of default GRF set up.
Definition: newgrf_config.cpp:172
SettingDesc::AsIntSetting
const struct IntSettingDesc * AsIntSetting() const
Get the setting description of this setting as an integer setting.
Definition: settings.cpp:833
ai_config.hpp
IniLoadFile::GetGroup
IniGroup * GetGroup(const std::string &name, bool create_new=true)
Get the group with the given name.
Definition: ini_load.cpp:163
IntSettingDesc::FormatValue
void FormatValue(char *buf, const char *last, const void *object) const override
Format the value of the setting associated with this object.
Definition: settings.cpp:684
IniGroup::next
IniGroup * next
the next group within this file
Definition: ini_type.h:39
IConsolePrint
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console.cpp:94