OpenTTD Source  12.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 
48 #include "table/strings.h"
49 
50 #include "safeguards.h"
51 
56 std::string _config_file;
57 std::string _private_file;
58 std::string _secrets_file;
59 
60 typedef std::list<ErrorMessageData> ErrorList;
62 
73 static auto &GenericSettingTables()
74 {
75  static const SettingTable _generic_setting_tables[] = {
76  _difficulty_settings,
77  _economy_settings,
78  _game_settings,
79  _gui_settings,
80  _linkgraph_settings,
81  _locale_settings,
82  _multimedia_settings,
83  _network_settings,
84  _news_display_settings,
85  _pathfinding_settings,
86  _script_settings,
87  _world_settings,
88  };
89  return _generic_setting_tables;
90 }
91 
95 static auto &PrivateSettingTables()
96 {
97  static const SettingTable _private_setting_tables[] = {
98  _network_private_settings,
99  };
100  return _private_setting_tables;
101 }
102 
106 static auto &SecretSettingTables()
107 {
108  static const SettingTable _secrets_setting_tables[] = {
109  _network_secrets_settings,
110  };
111  return _secrets_setting_tables;
112 }
113 
114 typedef void SettingDescProc(IniFile &ini, const SettingTable &desc, const char *grpname, void *object, bool only_startup);
115 typedef void SettingDescProcList(IniFile &ini, const char *grpname, StringList &list);
116 
117 static bool IsSignedVarMemType(VarType vt)
118 {
119  switch (GetVarMemType(vt)) {
120  case SLE_VAR_I8:
121  case SLE_VAR_I16:
122  case SLE_VAR_I32:
123  case SLE_VAR_I64:
124  return true;
125  }
126  return false;
127 }
128 
132 class ConfigIniFile : public IniFile {
133 private:
134  inline static const char * const list_group_names[] = {
135  "bans",
136  "newgrf",
137  "servers",
138  "server_bind_addresses",
139  nullptr,
140  };
141 
142 public:
143  ConfigIniFile(const std::string &filename) : IniFile(list_group_names)
144  {
145  this->LoadFromDisk(filename, NO_DIRECTORY);
146  }
147 };
148 
156 enum IniFileVersion : uint32 {
160 
162 };
163 
165 
173 size_t OneOfManySettingDesc::ParseSingleValue(const char *str, size_t len, const std::vector<std::string> &many)
174 {
175  /* check if it's an integer */
176  if (isdigit(*str)) return strtoul(str, nullptr, 0);
177 
178  size_t idx = 0;
179  for (auto one : many) {
180  if (one.size() == len && strncmp(one.c_str(), str, len) == 0) return idx;
181  idx++;
182  }
183 
184  return (size_t)-1;
185 }
186 
194 static size_t LookupManyOfMany(const std::vector<std::string> &many, const char *str)
195 {
196  const char *s;
197  size_t r;
198  size_t res = 0;
199 
200  for (;;) {
201  /* skip "whitespace" */
202  while (*str == ' ' || *str == '\t' || *str == '|') str++;
203  if (*str == 0) break;
204 
205  s = str;
206  while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
207 
208  r = OneOfManySettingDesc::ParseSingleValue(str, s - str, many);
209  if (r == (size_t)-1) return r;
210 
211  SetBit(res, (uint8)r); // value found, set it
212  if (*s == 0) break;
213  str = s + 1;
214  }
215  return res;
216 }
217 
226 template<typename T>
227 static int ParseIntList(const char *p, T *items, int maxitems)
228 {
229  int n = 0; // number of items read so far
230  bool comma = false; // do we accept comma?
231 
232  while (*p != '\0') {
233  switch (*p) {
234  case ',':
235  /* Do not accept multiple commas between numbers */
236  if (!comma) return -1;
237  comma = false;
238  FALLTHROUGH;
239 
240  case ' ':
241  p++;
242  break;
243 
244  default: {
245  if (n == maxitems) return -1; // we don't accept that many numbers
246  char *end;
247  unsigned long v = strtoul(p, &end, 0);
248  if (p == end) return -1; // invalid character (not a number)
249  if (sizeof(T) < sizeof(v)) v = Clamp<unsigned long>(v, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
250  items[n++] = v;
251  p = end; // first non-number
252  comma = true; // we accept comma now
253  break;
254  }
255  }
256  }
257 
258  /* If we have read comma but no number after it, fail.
259  * We have read comma when (n != 0) and comma is not allowed */
260  if (n != 0 && !comma) return -1;
261 
262  return n;
263 }
264 
273 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
274 {
275  unsigned long items[64];
276  int i, nitems;
277 
278  if (str == nullptr) {
279  memset(items, 0, sizeof(items));
280  nitems = nelems;
281  } else {
282  nitems = ParseIntList(str, items, lengthof(items));
283  if (nitems != nelems) return false;
284  }
285 
286  switch (type) {
287  case SLE_VAR_BL:
288  case SLE_VAR_I8:
289  case SLE_VAR_U8:
290  for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
291  break;
292 
293  case SLE_VAR_I16:
294  case SLE_VAR_U16:
295  for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
296  break;
297 
298  case SLE_VAR_I32:
299  case SLE_VAR_U32:
300  for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
301  break;
302 
303  default: NOT_REACHED();
304  }
305 
306  return true;
307 }
308 
318 void ListSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
319 {
320  const byte *p = static_cast<const byte *>(GetVariableAddress(object, this->save));
321  int i, v = 0;
322 
323  for (i = 0; i != this->save.length; i++) {
324  switch (GetVarMemType(this->save.conv)) {
325  case SLE_VAR_BL:
326  case SLE_VAR_I8: v = *(const int8 *)p; p += 1; break;
327  case SLE_VAR_U8: v = *(const uint8 *)p; p += 1; break;
328  case SLE_VAR_I16: v = *(const int16 *)p; p += 2; break;
329  case SLE_VAR_U16: v = *(const uint16 *)p; p += 2; break;
330  case SLE_VAR_I32: v = *(const int32 *)p; p += 4; break;
331  case SLE_VAR_U32: v = *(const uint32 *)p; p += 4; break;
332  default: NOT_REACHED();
333  }
334  if (IsSignedVarMemType(this->save.conv)) {
335  buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
336  } else {
337  buf += seprintf(buf, last, (i == 0) ? "%u" : ",%u", v);
338  }
339  }
340 }
341 
342 char *OneOfManySettingDesc::FormatSingleValue(char *buf, const char *last, uint id) const
343 {
344  if (id >= this->many.size()) {
345  return buf + seprintf(buf, last, "%d", id);
346  }
347  return strecpy(buf, this->many[id].c_str(), last);
348 }
349 
350 void OneOfManySettingDesc::FormatValue(char *buf, const char *last, const void *object) const
351 {
352  uint id = (uint)this->Read(object);
353  this->FormatSingleValue(buf, last, id);
354 }
355 
356 void ManyOfManySettingDesc::FormatValue(char *buf, const char *last, const void *object) const
357 {
358  uint bitmask = (uint)this->Read(object);
359  bool first = true;
360  for (uint id : SetBitIterator(bitmask)) {
361  if (!first) buf = strecpy(buf, "|", last);
362  buf = this->FormatSingleValue(buf, last, id);
363  first = false;
364  }
365 }
366 
372 size_t IntSettingDesc::ParseValue(const char *str) const
373 {
374  char *end;
375  size_t val = strtoul(str, &end, 0);
376  if (end == str) {
377  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
378  msg.SetDParamStr(0, str);
379  msg.SetDParamStr(1, this->GetName());
380  _settings_error_list.push_back(msg);
381  return this->def;
382  }
383  if (*end != '\0') {
384  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_TRAILING_CHARACTERS);
385  msg.SetDParamStr(0, this->GetName());
386  _settings_error_list.push_back(msg);
387  }
388  return val;
389 }
390 
391 size_t OneOfManySettingDesc::ParseValue(const char *str) const
392 {
393  size_t r = OneOfManySettingDesc::ParseSingleValue(str, strlen(str), this->many);
394  /* if the first attempt of conversion from string to the appropriate value fails,
395  * look if we have defined a converter from old value to new value. */
396  if (r == (size_t)-1 && this->many_cnvt != nullptr) r = this->many_cnvt(str);
397  if (r != (size_t)-1) return r; // and here goes converted value
398 
399  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
400  msg.SetDParamStr(0, str);
401  msg.SetDParamStr(1, this->GetName());
402  _settings_error_list.push_back(msg);
403  return this->def;
404 }
405 
406 size_t ManyOfManySettingDesc::ParseValue(const char *str) const
407 {
408  size_t r = LookupManyOfMany(this->many, str);
409  if (r != (size_t)-1) return r;
410  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
411  msg.SetDParamStr(0, str);
412  msg.SetDParamStr(1, this->GetName());
413  _settings_error_list.push_back(msg);
414  return this->def;
415 }
416 
417 size_t BoolSettingDesc::ParseValue(const char *str) const
418 {
419  if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0) return true;
420  if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return false;
421 
422  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
423  msg.SetDParamStr(0, str);
424  msg.SetDParamStr(1, this->GetName());
425  _settings_error_list.push_back(msg);
426  return this->def;
427 }
428 
435 void IntSettingDesc::MakeValueValidAndWrite(const void *object, int32 val) const
436 {
437  this->MakeValueValid(val);
438  this->Write(object, val);
439 }
440 
450 void IntSettingDesc::MakeValueValid(int32 &val) const
451 {
452  /* We need to take special care of the uint32 type as we receive from the function
453  * a signed integer. While here also bail out on 64-bit settings as those are not
454  * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
455  * 32-bit variable
456  * TODO: Support 64-bit settings/variables; requires 64 bit over command protocol! */
457  switch (GetVarMemType(this->save.conv)) {
458  case SLE_VAR_NULL: return;
459  case SLE_VAR_BL:
460  case SLE_VAR_I8:
461  case SLE_VAR_U8:
462  case SLE_VAR_I16:
463  case SLE_VAR_U16:
464  case SLE_VAR_I32: {
465  /* Override the minimum value. No value below this->min, except special value 0 */
466  if (!(this->flags & SF_GUI_0_IS_SPECIAL) || val != 0) {
467  if (!(this->flags & SF_GUI_DROPDOWN)) {
468  /* Clamp value-type setting to its valid range */
469  val = Clamp(val, this->min, this->max);
470  } else if (val < this->min || val > (int32)this->max) {
471  /* Reset invalid discrete setting (where different values change gameplay) to its default value */
472  val = this->def;
473  }
474  }
475  break;
476  }
477  case SLE_VAR_U32: {
478  /* Override the minimum value. No value below this->min, except special value 0 */
479  uint32 uval = (uint32)val;
480  if (!(this->flags & SF_GUI_0_IS_SPECIAL) || uval != 0) {
481  if (!(this->flags & SF_GUI_DROPDOWN)) {
482  /* Clamp value-type setting to its valid range */
483  uval = ClampU(uval, this->min, this->max);
484  } else if (uval < (uint)this->min || uval > this->max) {
485  /* Reset invalid discrete setting to its default value */
486  uval = (uint32)this->def;
487  }
488  }
489  val = (int32)uval;
490  return;
491  }
492  case SLE_VAR_I64:
493  case SLE_VAR_U64:
494  default: NOT_REACHED();
495  }
496 }
497 
503 void IntSettingDesc::Write(const void *object, int32 val) const
504 {
505  void *ptr = GetVariableAddress(object, this->save);
506  WriteValue(ptr, this->save.conv, (int64)val);
507 }
508 
514 int32 IntSettingDesc::Read(const void *object) const
515 {
516  void *ptr = GetVariableAddress(object, this->save);
517  return (int32)ReadValue(ptr, this->save.conv);
518 }
519 
527 void StringSettingDesc::MakeValueValid(std::string &str) const
528 {
529  if (this->max_length == 0 || str.size() < this->max_length) return;
530 
531  /* In case a maximum length is imposed by the setting, the length
532  * includes the '\0' termination for network transfer purposes.
533  * Also ensure the string is valid after chopping of some bytes. */
534  std::string stdstr(str, this->max_length - 1);
535  str.assign(StrMakeValid(stdstr, SVS_NONE));
536 }
537 
543 void StringSettingDesc::Write(const void *object, const std::string &str) const
544 {
545  reinterpret_cast<std::string *>(GetVariableAddress(object, this->save))->assign(str);
546 }
547 
553 const std::string &StringSettingDesc::Read(const void *object) const
554 {
555  return *reinterpret_cast<std::string *>(GetVariableAddress(object, this->save));
556 }
557 
567 static void IniLoadSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool only_startup)
568 {
569  IniGroup *group;
570  IniGroup *group_def = ini.GetGroup(grpname);
571 
572  for (auto &desc : settings_table) {
573  const SettingDesc *sd = GetSettingDesc(desc);
574  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
575  if (sd->startup != only_startup) continue;
576 
577  /* For settings.xx.yy load the settings from [xx] yy = ? */
578  std::string s{ sd->GetName() };
579  auto sc = s.find('.');
580  if (sc != std::string::npos) {
581  group = ini.GetGroup(s.substr(0, sc));
582  s = s.substr(sc + 1);
583  } else {
584  group = group_def;
585  }
586 
587  IniItem *item = group->GetItem(s, false);
588  if (item == nullptr && group != group_def) {
589  /* For settings.xx.yy load the settings from [settings] yy = ? in case the previous
590  * did not exist (e.g. loading old config files with a [settings] section */
591  item = group_def->GetItem(s, false);
592  }
593  if (item == nullptr) {
594  /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
595  * did not exist (e.g. loading old config files with a [yapf] section */
596  sc = s.find('.');
597  if (sc != std::string::npos) item = ini.GetGroup(s.substr(0, sc))->GetItem(s.substr(sc + 1), false);
598  }
599 
600  sd->ParseValue(item, object);
601  }
602 }
603 
604 void IntSettingDesc::ParseValue(const IniItem *item, void *object) const
605 {
606  size_t val = (item == nullptr) ? this->def : this->ParseValue(item->value.has_value() ? item->value->c_str() : "");
607  this->MakeValueValidAndWrite(object, (int32)val);
608 }
609 
610 void StringSettingDesc::ParseValue(const IniItem *item, void *object) const
611 {
612  std::string str = (item == nullptr) ? this->def : item->value.value_or("");
613  this->MakeValueValid(str);
614  this->Write(object, str);
615 }
616 
617 void ListSettingDesc::ParseValue(const IniItem *item, void *object) const
618 {
619  const char *str = (item == nullptr) ? this->def : item->value.has_value() ? item->value->c_str() : nullptr;
620  void *ptr = GetVariableAddress(object, this->save);
621  if (!LoadIntList(str, ptr, this->save.length, GetVarMemType(this->save.conv))) {
622  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY);
623  msg.SetDParamStr(0, this->GetName());
624  _settings_error_list.push_back(msg);
625 
626  /* Use default */
627  LoadIntList(this->def, ptr, this->save.length, GetVarMemType(this->save.conv));
628  }
629 }
630 
643 static void IniSaveSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool)
644 {
645  IniGroup *group_def = nullptr, *group;
646  IniItem *item;
647  char buf[512];
648 
649  for (auto &desc : settings_table) {
650  const SettingDesc *sd = GetSettingDesc(desc);
651  /* If the setting is not saved to the configuration
652  * file, just continue with the next setting */
653  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
654  if (sd->flags & SF_NOT_IN_CONFIG) continue;
655 
656  /* XXX - wtf is this?? (group override?) */
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  s = s.substr(sc + 1);
662  } else {
663  if (group_def == nullptr) group_def = ini.GetGroup(grpname);
664  group = group_def;
665  }
666 
667  item = group->GetItem(s, true);
668 
669  if (!item->value.has_value() || !sd->IsSameValue(item, object)) {
670  /* Value has changed, get the new value and put it into a buffer */
671  sd->FormatValue(buf, lastof(buf), object);
672 
673  /* The value is different, that means we have to write it to the ini */
674  item->value.emplace(buf);
675  }
676  }
677 }
678 
679 void IntSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
680 {
681  uint32 i = (uint32)this->Read(object);
682  seprintf(buf, last, IsSignedVarMemType(this->save.conv) ? "%d" : "%u", i);
683 }
684 
685 void BoolSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
686 {
687  bool val = this->Read(object) != 0;
688  strecpy(buf, val ? "true" : "false", last);
689 }
690 
691 bool IntSettingDesc::IsSameValue(const IniItem *item, void *object) const
692 {
693  int32 item_value = (int32)this->ParseValue(item->value->c_str());
694  int32 object_value = this->Read(object);
695  return item_value == object_value;
696 }
697 
698 void StringSettingDesc::FormatValue(char *buf, const char *last, const void *object) const
699 {
700  const std::string &str = this->Read(object);
701  switch (GetVarMemType(this->save.conv)) {
702  case SLE_VAR_STR: strecpy(buf, str.c_str(), last); break;
703 
704  case SLE_VAR_STRQ:
705  if (str.empty()) {
706  buf[0] = '\0';
707  } else {
708  seprintf(buf, last, "\"%s\"", str.c_str());
709  }
710  break;
711 
712  default: NOT_REACHED();
713  }
714 }
715 
716 bool StringSettingDesc::IsSameValue(const IniItem *item, void *object) const
717 {
718  /* The ini parsing removes the quotes, which are needed to retain the spaces in STRQs,
719  * so those values are always different in the parsed ini item than they should be. */
720  if (GetVarMemType(this->save.conv) == SLE_VAR_STRQ) return false;
721 
722  const std::string &str = this->Read(object);
723  return item->value->compare(str) == 0;
724 }
725 
726 bool ListSettingDesc::IsSameValue(const IniItem *item, void *object) const
727 {
728  /* Checking for equality is way more expensive than just writing the value. */
729  return false;
730 }
731 
741 static void IniLoadSettingList(IniFile &ini, const char *grpname, StringList &list)
742 {
743  IniGroup *group = ini.GetGroup(grpname);
744 
745  if (group == nullptr) return;
746 
747  list.clear();
748 
749  for (const IniItem *item = group->item; item != nullptr; item = item->next) {
750  if (!item->name.empty()) list.push_back(item->name);
751  }
752 }
753 
763 static void IniSaveSettingList(IniFile &ini, const char *grpname, StringList &list)
764 {
765  IniGroup *group = ini.GetGroup(grpname);
766 
767  if (group == nullptr) return;
768  group->Clear();
769 
770  for (const auto &iter : list) {
771  group->GetItem(iter, true)->SetValue("");
772  }
773 }
774 
781 void IniLoadWindowSettings(IniFile &ini, const char *grpname, void *desc)
782 {
783  IniLoadSettings(ini, _window_settings, grpname, desc, false);
784 }
785 
792 void IniSaveWindowSettings(IniFile &ini, const char *grpname, void *desc)
793 {
794  IniSaveSettings(ini, _window_settings, grpname, desc, false);
795 }
796 
802 bool SettingDesc::IsEditable(bool do_command) const
803 {
804  if (!do_command && !(this->flags & SF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->flags & SF_PER_COMPANY)) return false;
805  if ((this->flags & SF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
806  if ((this->flags & SF_NO_NETWORK) && _networking) return false;
807  if ((this->flags & SF_NEWGAME_ONLY) &&
808  (_game_mode == GM_NORMAL ||
809  (_game_mode == GM_EDITOR && !(this->flags & SF_SCENEDIT_TOO)))) return false;
810  if ((this->flags & SF_SCENEDIT_ONLY) && _game_mode != GM_EDITOR) return false;
811  return true;
812 }
813 
819 {
820  if (this->flags & SF_PER_COMPANY) return ST_COMPANY;
821  return (this->flags & SF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
822 }
823 
829 {
830  assert(this->IsIntSetting());
831  return static_cast<const IntSettingDesc *>(this);
832 }
833 
839 {
840  assert(this->IsStringSetting());
841  return static_cast<const StringSettingDesc *>(this);
842 }
843 
844 void PrepareOldDiffCustom();
845 void HandleOldDiffCustom(bool savegame);
846 
847 
849 static void ValidateSettings()
850 {
851  /* Do not allow a custom sea level with the original land generator. */
855  }
856 }
857 
858 static void AILoadConfig(IniFile &ini, const char *grpname)
859 {
860  IniGroup *group = ini.GetGroup(grpname);
861  IniItem *item;
862 
863  /* Clean any configured AI */
864  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
866  }
867 
868  /* If no group exists, return */
869  if (group == nullptr) return;
870 
872  for (item = group->item; c < MAX_COMPANIES && item != nullptr; c++, item = item->next) {
874 
875  config->Change(item->name.c_str());
876  if (!config->HasScript()) {
877  if (item->name != "none") {
878  Debug(script, 0, "The AI by the name '{}' was no longer found, and removed from the list.", item->name);
879  continue;
880  }
881  }
882  if (item->value.has_value()) config->StringToSettings(*item->value);
883  }
884 }
885 
886 static void GameLoadConfig(IniFile &ini, const char *grpname)
887 {
888  IniGroup *group = ini.GetGroup(grpname);
889  IniItem *item;
890 
891  /* Clean any configured GameScript */
893 
894  /* If no group exists, return */
895  if (group == nullptr) return;
896 
897  item = group->item;
898  if (item == nullptr) return;
899 
901 
902  config->Change(item->name.c_str());
903  if (!config->HasScript()) {
904  if (item->name != "none") {
905  Debug(script, 0, "The GameScript by the name '{}' was no longer found, and removed from the list.", item->name);
906  return;
907  }
908  }
909  if (item->value.has_value()) config->StringToSettings(*item->value);
910 }
911 
917 static int DecodeHexNibble(char c)
918 {
919  if (c >= '0' && c <= '9') return c - '0';
920  if (c >= 'A' && c <= 'F') return c + 10 - 'A';
921  if (c >= 'a' && c <= 'f') return c + 10 - 'a';
922  return -1;
923 }
924 
933 static bool DecodeHexText(const char *pos, uint8 *dest, size_t dest_size)
934 {
935  while (dest_size > 0) {
936  int hi = DecodeHexNibble(pos[0]);
937  int lo = (hi >= 0) ? DecodeHexNibble(pos[1]) : -1;
938  if (lo < 0) return false;
939  *dest++ = (hi << 4) | lo;
940  pos += 2;
941  dest_size--;
942  }
943  return *pos == '|';
944 }
945 
952 static GRFConfig *GRFLoadConfig(IniFile &ini, const char *grpname, bool is_static)
953 {
954  IniGroup *group = ini.GetGroup(grpname);
955  IniItem *item;
956  GRFConfig *first = nullptr;
957  GRFConfig **curr = &first;
958 
959  if (group == nullptr) return nullptr;
960 
961  uint num_grfs = 0;
962  for (item = group->item; item != nullptr; item = item->next) {
963  GRFConfig *c = nullptr;
964 
965  uint8 grfid_buf[4], md5sum[16];
966  const char *filename = item->name.c_str();
967  bool has_grfid = false;
968  bool has_md5sum = false;
969 
970  /* Try reading "<grfid>|" and on success, "<md5sum>|". */
971  has_grfid = DecodeHexText(filename, grfid_buf, lengthof(grfid_buf));
972  if (has_grfid) {
973  filename += 1 + 2 * lengthof(grfid_buf);
974  has_md5sum = DecodeHexText(filename, md5sum, lengthof(md5sum));
975  if (has_md5sum) filename += 1 + 2 * lengthof(md5sum);
976 
977  uint32 grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
978  if (has_md5sum) {
979  const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, md5sum);
980  if (s != nullptr) c = new GRFConfig(*s);
981  }
982  if (c == nullptr && !FioCheckFileExists(filename, NEWGRF_DIR)) {
983  const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
984  if (s != nullptr) c = new GRFConfig(*s);
985  }
986  }
987  if (c == nullptr) c = new GRFConfig(filename);
988 
989  /* Parse parameters */
990  if (item->value.has_value() && !item->value->empty()) {
991  int count = ParseIntList(item->value->c_str(), c->param, lengthof(c->param));
992  if (count < 0) {
993  SetDParamStr(0, filename);
994  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
995  count = 0;
996  }
997  c->num_params = count;
998  }
999 
1000  /* Check if item is valid */
1001  if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
1002  if (c->status == GCS_NOT_FOUND) {
1003  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND);
1004  } else if (HasBit(c->flags, GCF_UNSAFE)) {
1005  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE);
1006  } else if (HasBit(c->flags, GCF_SYSTEM)) {
1007  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM);
1008  } else if (HasBit(c->flags, GCF_INVALID)) {
1009  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE);
1010  } else {
1011  SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN);
1012  }
1013 
1014  SetDParamStr(0, StrEmpty(filename) ? item->name : filename);
1015  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_GRF, WL_CRITICAL);
1016  delete c;
1017  continue;
1018  }
1019 
1020  /* Check for duplicate GRFID (will also check for duplicate filenames) */
1021  bool duplicate = false;
1022  for (const GRFConfig *gc = first; gc != nullptr; gc = gc->next) {
1023  if (gc->ident.grfid == c->ident.grfid) {
1024  SetDParamStr(0, c->filename);
1025  SetDParamStr(1, gc->filename);
1026  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_DUPLICATE_GRFID, WL_CRITICAL);
1027  duplicate = true;
1028  break;
1029  }
1030  }
1031  if (duplicate) {
1032  delete c;
1033  continue;
1034  }
1035 
1036  if (is_static) {
1037  /* Mark file as static to avoid saving in savegame. */
1038  SetBit(c->flags, GCF_STATIC);
1039  } else if (++num_grfs > NETWORK_MAX_GRF_COUNT) {
1040  /* Check we will not load more non-static NewGRFs than allowed. This could trigger issues for game servers. */
1041  ShowErrorMessage(STR_CONFIG_ERROR, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED, WL_CRITICAL);
1042  break;
1043  }
1044 
1045  /* Add item to list */
1046  *curr = c;
1047  curr = &c->next;
1048  }
1049 
1050  return first;
1051 }
1052 
1053 static IniFileVersion LoadVersionFromConfig(IniFile &ini)
1054 {
1055  IniGroup *group = ini.GetGroup("version");
1056 
1057  auto version_number = group->GetItem("ini_version", false);
1058  /* Older ini-file versions don't have this key yet. */
1059  if (version_number == nullptr || !version_number->value.has_value()) return IFV_0;
1060 
1061  uint32 version = 0;
1062  std::from_chars(version_number->value->data(), version_number->value->data() + version_number->value->size(), version);
1063 
1064  return static_cast<IniFileVersion>(version);
1065 }
1066 
1067 static void AISaveConfig(IniFile &ini, const char *grpname)
1068 {
1069  IniGroup *group = ini.GetGroup(grpname);
1070 
1071  if (group == nullptr) return;
1072  group->Clear();
1073 
1074  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1076  const char *name;
1077  std::string value = config->SettingsToString();
1078 
1079  if (config->HasScript()) {
1080  name = config->GetName();
1081  } else {
1082  name = "none";
1083  }
1084 
1085  IniItem *item = new IniItem(group, name);
1086  item->SetValue(value);
1087  }
1088 }
1089 
1090 static void GameSaveConfig(IniFile &ini, const char *grpname)
1091 {
1092  IniGroup *group = ini.GetGroup(grpname);
1093 
1094  if (group == nullptr) return;
1095  group->Clear();
1096 
1098  const char *name;
1099  std::string value = config->SettingsToString();
1100 
1101  if (config->HasScript()) {
1102  name = config->GetName();
1103  } else {
1104  name = "none";
1105  }
1106 
1107  IniItem *item = new IniItem(group, name);
1108  item->SetValue(value);
1109 }
1110 
1115 static void SaveVersionInConfig(IniFile &ini)
1116 {
1117  IniGroup *group = ini.GetGroup("version");
1118  group->GetItem("version_string", true)->SetValue(_openttd_revision);
1119  group->GetItem("version_number", true)->SetValue(fmt::format("{:08X}", _openttd_newgrf_version));
1120  group->GetItem("ini_version", true)->SetValue(std::to_string(INIFILE_VERSION));
1121 }
1122 
1123 /* Save a GRF configuration to the given group name */
1124 static void GRFSaveConfig(IniFile &ini, const char *grpname, const GRFConfig *list)
1125 {
1126  ini.RemoveGroup(grpname);
1127  IniGroup *group = ini.GetGroup(grpname);
1128  const GRFConfig *c;
1129 
1130  for (c = list; c != nullptr; c = c->next) {
1131  /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1132  char key[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH];
1133  char params[512];
1134  GRFBuildParamList(params, c, lastof(params));
1135 
1136  char *pos = key + seprintf(key, lastof(key), "%08X|", BSWAP32(c->ident.grfid));
1137  pos = md5sumToString(pos, lastof(key), c->ident.md5sum);
1138  seprintf(pos, lastof(key), "|%s", c->filename);
1139  group->GetItem(key, true)->SetValue(params);
1140  }
1141 }
1142 
1143 /* Common handler for saving/loading variables to the configuration file */
1144 static void HandleSettingDescs(IniFile &generic_ini, IniFile &private_ini, IniFile &secrets_ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool only_startup = false)
1145 {
1146  proc(generic_ini, _misc_settings, "misc", nullptr, only_startup);
1147 #if defined(_WIN32) && !defined(DEDICATED)
1148  proc(generic_ini, _win32_settings, "win32", nullptr, only_startup);
1149 #endif /* _WIN32 */
1150 
1151  /* The name "patches" is a fallback, as every setting should sets its own group. */
1152 
1153  for (auto &table : GenericSettingTables()) {
1154  proc(generic_ini, table, "patches", &_settings_newgame, only_startup);
1155  }
1156  for (auto &table : PrivateSettingTables()) {
1157  proc(private_ini, table, "patches", &_settings_newgame, only_startup);
1158  }
1159  for (auto &table : SecretSettingTables()) {
1160  proc(secrets_ini, table, "patches", &_settings_newgame, only_startup);
1161  }
1162 
1163  proc(generic_ini, _currency_settings, "currency", &_custom_currency, only_startup);
1164  proc(generic_ini, _company_settings, "company", &_settings_client.company, only_startup);
1165 
1166  if (!only_startup) {
1167  proc_list(private_ini, "server_bind_addresses", _network_bind_list);
1168  proc_list(private_ini, "servers", _network_host_list);
1169  proc_list(private_ini, "bans", _network_ban_list);
1170  }
1171 }
1172 
1182 static void RemoveEntriesFromIni(IniFile &ini, const SettingTable &table)
1183 {
1184  for (auto &desc : table) {
1185  const SettingDesc *sd = GetSettingDesc(desc);
1186 
1187  /* For settings.xx.yy load the settings from [xx] yy = ? */
1188  std::string s{ sd->GetName() };
1189  auto sc = s.find('.');
1190  if (sc == std::string::npos) continue;
1191 
1192  IniGroup *group = ini.GetGroup(s.substr(0, sc));
1193  s = s.substr(sc + 1);
1194 
1195  group->RemoveItem(s);
1196  }
1197 }
1198 
1203 void LoadFromConfig(bool startup)
1204 {
1205  ConfigIniFile generic_ini(_config_file);
1206  ConfigIniFile private_ini(_private_file);
1207  ConfigIniFile secrets_ini(_secrets_file);
1208 
1209  if (!startup) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1210 
1211  IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1212 
1213  /* Before the split of private/secrets, we have to look in the generic for these settings. */
1214  if (generic_version < IFV_PRIVATE_SECRETS) {
1215  HandleSettingDescs(generic_ini, generic_ini, generic_ini, IniLoadSettings, IniLoadSettingList, startup);
1216  } else {
1217  HandleSettingDescs(generic_ini, private_ini, secrets_ini, IniLoadSettings, IniLoadSettingList, startup);
1218  }
1219 
1220  /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1221  if (!startup) {
1222  /* Convert network.server_advertise to network.server_game_type, but only if network.server_game_type is set to default value. */
1223  if (generic_version < IFV_GAME_TYPE) {
1224  if (_settings_client.network.server_game_type == SERVER_GAME_TYPE_LOCAL) {
1225  IniGroup *network = generic_ini.GetGroup("network", false);
1226  if (network != nullptr) {
1227  IniItem *server_advertise = network->GetItem("server_advertise", false);
1228  if (server_advertise != nullptr && server_advertise->value == "true") {
1229  _settings_client.network.server_game_type = SERVER_GAME_TYPE_PUBLIC;
1230  }
1231  }
1232  }
1233  }
1234 
1235  _grfconfig_newgame = GRFLoadConfig(generic_ini, "newgrf", false);
1236  _grfconfig_static = GRFLoadConfig(generic_ini, "newgrf-static", true);
1237  AILoadConfig(generic_ini, "ai_players");
1238  GameLoadConfig(generic_ini, "game_scripts");
1239 
1241  IniLoadSettings(generic_ini, _old_gameopt_settings, "gameopt", &_settings_newgame, false);
1242  HandleOldDiffCustom(false);
1243 
1244  ValidateSettings();
1246 
1247  /* Display scheduled errors */
1248  extern void ScheduleErrorMessage(ErrorList &datas);
1250  if (FindWindowById(WC_ERRMSG, 0) == nullptr) ShowFirstError();
1251  }
1252 }
1253 
1256 {
1257  ConfigIniFile generic_ini(_config_file);
1258  ConfigIniFile private_ini(_private_file);
1259  ConfigIniFile secrets_ini(_secrets_file);
1260 
1261  IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1262 
1263  /* If we newly create the private/secrets file, add a dummy group on top
1264  * just so we can add a comment before it (that is how IniFile works).
1265  * This to explain what the file is about. After doing it once, never touch
1266  * it again, as otherwise we might be reverting user changes. */
1267  if (!private_ini.GetGroup("private", false)) private_ini.GetGroup("private")->comment = "; This file possibly contains private information which can identify you as person.\n";
1268  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";
1269 
1270  if (generic_version == IFV_0) {
1271  /* Remove some obsolete groups. These have all been loaded into other groups. */
1272  generic_ini.RemoveGroup("patches");
1273  generic_ini.RemoveGroup("yapf");
1274  generic_ini.RemoveGroup("gameopt");
1275 
1276  /* Remove all settings from the generic ini that are now in the private ini. */
1277  generic_ini.RemoveGroup("server_bind_addresses");
1278  generic_ini.RemoveGroup("servers");
1279  generic_ini.RemoveGroup("bans");
1280  for (auto &table : PrivateSettingTables()) {
1281  RemoveEntriesFromIni(generic_ini, table);
1282  }
1283 
1284  /* Remove all settings from the generic ini that are now in the secrets ini. */
1285  for (auto &table : SecretSettingTables()) {
1286  RemoveEntriesFromIni(generic_ini, table);
1287  }
1288  }
1289 
1290  /* Remove network.server_advertise. */
1291  if (generic_version < IFV_GAME_TYPE) {
1292  IniGroup *network = generic_ini.GetGroup("network", false);
1293  if (network != nullptr) {
1294  network->RemoveItem("server_advertise");
1295  }
1296  }
1297 
1298  HandleSettingDescs(generic_ini, private_ini, secrets_ini, IniSaveSettings, IniSaveSettingList);
1299  GRFSaveConfig(generic_ini, "newgrf", _grfconfig_newgame);
1300  GRFSaveConfig(generic_ini, "newgrf-static", _grfconfig_static);
1301  AISaveConfig(generic_ini, "ai_players");
1302  GameSaveConfig(generic_ini, "game_scripts");
1303 
1304  SaveVersionInConfig(generic_ini);
1305  SaveVersionInConfig(private_ini);
1306  SaveVersionInConfig(secrets_ini);
1307 
1308  generic_ini.SaveToDisk(_config_file);
1309  private_ini.SaveToDisk(_private_file);
1310  secrets_ini.SaveToDisk(_secrets_file);
1311 }
1312 
1318 {
1319  StringList list;
1320 
1322  for (IniGroup *group = ini.group; group != nullptr; group = group->next) {
1323  if (group->name.compare(0, 7, "preset-") == 0) {
1324  list.push_back(group->name.substr(7));
1325  }
1326  }
1327 
1328  return list;
1329 }
1330 
1337 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1338 {
1339  size_t len = strlen(config_name) + 8;
1340  char *section = (char*)alloca(len);
1341  seprintf(section, section + len - 1, "preset-%s", config_name);
1342 
1344  GRFConfig *config = GRFLoadConfig(ini, section, false);
1345 
1346  return config;
1347 }
1348 
1355 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1356 {
1357  size_t len = strlen(config_name) + 8;
1358  char *section = (char*)alloca(len);
1359  seprintf(section, section + len - 1, "preset-%s", config_name);
1360 
1362  GRFSaveConfig(ini, section, config);
1363  ini.SaveToDisk(_config_file);
1364 }
1365 
1370 void DeleteGRFPresetFromConfig(const char *config_name)
1371 {
1372  size_t len = strlen(config_name) + 8;
1373  char *section = (char*)alloca(len);
1374  seprintf(section, section + len - 1, "preset-%s", config_name);
1375 
1377  ini.RemoveGroup(section);
1378  ini.SaveToDisk(_config_file);
1379 }
1380 
1387 void IntSettingDesc::ChangeValue(const void *object, int32 newval) const
1388 {
1389  int32 oldval = this->Read(object);
1390  this->MakeValueValid(newval);
1391  if (this->pre_check != nullptr && !this->pre_check(newval)) return;
1392  if (oldval == newval) return;
1393 
1394  this->Write(object, newval);
1395  if (this->post_callback != nullptr) this->post_callback(newval);
1396 
1397  if (this->flags & SF_NO_NETWORK) {
1399  GamelogSetting(this->GetName(), oldval, newval);
1401  }
1402 
1404 
1405  if (_save_config) SaveToConfig();
1406 }
1407 
1415 static const SettingDesc *GetSettingFromName(const std::string_view name, const SettingTable &settings)
1416 {
1417  /* First check all full names */
1418  for (auto &desc : settings) {
1419  const SettingDesc *sd = GetSettingDesc(desc);
1420  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1421  if (sd->GetName() == name) return sd;
1422  }
1423 
1424  /* Then check the shortcut variant of the name. */
1425  std::string short_name_suffix = std::string{ "." }.append(name);
1426  for (auto &desc : settings) {
1427  const SettingDesc *sd = GetSettingDesc(desc);
1428  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1429  if (StrEndsWith(sd->GetName(), short_name_suffix)) return sd;
1430  }
1431 
1432  return nullptr;
1433 }
1434 
1440 void GetSaveLoadFromSettingTable(SettingTable settings, std::vector<SaveLoad> &saveloads)
1441 {
1442  for (auto &desc : settings) {
1443  const SettingDesc *sd = GetSettingDesc(desc);
1444  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1445  saveloads.push_back(sd->save);
1446  }
1447 }
1448 
1455 static const SettingDesc *GetCompanySettingFromName(std::string_view name)
1456 {
1457  static const std::string_view company_prefix = "company.";
1458  if (StrStartsWith(name, company_prefix)) name.remove_prefix(company_prefix.size());
1459  return GetSettingFromName(name, _company_settings);
1460 }
1461 
1468 const SettingDesc *GetSettingFromName(const std::string_view name)
1469 {
1470  for (auto &table : GenericSettingTables()) {
1471  auto sd = GetSettingFromName(name, table);
1472  if (sd != nullptr) return sd;
1473  }
1474  for (auto &table : PrivateSettingTables()) {
1475  auto sd = GetSettingFromName(name, table);
1476  if (sd != nullptr) return sd;
1477  }
1478  for (auto &table : SecretSettingTables()) {
1479  auto sd = GetSettingFromName(name, table);
1480  if (sd != nullptr) return sd;
1481  }
1482 
1483  return GetCompanySettingFromName(name);
1484 }
1485 
1497 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1498 {
1499  if (text.empty()) return CMD_ERROR;
1500  const SettingDesc *sd = GetSettingFromName(text);
1501 
1502  if (sd == nullptr) return CMD_ERROR;
1504  if (!sd->IsIntSetting()) return CMD_ERROR;
1505 
1506  if (!sd->IsEditable(true)) return CMD_ERROR;
1507 
1508  if (flags & DC_EXEC) {
1509  sd->AsIntSetting()->ChangeValue(&GetGameSettings(), p2);
1510  }
1511 
1512  return CommandCost();
1513 }
1514 
1525 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1526 {
1527  if (text.empty()) return CMD_ERROR;
1528  const SettingDesc *sd = GetCompanySettingFromName(text.c_str());
1529 
1530  if (sd == nullptr) return CMD_ERROR;
1531  if (!sd->IsIntSetting()) return CMD_ERROR;
1532 
1533  if (flags & DC_EXEC) {
1535  }
1536 
1537  return CommandCost();
1538 }
1539 
1547 bool SetSettingValue(const IntSettingDesc *sd, int32 value, bool force_newgame)
1548 {
1549  const IntSettingDesc *setting = sd->AsIntSetting();
1550  if ((setting->flags & SF_PER_COMPANY) != 0) {
1551  if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
1552  return DoCommandP(0, 0, value, CMD_CHANGE_COMPANY_SETTING, nullptr, setting->GetName());
1553  }
1554 
1555  setting->ChangeValue(&_settings_client.company, value);
1556  return true;
1557  }
1558 
1559  /* If an item is company-based, we do not send it over the network
1560  * (if any) to change. Also *hack*hack* we update the _newgame version
1561  * of settings because changing a company-based setting in a game also
1562  * changes its defaults. At least that is the convention we have chosen */
1563  if (setting->flags & SF_NO_NETWORK_SYNC) {
1564  if (_game_mode != GM_MENU) {
1565  setting->ChangeValue(&_settings_newgame, value);
1566  }
1567  setting->ChangeValue(&GetGameSettings(), value);
1568  return true;
1569  }
1570 
1571  if (force_newgame) {
1572  setting->ChangeValue(&_settings_newgame, value);
1573  return true;
1574  }
1575 
1576  /* send non-company-based settings over the network */
1577  if (!_networking || (_networking && _network_server)) {
1578  return DoCommandP(0, 0, value, CMD_CHANGE_SETTING, nullptr, setting->GetName());
1579  }
1580  return false;
1581 }
1582 
1587 {
1588  Company *c = Company::Get(cid);
1589  for (auto &desc : _company_settings) {
1590  const IntSettingDesc *int_setting = GetSettingDesc(desc)->AsIntSetting();
1591  int_setting->MakeValueValidAndWrite(&c->settings, int_setting->def);
1592  }
1593 }
1594 
1599 {
1600  const void *old_object = &Company::Get(_current_company)->settings;
1601  const void *new_object = &_settings_client.company;
1602  for (auto &desc : _company_settings) {
1603  const SettingDesc *sd = GetSettingDesc(desc);
1604  uint32 old_value = (uint32)sd->AsIntSetting()->Read(new_object);
1605  uint32 new_value = (uint32)sd->AsIntSetting()->Read(old_object);
1606  if (old_value != new_value) NetworkSendCommand(0, 0, new_value, CMD_CHANGE_COMPANY_SETTING, nullptr, sd->GetName(), _local_company);
1607  }
1608 }
1609 
1617 bool SetSettingValue(const StringSettingDesc *sd, std::string value, bool force_newgame)
1618 {
1619  assert(sd->flags & SF_NO_NETWORK_SYNC);
1620 
1621  if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ && value.compare("(null)") == 0) {
1622  value.clear();
1623  }
1624 
1625  const void *object = (_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game;
1626  sd->AsStringSetting()->ChangeValue(object, value);
1627  return true;
1628 }
1629 
1636 void StringSettingDesc::ChangeValue(const void *object, std::string &newval) const
1637 {
1638  this->MakeValueValid(newval);
1639  if (this->pre_check != nullptr && !this->pre_check(newval)) return;
1640 
1641  this->Write(object, newval);
1642  if (this->post_callback != nullptr) this->post_callback(newval);
1643 
1644  if (_save_config) SaveToConfig();
1645 }
1646 
1647 /* Those 2 functions need to be here, else we have to make some stuff non-static
1648  * and besides, it is also better to keep stuff like this at the same place */
1649 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
1650 {
1651  const SettingDesc *sd = GetSettingFromName(name);
1652  if (sd == nullptr) {
1653  IConsolePrint(CC_ERROR, "'{}' is an unknown setting.", name);
1654  return;
1655  }
1656 
1657  bool success = true;
1658  if (sd->IsStringSetting()) {
1659  success = SetSettingValue(sd->AsStringSetting(), value, force_newgame);
1660  } else if (sd->IsIntSetting()) {
1661  const IntSettingDesc *isd = sd->AsIntSetting();
1662  size_t val = isd->ParseValue(value);
1663  if (!_settings_error_list.empty()) {
1664  IConsolePrint(CC_ERROR, "'{}' is not a valid value for this setting.", value);
1665  _settings_error_list.clear();
1666  return;
1667  }
1668  success = SetSettingValue(isd, (int32)val, force_newgame);
1669  }
1670 
1671  if (!success) {
1672  if (_network_server) {
1673  IConsolePrint(CC_ERROR, "This command/variable is not available during network games.");
1674  } else {
1675  IConsolePrint(CC_ERROR, "This command/variable is only available to a network server.");
1676  }
1677  }
1678 }
1679 
1680 void IConsoleSetSetting(const char *name, int value)
1681 {
1682  const SettingDesc *sd = GetSettingFromName(name);
1683  assert(sd != nullptr);
1684  SetSettingValue(sd->AsIntSetting(), value);
1685 }
1686 
1692 void IConsoleGetSetting(const char *name, bool force_newgame)
1693 {
1694  const SettingDesc *sd = GetSettingFromName(name);
1695  if (sd == nullptr) {
1696  IConsolePrint(CC_ERROR, "'{}' is an unknown setting.", name);
1697  return;
1698  }
1699 
1700  const void *object = (_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game;
1701 
1702  if (sd->IsStringSetting()) {
1703  IConsolePrint(CC_INFO, "Current value for '{}' is '{}'.", sd->GetName(), sd->AsStringSetting()->Read(object));
1704  } else if (sd->IsIntSetting()) {
1705  char value[20];
1706  sd->FormatValue(value, lastof(value), object);
1707  const IntSettingDesc *int_setting = sd->AsIntSetting();
1708  IConsolePrint(CC_INFO, "Current value for '{}' is '{}' (min: {}{}, max: {}).",
1709  sd->GetName(), value, (sd->flags & SF_GUI_0_IS_SPECIAL) ? "(0) " : "", int_setting->min, int_setting->max);
1710  }
1711 }
1712 
1713 static void IConsoleListSettingsTable(const SettingTable &table, const char *prefilter)
1714 {
1715  for (auto &desc : table) {
1716  const SettingDesc *sd = GetSettingDesc(desc);
1717  if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1718  if (prefilter != nullptr && sd->GetName().find(prefilter) == std::string::npos) continue;
1719  char value[80];
1720  sd->FormatValue(value, lastof(value), &GetGameSettings());
1721  IConsolePrint(CC_DEFAULT, "{} = {}", sd->GetName(), value);
1722  }
1723 }
1724 
1730 void IConsoleListSettings(const char *prefilter)
1731 {
1732  IConsolePrint(CC_HELP, "All settings with their current value:");
1733 
1734  for (auto &table : GenericSettingTables()) {
1735  IConsoleListSettingsTable(table, prefilter);
1736  }
1737  for (auto &table : PrivateSettingTables()) {
1738  IConsoleListSettingsTable(table, prefilter);
1739  }
1740  for (auto &table : SecretSettingTables()) {
1741  IConsoleListSettingsTable(table, prefilter);
1742  }
1743 
1744  IConsolePrint(CC_HELP, "Use 'setting' command to change a value.");
1745 }
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:348
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:350
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:661
TileIndex
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:83
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:698
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:450
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:591
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:527
RemoveEntriesFromIni
static void RemoveEntriesFromIni(IniFile &ini, const SettingTable &table)
Remove all entries from a settings table from an ini-file.
Definition: settings.cpp:1182
IFV_GAME_TYPE
@ IFV_GAME_TYPE
2 PR#9515 Convert server_advertise to server_game_type.
Definition: settings.cpp:159
SLE_VAR_STR
@ SLE_VAR_STR
string pointer
Definition: saveload.h:591
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:736
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:23
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:952
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:1415
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:849
SetDefaultCompanySettings
void SetDefaultCompanySettings(CompanyID cid)
Set the company settings for a new company to their default values.
Definition: settings.cpp:1586
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:716
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:781
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:356
ST_GAME
@ ST_GAME
Game setting.
Definition: settings_internal.h:62
_network_server
bool _network_server
network-server is active
Definition: network.cpp:58
IntSettingDesc::MakeValueValidAndWrite
void MakeValueValidAndWrite(const void *object, int32 value) const
Make the value valid and then write it to the setting.
Definition: settings.cpp:435
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:818
SaveToConfig
void SaveToConfig()
Save the values to the configuration file.
Definition: settings.cpp:1255
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:55
SettingDesc::IsEditable
bool IsEditable(bool do_command=false) const
Check whether the setting is editable in the current gamemode.
Definition: settings.cpp:802
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:1146
ClampU
static uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:122
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:574
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:589
IntSettingDesc::ChangeValue
void ChangeValue(const void *object, int32 newvalue) const
Handle changing a value.
Definition: settings.cpp:1387
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:194
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:659
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:52
_network_bind_list
StringList _network_bind_list
The addresses to bind on.
Definition: network.cpp:66
StringSettingDesc::Read
const std::string & Read(const void *object) const
Read the string from the the actual setting.
Definition: settings.cpp:553
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:658
_private_file
std::string _private_file
Private configuration file of OpenTTD.
Definition: settings.cpp:57
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:158
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:348
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
NetworkSendCommand
void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const std::string &text, CompanyID company)
Prepare a DoCommand to be send over the network.
Definition: network_command.cpp:136
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:346
genworld.h
SettingDesc::AsStringSetting
const struct StringSettingDesc * AsStringSetting() const
Get the setting description of this setting as a string setting.
Definition: settings.cpp:838
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:406
ConfigIniFile
IniFile to store a configuration.
Definition: settings.cpp:132
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:161
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:383
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:575
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:616
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:643
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:775
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:617
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
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:933
StringSettingDesc::ChangeValue
void ChangeValue(const void *object, std::string &newval) const
Handle changing a string value.
Definition: settings.cpp:1636
GetGRFPresetList
StringList GetGRFPresetList()
Get the list of known NewGrf presets.
Definition: settings.cpp:1317
CommandCost
Common return value for all commands.
Definition: command_type.h:23
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:227
DoCommandP
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:541
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:741
ScriptConfig::GetName
const char * GetName() const
Get the name of the Script.
Definition: script_config.cpp:172
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:106
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:610
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:53
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:367
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:104
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
CmdChangeSetting
CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
Network-safe changing of settings (server-only).
Definition: settings.cpp:1497
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:58
SyncCompanySettings
void SyncCompanySettings()
Sync all company settings in a multiplayer game.
Definition: settings.cpp:1598
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:567
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:182
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:64
DifficultySettings::quantity_sea_lakes
byte quantity_sea_lakes
the amount of seas/lakes
Definition: settings_type.h:87
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
GameSettings
All settings together for the game.
Definition: settings_type.h:573
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:57
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:157
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:318
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:1370
ErrorMessageData
The data of the error message.
Definition: error.h:29
VehicleDefaultSettings
Default settings for vehicles.
Definition: settings_type.h:555
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:763
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:503
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:380
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:1053
LoadGRFPresetFromConfig
GRFConfig * LoadGRFPresetFromConfig(const char *config_name)
Load a NewGRF configuration by preset-name.
Definition: settings.cpp:1337
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:391
WriteValue
void WriteValue(void *ptr, VarType conv, int64 val)
Write the value of a setting.
Definition: saveload.cpp:828
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:58
GenericSettingTables
static auto & GenericSettingTables()
List of all the generic setting tables.
Definition: settings.cpp:73
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:417
NetworkSettings::server_game_type
ServerGameType server_game_type
Server type: local / public / invite-only.
Definition: settings_type.h:276
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:604
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:1730
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:281
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:691
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:95
GameCreationSettings::land_generator
byte land_generator
the landscape generator
Definition: settings_type.h:308
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:1547
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:1065
CmdChangeCompanySetting
CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
Change one of the per-company settings.
Definition: settings.cpp:1525
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:208
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:457
IniSaveWindowSettings
void IniSaveWindowSettings(IniFile &ini, const char *grpname, void *desc)
Save a WindowDesc to config.
Definition: settings.cpp:792
DecodeHexNibble
static int DecodeHexNibble(char c)
Convert a character to a hex nibble value, or -1 otherwise.
Definition: settings.cpp:917
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:104
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
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:535
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:660
IntSettingDesc::Read
int32 Read(const void *object) const
Read the integer from the the actual setting.
Definition: settings.cpp:514
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:592
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:726
SVS_NONE
@ SVS_NONE
Allow nothing and replace nothing.
Definition: string_type.h:49
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:372
StringSettingDesc::Write
void Write(const void *object, const std::string &str) const
Write a string to the actual setting.
Definition: settings.cpp:543
IConsoleGetSetting
void IConsoleGetSetting(const char *name, bool force_newgame)
Output value of a specific setting to the console.
Definition: settings.cpp:1692
network.h
IntSettingDesc::max
uint32 max
maximum values
Definition: settings_internal.h:162
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:378
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:68
ClientSettings::network
NetworkSettings network
settings related to the network
Definition: settings_type.h:593
SaveVersionInConfig
static void SaveVersionInConfig(IniFile &ini)
Save the version of OpenTTD to the ini file.
Definition: settings.cpp:1115
CMD_CHANGE_SETTING
@ CMD_CHANGE_SETTING
change a setting
Definition: command_type.h:309
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:1096
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:1455
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:804
ClientSettings::company
CompanySettings company
default values for per-company settings
Definition: settings_type.h:594
md5sumToString
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:553
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:164
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:67
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:685
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:112
_config_file
std::string _config_file
Configuration file of OpenTTD.
Definition: settings.cpp:56
WC_ERRMSG
@ WC_ERRMSG
Error message; Window numbers:
Definition: window_type.h:102
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:115
game_config.hpp
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3162
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:156
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:394
_settings_error_list
static ErrorList _settings_error_list
Errors while loading minimal settings.
Definition: settings.cpp:61
LoadFromConfig
void LoadFromConfig(bool startup)
Load the values from the configuration files.
Definition: settings.cpp:1203
CMD_CHANGE_COMPANY_SETTING
@ CMD_CHANGE_COMPANY_SETTING
change a company setting
Definition: command_type.h:310
SaveGRFPresetToConfig
void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
Save a NewGRF configuration with a preset name.
Definition: settings.cpp:1355
DebugReconsiderSendRemoteMessages
void DebugReconsiderSendRemoteMessages()
Reconsider whether we need to send debug messages to either NetworkAdminConsole or IConsolePrint.
Definition: debug.cpp:282
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:1440
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:162
IntSettingDesc::def
int32 def
default value given when none is present
Definition: settings_internal.h:160
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:273
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:296
_settings_newgame
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:54
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:173
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:828
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:679
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