Fix: Stopped ships shouldn't block depots (#8578)
[openttd-github.git] / src / settings.cpp
blobd3be5969296319449e4deec3f141ed62518ab63d
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 */
8 /**
9 * @file settings.cpp
10 * All actions handling saving and loading of the settings/configuration goes on in this file.
11 * The file consists of three parts:
12 * <ol>
13 * <li>Parsing the configuration file (openttd.cfg). This is achieved with the ini_ functions which
14 * handle various types, such as normal 'key = value' pairs, lists and value combinations of
15 * lists, strings, integers, 'bit'-masks and element selections.
16 * <li>Handle reading and writing to the setting-structures from inside the game either from
17 * the console for example or through the gui with CMD_ functions.
18 * <li>Handle saving/loading of the PATS chunk inside the savegame.
19 * </ol>
20 * @see SettingDesc
21 * @see SaveLoad
24 #include "stdafx.h"
25 #include <limits>
26 #include "currency.h"
27 #include "screenshot.h"
28 #include "network/network.h"
29 #include "network/network_func.h"
30 #include "settings_internal.h"
31 #include "command_func.h"
32 #include "console_func.h"
33 #include "pathfinder/pathfinder_type.h"
34 #include "genworld.h"
35 #include "train.h"
36 #include "news_func.h"
37 #include "window_func.h"
38 #include "sound_func.h"
39 #include "company_func.h"
40 #include "rev.h"
41 #if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
42 #include "fontcache.h"
43 #endif
44 #include "textbuf_gui.h"
45 #include "rail_gui.h"
46 #include "elrail_func.h"
47 #include "error.h"
48 #include "town.h"
49 #include "video/video_driver.hpp"
50 #include "sound/sound_driver.hpp"
51 #include "music/music_driver.hpp"
52 #include "blitter/factory.hpp"
53 #include "base_media_base.h"
54 #include "gamelog.h"
55 #include "settings_func.h"
56 #include "ini_type.h"
57 #include "ai/ai_config.hpp"
58 #include "ai/ai.hpp"
59 #include "game/game_config.hpp"
60 #include "game/game.hpp"
61 #include "ship.h"
62 #include "smallmap_gui.h"
63 #include "roadveh.h"
64 #include "fios.h"
65 #include "strings_func.h"
67 #include "void_map.h"
68 #include "station_base.h"
70 #if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
71 #define HAS_TRUETYPE_FONT
72 #endif
74 #include "table/strings.h"
75 #include "table/settings.h"
77 #include "safeguards.h"
79 ClientSettings _settings_client;
80 GameSettings _settings_game; ///< Game settings of a running game or the scenario editor.
81 GameSettings _settings_newgame; ///< Game settings for new games (updated from the intro screen).
82 VehicleDefaultSettings _old_vds; ///< Used for loading default vehicles settings from old savegames
83 std::string _config_file; ///< Configuration file of OpenTTD
85 typedef std::list<ErrorMessageData> ErrorList;
86 static ErrorList _settings_error_list; ///< Errors while loading minimal settings.
89 typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
90 typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList &list);
92 static bool IsSignedVarMemType(VarType vt);
94 /**
95 * Groups in openttd.cfg that are actually lists.
97 static const char * const _list_group_names[] = {
98 "bans",
99 "newgrf",
100 "servers",
101 "server_bind_addresses",
102 nullptr
106 * Find the index value of a ONEofMANY type in a string separated by |
107 * @param many full domain of values the ONEofMANY setting can have
108 * @param one the current value of the setting for which a value needs found
109 * @param onelen force calculation of the *one parameter
110 * @return the integer index of the full-list, or -1 if not found
112 static size_t LookupOneOfMany(const char *many, const char *one, size_t onelen = 0)
114 const char *s;
115 size_t idx;
117 if (onelen == 0) onelen = strlen(one);
119 /* check if it's an integer */
120 if (*one >= '0' && *one <= '9') return strtoul(one, nullptr, 0);
122 idx = 0;
123 for (;;) {
124 /* find end of item */
125 s = many;
126 while (*s != '|' && *s != 0) s++;
127 if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
128 if (*s == 0) return (size_t)-1;
129 many = s + 1;
130 idx++;
135 * Find the set-integer value MANYofMANY type in a string
136 * @param many full domain of values the MANYofMANY setting can have
137 * @param str the current string value of the setting, each individual
138 * of separated by a whitespace,tab or | character
139 * @return the 'fully' set integer, or -1 if a set is not found
141 static size_t LookupManyOfMany(const char *many, const char *str)
143 const char *s;
144 size_t r;
145 size_t res = 0;
147 for (;;) {
148 /* skip "whitespace" */
149 while (*str == ' ' || *str == '\t' || *str == '|') str++;
150 if (*str == 0) break;
152 s = str;
153 while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
155 r = LookupOneOfMany(many, str, s - str);
156 if (r == (size_t)-1) return r;
158 SetBit(res, (uint8)r); // value found, set it
159 if (*s == 0) break;
160 str = s + 1;
162 return res;
166 * Parse an integerlist string and set each found value
167 * @param p the string to be parsed. Each element in the list is separated by a
168 * comma or a space character
169 * @param items pointer to the integerlist-array that will be filled with values
170 * @param maxitems the maximum number of elements the integerlist-array has
171 * @return returns the number of items found, or -1 on an error
173 template<typename T>
174 static int ParseIntList(const char *p, T *items, int maxitems)
176 int n = 0; // number of items read so far
177 bool comma = false; // do we accept comma?
179 while (*p != '\0') {
180 switch (*p) {
181 case ',':
182 /* Do not accept multiple commas between numbers */
183 if (!comma) return -1;
184 comma = false;
185 FALLTHROUGH;
187 case ' ':
188 p++;
189 break;
191 default: {
192 if (n == maxitems) return -1; // we don't accept that many numbers
193 char *end;
194 unsigned long v = strtoul(p, &end, 0);
195 if (p == end) return -1; // invalid character (not a number)
196 if (sizeof(T) < sizeof(v)) v = Clamp<unsigned long>(v, std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
197 items[n++] = v;
198 p = end; // first non-number
199 comma = true; // we accept comma now
200 break;
205 /* If we have read comma but no number after it, fail.
206 * We have read comma when (n != 0) and comma is not allowed */
207 if (n != 0 && !comma) return -1;
209 return n;
213 * Load parsed string-values into an integer-array (intlist)
214 * @param str the string that contains the values (and will be parsed)
215 * @param array pointer to the integer-arrays that will be filled
216 * @param nelems the number of elements the array holds. Maximum is 64 elements
217 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
218 * @return return true on success and false on error
220 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
222 unsigned long items[64];
223 int i, nitems;
225 if (str == nullptr) {
226 memset(items, 0, sizeof(items));
227 nitems = nelems;
228 } else {
229 nitems = ParseIntList(str, items, lengthof(items));
230 if (nitems != nelems) return false;
233 switch (type) {
234 case SLE_VAR_BL:
235 case SLE_VAR_I8:
236 case SLE_VAR_U8:
237 for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
238 break;
240 case SLE_VAR_I16:
241 case SLE_VAR_U16:
242 for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
243 break;
245 case SLE_VAR_I32:
246 case SLE_VAR_U32:
247 for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
248 break;
250 default: NOT_REACHED();
253 return true;
257 * Convert an integer-array (intlist) to a string representation. Each value
258 * is separated by a comma or a space character
259 * @param buf output buffer where the string-representation will be stored
260 * @param last last item to write to in the output buffer
261 * @param array pointer to the integer-arrays that is read from
262 * @param nelems the number of elements the array holds.
263 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
265 static void MakeIntList(char *buf, const char *last, const void *array, int nelems, VarType type)
267 int i, v = 0;
268 const byte *p = (const byte *)array;
270 for (i = 0; i != nelems; i++) {
271 switch (GetVarMemType(type)) {
272 case SLE_VAR_BL:
273 case SLE_VAR_I8: v = *(const int8 *)p; p += 1; break;
274 case SLE_VAR_U8: v = *(const uint8 *)p; p += 1; break;
275 case SLE_VAR_I16: v = *(const int16 *)p; p += 2; break;
276 case SLE_VAR_U16: v = *(const uint16 *)p; p += 2; break;
277 case SLE_VAR_I32: v = *(const int32 *)p; p += 4; break;
278 case SLE_VAR_U32: v = *(const uint32 *)p; p += 4; break;
279 default: NOT_REACHED();
281 if (IsSignedVarMemType(type)) {
282 buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
283 } else if (type & SLF_HEX) {
284 buf += seprintf(buf, last, (i == 0) ? "0x%X" : ",0x%X", v);
285 } else {
286 buf += seprintf(buf, last, (i == 0) ? "%u" : ",%u", v);
292 * Convert a ONEofMANY structure to a string representation.
293 * @param buf output buffer where the string-representation will be stored
294 * @param last last item to write to in the output buffer
295 * @param many the full-domain string of possible values
296 * @param id the value of the variable and whose string-representation must be found
298 static void MakeOneOfMany(char *buf, const char *last, const char *many, int id)
300 int orig_id = id;
302 /* Look for the id'th element */
303 while (--id >= 0) {
304 for (; *many != '|'; many++) {
305 if (*many == '\0') { // not found
306 seprintf(buf, last, "%d", orig_id);
307 return;
310 many++; // pass the |-character
313 /* copy string until next item (|) or the end of the list if this is the last one */
314 while (*many != '\0' && *many != '|' && buf < last) *buf++ = *many++;
315 *buf = '\0';
319 * Convert a MANYofMANY structure to a string representation.
320 * @param buf output buffer where the string-representation will be stored
321 * @param last last item to write to in the output buffer
322 * @param many the full-domain string of possible values
323 * @param x the value of the variable and whose string-representation must
324 * be found in the bitmasked many string
326 static void MakeManyOfMany(char *buf, const char *last, const char *many, uint32 x)
328 const char *start;
329 int i = 0;
330 bool init = true;
332 for (; x != 0; x >>= 1, i++) {
333 start = many;
334 while (*many != 0 && *many != '|') many++; // advance to the next element
336 if (HasBit(x, 0)) { // item found, copy it
337 if (!init) buf += seprintf(buf, last, "|");
338 init = false;
339 if (start == many) {
340 buf += seprintf(buf, last, "%d", i);
341 } else {
342 memcpy(buf, start, many - start);
343 buf += many - start;
347 if (*many == '|') many++;
350 *buf = '\0';
354 * Convert a string representation (external) of a setting to the internal rep.
355 * @param desc SettingDesc struct that holds all information about the variable
356 * @param orig_str input string that will be parsed based on the type of desc
357 * @return return the parsed value of the setting
359 static const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
361 const char *str = orig_str == nullptr ? "" : orig_str;
363 switch (desc->cmd) {
364 case SDT_NUMX: {
365 char *end;
366 size_t val = strtoul(str, &end, 0);
367 if (end == str) {
368 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
369 msg.SetDParamStr(0, str);
370 msg.SetDParamStr(1, desc->name);
371 _settings_error_list.push_back(msg);
372 return desc->def;
374 if (*end != '\0') {
375 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_TRAILING_CHARACTERS);
376 msg.SetDParamStr(0, desc->name);
377 _settings_error_list.push_back(msg);
379 return (void*)val;
382 case SDT_ONEOFMANY: {
383 size_t r = LookupOneOfMany(desc->many, str);
384 /* if the first attempt of conversion from string to the appropriate value fails,
385 * look if we have defined a converter from old value to new value. */
386 if (r == (size_t)-1 && desc->proc_cnvt != nullptr) r = desc->proc_cnvt(str);
387 if (r != (size_t)-1) return (void*)r; // and here goes converted value
389 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
390 msg.SetDParamStr(0, str);
391 msg.SetDParamStr(1, desc->name);
392 _settings_error_list.push_back(msg);
393 return desc->def;
396 case SDT_MANYOFMANY: {
397 size_t r = LookupManyOfMany(desc->many, str);
398 if (r != (size_t)-1) return (void*)r;
399 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
400 msg.SetDParamStr(0, str);
401 msg.SetDParamStr(1, desc->name);
402 _settings_error_list.push_back(msg);
403 return desc->def;
406 case SDT_BOOLX: {
407 if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0) return (void*)true;
408 if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return (void*)false;
410 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
411 msg.SetDParamStr(0, str);
412 msg.SetDParamStr(1, desc->name);
413 _settings_error_list.push_back(msg);
414 return desc->def;
417 case SDT_STDSTRING:
418 case SDT_STRING: return orig_str;
419 case SDT_INTLIST: return str;
420 default: break;
423 return nullptr;
427 * Set the value of a setting and if needed clamp the value to
428 * the preset minimum and maximum.
429 * @param ptr the variable itself
430 * @param sd pointer to the 'information'-database of the variable
431 * @param val signed long version of the new value
432 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
433 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
435 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
437 const SettingDescBase *sdb = &sd->desc;
439 if (sdb->cmd != SDT_BOOLX &&
440 sdb->cmd != SDT_NUMX &&
441 sdb->cmd != SDT_ONEOFMANY &&
442 sdb->cmd != SDT_MANYOFMANY) {
443 return;
446 /* We cannot know the maximum value of a bitset variable, so just have faith */
447 if (sdb->cmd != SDT_MANYOFMANY) {
448 /* We need to take special care of the uint32 type as we receive from the function
449 * a signed integer. While here also bail out on 64-bit settings as those are not
450 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
451 * 32-bit variable
452 * TODO: Support 64-bit settings/variables */
453 switch (GetVarMemType(sd->save.conv)) {
454 case SLE_VAR_NULL: return;
455 case SLE_VAR_BL:
456 case SLE_VAR_I8:
457 case SLE_VAR_U8:
458 case SLE_VAR_I16:
459 case SLE_VAR_U16:
460 case SLE_VAR_I32: {
461 /* Override the minimum value. No value below sdb->min, except special value 0 */
462 if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) {
463 if (!(sdb->flags & SGF_MULTISTRING)) {
464 /* Clamp value-type setting to its valid range */
465 val = Clamp(val, sdb->min, sdb->max);
466 } else if (val < sdb->min || val > (int32)sdb->max) {
467 /* Reset invalid discrete setting (where different values change gameplay) to its default value */
468 val = (int32)(size_t)sdb->def;
471 break;
473 case SLE_VAR_U32: {
474 /* Override the minimum value. No value below sdb->min, except special value 0 */
475 uint32 uval = (uint32)val;
476 if (!(sdb->flags & SGF_0ISDISABLED) || uval != 0) {
477 if (!(sdb->flags & SGF_MULTISTRING)) {
478 /* Clamp value-type setting to its valid range */
479 uval = ClampU(uval, sdb->min, sdb->max);
480 } else if (uval < (uint)sdb->min || uval > sdb->max) {
481 /* Reset invalid discrete setting to its default value */
482 uval = (uint32)(size_t)sdb->def;
485 WriteValue(ptr, SLE_VAR_U32, (int64)uval);
486 return;
488 case SLE_VAR_I64:
489 case SLE_VAR_U64:
490 default: NOT_REACHED();
494 WriteValue(ptr, sd->save.conv, (int64)val);
498 * Load values from a group of an IniFile structure into the internal representation
499 * @param ini pointer to IniFile structure that holds administrative information
500 * @param sd pointer to SettingDesc structure whose internally pointed variables will
501 * be given values
502 * @param grpname the group of the IniFile to search in for the new values
503 * @param object pointer to the object been loaded
505 static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
507 IniGroup *group;
508 IniGroup *group_def = ini->GetGroup(grpname);
510 for (; sd->save.cmd != SL_END; sd++) {
511 const SettingDescBase *sdb = &sd->desc;
512 const SaveLoad *sld = &sd->save;
514 if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
516 /* For settings.xx.yy load the settings from [xx] yy = ? */
517 std::string s{ sdb->name };
518 auto sc = s.find('.');
519 if (sc != std::string::npos) {
520 group = ini->GetGroup(s.substr(0, sc));
521 s = s.substr(sc + 1);
522 } else {
523 group = group_def;
526 IniItem *item = group->GetItem(s, false);
527 if (item == nullptr && group != group_def) {
528 /* For settings.xx.yy load the settings from [settings] yy = ? in case the previous
529 * did not exist (e.g. loading old config files with a [settings] section */
530 item = group_def->GetItem(s, false);
532 if (item == nullptr) {
533 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
534 * did not exist (e.g. loading old config files with a [yapf] section */
535 sc = s.find('.');
536 if (sc != std::string::npos) item = ini->GetGroup(s.substr(0, sc))->GetItem(s.substr(sc + 1), false);
539 const void *p = (item == nullptr) ? sdb->def : StringToVal(sdb, item->value.has_value() ? item->value->c_str() : nullptr);
540 void *ptr = GetVariableAddress(object, sld);
542 switch (sdb->cmd) {
543 case SDT_BOOLX: // All four are various types of (integer) numbers
544 case SDT_NUMX:
545 case SDT_ONEOFMANY:
546 case SDT_MANYOFMANY:
547 Write_ValidateSetting(ptr, sd, (int32)(size_t)p);
548 break;
550 case SDT_STRING:
551 switch (GetVarMemType(sld->conv)) {
552 case SLE_VAR_STRB:
553 case SLE_VAR_STRBQ:
554 if (p != nullptr) strecpy((char*)ptr, (const char*)p, (char*)ptr + sld->length - 1);
555 break;
557 case SLE_VAR_STR:
558 case SLE_VAR_STRQ:
559 free(*(char**)ptr);
560 *(char**)ptr = p == nullptr ? nullptr : stredup((const char*)p);
561 break;
563 case SLE_VAR_CHAR: if (p != nullptr) *(char *)ptr = *(const char *)p; break;
565 default: NOT_REACHED();
567 break;
569 case SDT_STDSTRING:
570 switch (GetVarMemType(sld->conv)) {
571 case SLE_VAR_STR:
572 case SLE_VAR_STRQ:
573 if (p != nullptr) {
574 reinterpret_cast<std::string *>(ptr)->assign((const char *)p);
575 } else {
576 reinterpret_cast<std::string *>(ptr)->clear();
578 break;
580 default: NOT_REACHED();
583 break;
585 case SDT_INTLIST: {
586 if (!LoadIntList((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
587 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY);
588 msg.SetDParamStr(0, sdb->name);
589 _settings_error_list.push_back(msg);
591 /* Use default */
592 LoadIntList((const char*)sdb->def, ptr, sld->length, GetVarMemType(sld->conv));
593 } else if (sd->desc.proc_cnvt != nullptr) {
594 sd->desc.proc_cnvt((const char*)p);
596 break;
598 default: NOT_REACHED();
604 * Save the values of settings to the inifile.
605 * @param ini pointer to IniFile structure
606 * @param sd read-only SettingDesc structure which contains the unmodified,
607 * loaded values of the configuration file and various information about it
608 * @param grpname holds the name of the group (eg. [network]) where these will be saved
609 * @param object pointer to the object been saved
610 * The function works as follows: for each item in the SettingDesc structure we
611 * have a look if the value has changed since we started the game (the original
612 * values are reloaded when saving). If settings indeed have changed, we get
613 * these and save them.
615 static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
617 IniGroup *group_def = nullptr, *group;
618 IniItem *item;
619 char buf[512];
620 void *ptr;
622 for (; sd->save.cmd != SL_END; sd++) {
623 const SettingDescBase *sdb = &sd->desc;
624 const SaveLoad *sld = &sd->save;
626 /* If the setting is not saved to the configuration
627 * file, just continue with the next setting */
628 if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
629 if (sld->conv & SLF_NOT_IN_CONFIG) continue;
631 /* XXX - wtf is this?? (group override?) */
632 std::string s{ sdb->name };
633 auto sc = s.find('.');
634 if (sc != std::string::npos) {
635 group = ini->GetGroup(s.substr(0, sc));
636 s = s.substr(sc + 1);
637 } else {
638 if (group_def == nullptr) group_def = ini->GetGroup(grpname);
639 group = group_def;
642 item = group->GetItem(s, true);
643 ptr = GetVariableAddress(object, sld);
645 if (item->value.has_value()) {
646 /* check if the value is the same as the old value */
647 const void *p = StringToVal(sdb, item->value->c_str());
649 /* The main type of a variable/setting is in bytes 8-15
650 * The subtype (what kind of numbers do we have there) is in 0-7 */
651 switch (sdb->cmd) {
652 case SDT_BOOLX:
653 case SDT_NUMX:
654 case SDT_ONEOFMANY:
655 case SDT_MANYOFMANY:
656 switch (GetVarMemType(sld->conv)) {
657 case SLE_VAR_BL:
658 if (*(bool*)ptr == (p != nullptr)) continue;
659 break;
661 case SLE_VAR_I8:
662 case SLE_VAR_U8:
663 if (*(byte*)ptr == (byte)(size_t)p) continue;
664 break;
666 case SLE_VAR_I16:
667 case SLE_VAR_U16:
668 if (*(uint16*)ptr == (uint16)(size_t)p) continue;
669 break;
671 case SLE_VAR_I32:
672 case SLE_VAR_U32:
673 if (*(uint32*)ptr == (uint32)(size_t)p) continue;
674 break;
676 default: NOT_REACHED();
678 break;
680 default: break; // Assume the other types are always changed
684 /* Value has changed, get the new value and put it into a buffer */
685 switch (sdb->cmd) {
686 case SDT_BOOLX:
687 case SDT_NUMX:
688 case SDT_ONEOFMANY:
689 case SDT_MANYOFMANY: {
690 uint32 i = (uint32)ReadValue(ptr, sld->conv);
692 switch (sdb->cmd) {
693 case SDT_BOOLX: strecpy(buf, (i != 0) ? "true" : "false", lastof(buf)); break;
694 case SDT_NUMX: seprintf(buf, lastof(buf), IsSignedVarMemType(sld->conv) ? "%d" : (sld->conv & SLF_HEX) ? "%X" : "%u", i); break;
695 case SDT_ONEOFMANY: MakeOneOfMany(buf, lastof(buf), sdb->many, i); break;
696 case SDT_MANYOFMANY: MakeManyOfMany(buf, lastof(buf), sdb->many, i); break;
697 default: NOT_REACHED();
699 break;
702 case SDT_STRING:
703 switch (GetVarMemType(sld->conv)) {
704 case SLE_VAR_STRB: strecpy(buf, (char*)ptr, lastof(buf)); break;
705 case SLE_VAR_STRBQ:seprintf(buf, lastof(buf), "\"%s\"", (char*)ptr); break;
706 case SLE_VAR_STR: strecpy(buf, *(char**)ptr, lastof(buf)); break;
708 case SLE_VAR_STRQ:
709 if (*(char**)ptr == nullptr) {
710 buf[0] = '\0';
711 } else {
712 seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
714 break;
716 case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
717 default: NOT_REACHED();
719 break;
721 case SDT_STDSTRING:
722 switch (GetVarMemType(sld->conv)) {
723 case SLE_VAR_STR: strecpy(buf, reinterpret_cast<std::string *>(ptr)->c_str(), lastof(buf)); break;
725 case SLE_VAR_STRQ:
726 if (reinterpret_cast<std::string *>(ptr)->empty()) {
727 buf[0] = '\0';
728 } else {
729 seprintf(buf, lastof(buf), "\"%s\"", reinterpret_cast<std::string *>(ptr)->c_str());
731 break;
733 default: NOT_REACHED();
735 break;
737 case SDT_INTLIST:
738 MakeIntList(buf, lastof(buf), ptr, sld->length, sld->conv);
739 break;
741 default: NOT_REACHED();
744 /* The value is different, that means we have to write it to the ini */
745 item->value.emplace(buf);
750 * Loads all items from a 'grpname' section into a list
751 * The list parameter can be a nullptr pointer, in this case nothing will be
752 * saved and a callback function should be defined that will take over the
753 * list-handling and store the data itself somewhere.
754 * @param ini IniFile handle to the ini file with the source data
755 * @param grpname character string identifying the section-header of the ini file that will be parsed
756 * @param list new list with entries of the given section
758 static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList &list)
760 IniGroup *group = ini->GetGroup(grpname);
762 if (group == nullptr) return;
764 list.clear();
766 for (const IniItem *item = group->item; item != nullptr; item = item->next) {
767 if (!item->name.empty()) list.push_back(item->name);
772 * Saves all items from a list into the 'grpname' section
773 * The list parameter can be a nullptr pointer, in this case a callback function
774 * should be defined that will provide the source data to be saved.
775 * @param ini IniFile handle to the ini file where the destination data is saved
776 * @param grpname character string identifying the section-header of the ini file
777 * @param list pointer to an string(pointer) array that will be used as the
778 * source to be saved into the relevant ini section
780 static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList &list)
782 IniGroup *group = ini->GetGroup(grpname);
784 if (group == nullptr) return;
785 group->Clear();
787 for (const auto &iter : list) {
788 group->GetItem(iter.c_str(), true)->SetValue("");
793 * Load a WindowDesc from config.
794 * @param ini IniFile handle to the ini file with the source data
795 * @param grpname character string identifying the section-header of the ini file that will be parsed
796 * @param desc Destination WindowDesc
798 void IniLoadWindowSettings(IniFile *ini, const char *grpname, void *desc)
800 IniLoadSettings(ini, _window_settings, grpname, desc);
804 * Save a WindowDesc to config.
805 * @param ini IniFile handle to the ini file where the destination data is saved
806 * @param grpname character string identifying the section-header of the ini file
807 * @param desc Source WindowDesc
809 void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc)
811 IniSaveSettings(ini, _window_settings, grpname, desc);
815 * Check whether the setting is editable in the current gamemode.
816 * @param do_command true if this is about checking a command from the server.
817 * @return true if editable.
819 bool SettingDesc::IsEditable(bool do_command) const
821 if (!do_command && !(this->save.conv & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->desc.flags & SGF_PER_COMPANY)) return false;
822 if ((this->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
823 if ((this->desc.flags & SGF_NO_NETWORK) && _networking) return false;
824 if ((this->desc.flags & SGF_NEWGAME_ONLY) &&
825 (_game_mode == GM_NORMAL ||
826 (_game_mode == GM_EDITOR && !(this->desc.flags & SGF_SCENEDIT_TOO)))) return false;
827 return true;
831 * Return the type of the setting.
832 * @return type of setting
834 SettingType SettingDesc::GetType() const
836 if (this->desc.flags & SGF_PER_COMPANY) return ST_COMPANY;
837 return (this->save.conv & SLF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
840 /* Begin - Callback Functions for the various settings. */
842 /** Reposition the main toolbar as the setting changed. */
843 static bool v_PositionMainToolbar(int32 p1)
845 if (_game_mode != GM_MENU) PositionMainToolbar(nullptr);
846 return true;
849 /** Reposition the statusbar as the setting changed. */
850 static bool v_PositionStatusbar(int32 p1)
852 if (_game_mode != GM_MENU) {
853 PositionStatusbar(nullptr);
854 PositionNewsMessage(nullptr);
855 PositionNetworkChatWindow(nullptr);
857 return true;
860 static bool PopulationInLabelActive(int32 p1)
862 UpdateAllTownVirtCoords();
863 return true;
866 static bool RedrawScreen(int32 p1)
868 MarkWholeScreenDirty();
869 return true;
873 * Redraw the smallmap after a colour scheme change.
874 * @param p1 Callback parameter.
875 * @return Always true.
877 static bool RedrawSmallmap(int32 p1)
879 BuildLandLegend();
880 BuildOwnerLegend();
881 SetWindowClassesDirty(WC_SMALLMAP);
882 return true;
885 static bool InvalidateDetailsWindow(int32 p1)
887 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
888 return true;
891 static bool StationSpreadChanged(int32 p1)
893 InvalidateWindowData(WC_SELECT_STATION, 0);
894 InvalidateWindowData(WC_BUILD_STATION, 0);
895 return true;
898 static bool InvalidateBuildIndustryWindow(int32 p1)
900 InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
901 return true;
904 static bool CloseSignalGUI(int32 p1)
906 if (p1 == 0) {
907 DeleteWindowByClass(WC_BUILD_SIGNAL);
909 return true;
912 static bool InvalidateTownViewWindow(int32 p1)
914 InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
915 return true;
918 static bool DeleteSelectStationWindow(int32 p1)
920 DeleteWindowById(WC_SELECT_STATION, 0);
921 return true;
924 static bool UpdateConsists(int32 p1)
926 for (Train *t : Train::Iterate()) {
927 /* Update the consist of all trains so the maximum speed is set correctly. */
928 if (t->IsFrontEngine() || t->IsFreeWagon()) t->ConsistChanged(CCF_TRACK);
930 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
931 return true;
934 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
935 static bool CheckInterval(int32 p1)
937 bool update_vehicles;
938 VehicleDefaultSettings *vds;
939 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
940 vds = &_settings_client.company.vehicle;
941 update_vehicles = false;
942 } else {
943 vds = &Company::Get(_current_company)->settings.vehicle;
944 update_vehicles = true;
947 if (p1 != 0) {
948 vds->servint_trains = 50;
949 vds->servint_roadveh = 50;
950 vds->servint_aircraft = 50;
951 vds->servint_ships = 50;
952 } else {
953 vds->servint_trains = 150;
954 vds->servint_roadveh = 150;
955 vds->servint_aircraft = 100;
956 vds->servint_ships = 360;
959 if (update_vehicles) {
960 const Company *c = Company::Get(_current_company);
961 for (Vehicle *v : Vehicle::Iterate()) {
962 if (v->owner == _current_company && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
963 v->SetServiceInterval(CompanyServiceInterval(c, v->type));
964 v->SetServiceIntervalIsPercent(p1 != 0);
969 InvalidateDetailsWindow(0);
971 return true;
974 static bool UpdateInterval(VehicleType type, int32 p1)
976 bool update_vehicles;
977 VehicleDefaultSettings *vds;
978 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
979 vds = &_settings_client.company.vehicle;
980 update_vehicles = false;
981 } else {
982 vds = &Company::Get(_current_company)->settings.vehicle;
983 update_vehicles = true;
986 /* Test if the interval is valid */
987 uint16 interval = GetServiceIntervalClamped(p1, vds->servint_ispercent);
988 if (interval != p1) return false;
990 if (update_vehicles) {
991 for (Vehicle *v : Vehicle::Iterate()) {
992 if (v->owner == _current_company && v->type == type && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
993 v->SetServiceInterval(p1);
998 InvalidateDetailsWindow(0);
1000 return true;
1003 static bool UpdateIntervalTrains(int32 p1)
1005 return UpdateInterval(VEH_TRAIN, p1);
1008 static bool UpdateIntervalRoadVeh(int32 p1)
1010 return UpdateInterval(VEH_ROAD, p1);
1013 static bool UpdateIntervalShips(int32 p1)
1015 return UpdateInterval(VEH_SHIP, p1);
1018 static bool UpdateIntervalAircraft(int32 p1)
1020 return UpdateInterval(VEH_AIRCRAFT, p1);
1023 static bool TrainAccelerationModelChanged(int32 p1)
1025 for (Train *t : Train::Iterate()) {
1026 if (t->IsFrontEngine()) {
1027 t->tcache.cached_max_curve_speed = t->GetCurveSpeedLimit();
1028 t->UpdateAcceleration();
1032 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1033 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
1034 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
1035 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
1037 return true;
1041 * This function updates the train acceleration cache after a steepness change.
1042 * @param p1 Callback parameter.
1043 * @return Always true.
1045 static bool TrainSlopeSteepnessChanged(int32 p1)
1047 for (Train *t : Train::Iterate()) {
1048 if (t->IsFrontEngine()) t->CargoChanged();
1051 return true;
1055 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
1056 * @param p1 Callback parameter
1057 * @return Always true
1059 static bool RoadVehAccelerationModelChanged(int32 p1)
1061 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
1062 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1063 if (rv->IsFrontEngine()) {
1064 rv->CargoChanged();
1069 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1070 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
1071 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
1072 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
1074 return true;
1078 * This function updates the road vehicle acceleration cache after a steepness change.
1079 * @param p1 Callback parameter.
1080 * @return Always true.
1082 static bool RoadVehSlopeSteepnessChanged(int32 p1)
1084 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1085 if (rv->IsFrontEngine()) rv->CargoChanged();
1088 return true;
1091 static bool DragSignalsDensityChanged(int32)
1093 InvalidateWindowData(WC_BUILD_SIGNAL, 0);
1095 return true;
1098 static bool TownFoundingChanged(int32 p1)
1100 if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
1101 DeleteWindowById(WC_FOUND_TOWN, 0);
1102 return true;
1104 InvalidateWindowData(WC_FOUND_TOWN, 0);
1105 return true;
1108 static bool InvalidateVehTimetableWindow(int32 p1)
1110 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, VIWD_MODIFY_ORDERS);
1111 return true;
1114 static bool ZoomMinMaxChanged(int32 p1)
1116 extern void ConstrainAllViewportsZoom();
1117 ConstrainAllViewportsZoom();
1118 GfxClearSpriteCache();
1119 if (_settings_client.gui.zoom_min > _gui_zoom) {
1120 /* Restrict GUI zoom if it is no longer available. */
1121 _gui_zoom = _settings_client.gui.zoom_min;
1122 UpdateCursorSize();
1123 LoadStringWidthTable();
1125 return true;
1129 * Update any possible saveload window and delete any newgrf dialogue as
1130 * its widget parts might change. Reinit all windows as it allows access to the
1131 * newgrf debug button.
1132 * @param p1 unused.
1133 * @return Always true.
1135 static bool InvalidateNewGRFChangeWindows(int32 p1)
1137 InvalidateWindowClassesData(WC_SAVELOAD);
1138 DeleteWindowByClass(WC_GAME_OPTIONS);
1139 ReInitAllWindows();
1140 return true;
1143 static bool InvalidateCompanyLiveryWindow(int32 p1)
1145 InvalidateWindowClassesData(WC_COMPANY_COLOUR, -1);
1146 return RedrawScreen(p1);
1149 static bool InvalidateIndustryViewWindow(int32 p1)
1151 InvalidateWindowClassesData(WC_INDUSTRY_VIEW);
1152 return true;
1155 static bool InvalidateAISettingsWindow(int32 p1)
1157 InvalidateWindowClassesData(WC_AI_SETTINGS);
1158 return true;
1162 * Update the town authority window after a town authority setting change.
1163 * @param p1 Unused.
1164 * @return Always true.
1166 static bool RedrawTownAuthority(int32 p1)
1168 SetWindowClassesDirty(WC_TOWN_AUTHORITY);
1169 return true;
1173 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1174 * @param p1 Unused.
1175 * @return Always true.
1177 static bool InvalidateCompanyInfrastructureWindow(int32 p1)
1179 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
1180 return true;
1184 * Invalidate the company details window after the shares setting changed.
1185 * @param p1 Unused.
1186 * @return Always true.
1188 static bool InvalidateCompanyWindow(int32 p1)
1190 InvalidateWindowClassesData(WC_COMPANY);
1191 return true;
1194 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1195 static void ValidateSettings()
1197 /* Do not allow a custom sea level with the original land generator. */
1198 if (_settings_newgame.game_creation.land_generator == LG_ORIGINAL &&
1199 _settings_newgame.difficulty.quantity_sea_lakes == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) {
1200 _settings_newgame.difficulty.quantity_sea_lakes = CUSTOM_SEA_LEVEL_MIN_PERCENTAGE;
1204 static bool DifficultyNoiseChange(int32 i)
1206 if (_game_mode == GM_NORMAL) {
1207 UpdateAirportsNoise();
1208 if (_settings_game.economy.station_noise_level) {
1209 InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
1213 return true;
1216 static bool MaxNoAIsChange(int32 i)
1218 if (GetGameSettings().difficulty.max_no_competitors != 0 &&
1219 AI::GetInfoList()->size() == 0 &&
1220 (!_networking || _network_server)) {
1221 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
1224 InvalidateWindowClassesData(WC_GAME_OPTIONS, 0);
1225 return true;
1229 * Check whether the road side may be changed.
1230 * @param p1 unused
1231 * @return true if the road side may be changed.
1233 static bool CheckRoadSide(int p1)
1235 extern bool RoadVehiclesAreBuilt();
1236 return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
1240 * Conversion callback for _gameopt_settings_game.landscape
1241 * It converts (or try) between old values and the new ones,
1242 * without losing initial setting of the user
1243 * @param value that was read from config file
1244 * @return the "hopefully" converted value
1246 static size_t ConvertLandscape(const char *value)
1248 /* try with the old values */
1249 return LookupOneOfMany("normal|hilly|desert|candy", value);
1252 static bool CheckFreeformEdges(int32 p1)
1254 if (_game_mode == GM_MENU) return true;
1255 if (p1 != 0) {
1256 for (Ship *s : Ship::Iterate()) {
1257 /* Check if there is a ship on the northern border. */
1258 if (TileX(s->tile) == 0 || TileY(s->tile) == 0) {
1259 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1260 return false;
1263 for (const BaseStation *st : BaseStation::Iterate()) {
1264 /* Check if there is a non-deleted buoy on the northern border. */
1265 if (st->IsInUse() && (TileX(st->xy) == 0 || TileY(st->xy) == 0)) {
1266 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1267 return false;
1270 for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
1271 for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
1272 } else {
1273 for (uint i = 0; i < MapMaxX(); i++) {
1274 if (TileHeight(TileXY(i, 1)) != 0) {
1275 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1276 return false;
1279 for (uint i = 1; i < MapMaxX(); i++) {
1280 if (!IsTileType(TileXY(i, MapMaxY() - 1), MP_WATER) || TileHeight(TileXY(1, MapMaxY())) != 0) {
1281 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1282 return false;
1285 for (uint i = 0; i < MapMaxY(); i++) {
1286 if (TileHeight(TileXY(1, i)) != 0) {
1287 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1288 return false;
1291 for (uint i = 1; i < MapMaxY(); i++) {
1292 if (!IsTileType(TileXY(MapMaxX() - 1, i), MP_WATER) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
1293 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1294 return false;
1297 /* Make tiles at the border water again. */
1298 for (uint i = 0; i < MapMaxX(); i++) {
1299 SetTileHeight(TileXY(i, 0), 0);
1300 SetTileType(TileXY(i, 0), MP_WATER);
1302 for (uint i = 0; i < MapMaxY(); i++) {
1303 SetTileHeight(TileXY(0, i), 0);
1304 SetTileType(TileXY(0, i), MP_WATER);
1307 MarkWholeScreenDirty();
1308 return true;
1312 * Changing the setting "allow multiple NewGRF sets" is not allowed
1313 * if there are vehicles.
1315 static bool ChangeDynamicEngines(int32 p1)
1317 if (_game_mode == GM_MENU) return true;
1319 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1320 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
1321 return false;
1324 return true;
1327 static bool ChangeMaxHeightLevel(int32 p1)
1329 if (_game_mode == GM_NORMAL) return false;
1330 if (_game_mode != GM_EDITOR) return true;
1332 /* Check if at least one mountain on the map is higher than the new value.
1333 * If yes, disallow the change. */
1334 for (TileIndex t = 0; t < MapSize(); t++) {
1335 if ((int32)TileHeight(t) > p1) {
1336 ShowErrorMessage(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN, INVALID_STRING_ID, WL_ERROR);
1337 /* Return old, unchanged value */
1338 return false;
1342 /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1343 InvalidateWindowClassesData(WC_SMALLMAP, 2);
1345 return true;
1348 static bool StationCatchmentChanged(int32 p1)
1350 Station::RecomputeCatchmentForAll();
1351 MarkWholeScreenDirty();
1352 return true;
1355 static bool MaxVehiclesChanged(int32 p1)
1357 InvalidateWindowClassesData(WC_BUILD_TOOLBAR);
1358 MarkWholeScreenDirty();
1359 return true;
1362 static bool InvalidateShipPathCache(int32 p1)
1364 for (Ship *s : Ship::Iterate()) {
1365 s->path.clear();
1367 return true;
1370 static bool UpdateClientName(int32 p1)
1372 NetworkUpdateClientName();
1373 return true;
1376 static bool UpdateServerPassword(int32 p1)
1378 if (strcmp(_settings_client.network.server_password, "*") == 0) {
1379 _settings_client.network.server_password[0] = '\0';
1382 return true;
1385 static bool UpdateRconPassword(int32 p1)
1387 if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
1388 _settings_client.network.rcon_password[0] = '\0';
1391 return true;
1394 static bool UpdateClientConfigValues(int32 p1)
1396 if (_network_server) NetworkServerSendConfigUpdate();
1398 return true;
1401 /* End - Callback Functions */
1404 * Prepare for reading and old diff_custom by zero-ing the memory.
1406 static void PrepareOldDiffCustom()
1408 memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
1412 * Reading of the old diff_custom array and transforming it to the new format.
1413 * @param savegame is it read from the config or savegame. In the latter case
1414 * we are sure there is an array; in the former case we have
1415 * to check that.
1417 static void HandleOldDiffCustom(bool savegame)
1419 uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && IsSavegameVersionBefore(SLV_4)) ? 1 : 0);
1421 if (!savegame) {
1422 /* If we did read to old_diff_custom, then at least one value must be non 0. */
1423 bool old_diff_custom_used = false;
1424 for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
1425 old_diff_custom_used = (_old_diff_custom[i] != 0);
1428 if (!old_diff_custom_used) return;
1431 for (uint i = 0; i < options_to_load; i++) {
1432 const SettingDesc *sd = &_settings[i];
1433 /* Skip deprecated options */
1434 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1435 void *var = GetVariableAddress(savegame ? &_settings_game : &_settings_newgame, &sd->save);
1436 Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
1440 static void AILoadConfig(IniFile *ini, const char *grpname)
1442 IniGroup *group = ini->GetGroup(grpname);
1443 IniItem *item;
1445 /* Clean any configured AI */
1446 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1447 AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME)->Change(nullptr);
1450 /* If no group exists, return */
1451 if (group == nullptr) return;
1453 CompanyID c = COMPANY_FIRST;
1454 for (item = group->item; c < MAX_COMPANIES && item != nullptr; c++, item = item->next) {
1455 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1457 config->Change(item->name.c_str());
1458 if (!config->HasScript()) {
1459 if (item->name != "none") {
1460 DEBUG(script, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->name.c_str());
1461 continue;
1464 if (item->value.has_value()) config->StringToSettings(item->value->c_str());
1468 static void GameLoadConfig(IniFile *ini, const char *grpname)
1470 IniGroup *group = ini->GetGroup(grpname);
1471 IniItem *item;
1473 /* Clean any configured GameScript */
1474 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME)->Change(nullptr);
1476 /* If no group exists, return */
1477 if (group == nullptr) return;
1479 item = group->item;
1480 if (item == nullptr) return;
1482 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1484 config->Change(item->name.c_str());
1485 if (!config->HasScript()) {
1486 if (item->name != "none") {
1487 DEBUG(script, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item->name.c_str());
1488 return;
1491 if (item->value.has_value()) config->StringToSettings(item->value->c_str());
1495 * Convert a character to a hex nibble value, or \c -1 otherwise.
1496 * @param c Character to convert.
1497 * @return Hex value of the character, or \c -1 if not a hex digit.
1499 static int DecodeHexNibble(char c)
1501 if (c >= '0' && c <= '9') return c - '0';
1502 if (c >= 'A' && c <= 'F') return c + 10 - 'A';
1503 if (c >= 'a' && c <= 'f') return c + 10 - 'a';
1504 return -1;
1508 * Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
1509 * After the hex number should be a \c '|' character.
1510 * @param pos First character to convert.
1511 * @param[out] dest Output byte array to write the bytes.
1512 * @param dest_size Number of bytes in \a dest.
1513 * @return Whether reading was successful.
1515 static bool DecodeHexText(const char *pos, uint8 *dest, size_t dest_size)
1517 while (dest_size > 0) {
1518 int hi = DecodeHexNibble(pos[0]);
1519 int lo = (hi >= 0) ? DecodeHexNibble(pos[1]) : -1;
1520 if (lo < 0) return false;
1521 *dest++ = (hi << 4) | lo;
1522 pos += 2;
1523 dest_size--;
1525 return *pos == '|';
1529 * Load a GRF configuration
1530 * @param ini The configuration to read from.
1531 * @param grpname Group name containing the configuration of the GRF.
1532 * @param is_static GRF is static.
1534 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
1536 IniGroup *group = ini->GetGroup(grpname);
1537 IniItem *item;
1538 GRFConfig *first = nullptr;
1539 GRFConfig **curr = &first;
1541 if (group == nullptr) return nullptr;
1543 for (item = group->item; item != nullptr; item = item->next) {
1544 GRFConfig *c = nullptr;
1546 uint8 grfid_buf[4], md5sum[16];
1547 const char *filename = item->name.c_str();
1548 bool has_grfid = false;
1549 bool has_md5sum = false;
1551 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1552 has_grfid = DecodeHexText(filename, grfid_buf, lengthof(grfid_buf));
1553 if (has_grfid) {
1554 filename += 1 + 2 * lengthof(grfid_buf);
1555 has_md5sum = DecodeHexText(filename, md5sum, lengthof(md5sum));
1556 if (has_md5sum) filename += 1 + 2 * lengthof(md5sum);
1558 uint32 grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
1559 if (has_md5sum) {
1560 const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, md5sum);
1561 if (s != nullptr) c = new GRFConfig(*s);
1563 if (c == nullptr && !FioCheckFileExists(filename, NEWGRF_DIR)) {
1564 const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
1565 if (s != nullptr) c = new GRFConfig(*s);
1568 if (c == nullptr) c = new GRFConfig(filename);
1570 /* Parse parameters */
1571 if (item->value.has_value() && !item->value->empty()) {
1572 int count = ParseIntList(item->value->c_str(), c->param, lengthof(c->param));
1573 if (count < 0) {
1574 SetDParamStr(0, filename);
1575 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
1576 count = 0;
1578 c->num_params = count;
1581 /* Check if item is valid */
1582 if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
1583 if (c->status == GCS_NOT_FOUND) {
1584 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND);
1585 } else if (HasBit(c->flags, GCF_UNSAFE)) {
1586 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE);
1587 } else if (HasBit(c->flags, GCF_SYSTEM)) {
1588 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM);
1589 } else if (HasBit(c->flags, GCF_INVALID)) {
1590 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE);
1591 } else {
1592 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN);
1595 SetDParamStr(0, StrEmpty(filename) ? item->name.c_str() : filename);
1596 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_GRF, WL_CRITICAL);
1597 delete c;
1598 continue;
1601 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1602 bool duplicate = false;
1603 for (const GRFConfig *gc = first; gc != nullptr; gc = gc->next) {
1604 if (gc->ident.grfid == c->ident.grfid) {
1605 SetDParamStr(0, c->filename);
1606 SetDParamStr(1, gc->filename);
1607 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_DUPLICATE_GRFID, WL_CRITICAL);
1608 duplicate = true;
1609 break;
1612 if (duplicate) {
1613 delete c;
1614 continue;
1617 /* Mark file as static to avoid saving in savegame. */
1618 if (is_static) SetBit(c->flags, GCF_STATIC);
1620 /* Add item to list */
1621 *curr = c;
1622 curr = &c->next;
1625 return first;
1628 static void AISaveConfig(IniFile *ini, const char *grpname)
1630 IniGroup *group = ini->GetGroup(grpname);
1632 if (group == nullptr) return;
1633 group->Clear();
1635 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1636 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1637 const char *name;
1638 char value[1024];
1639 config->SettingsToString(value, lastof(value));
1641 if (config->HasScript()) {
1642 name = config->GetName();
1643 } else {
1644 name = "none";
1647 IniItem *item = new IniItem(group, name);
1648 item->SetValue(value);
1652 static void GameSaveConfig(IniFile *ini, const char *grpname)
1654 IniGroup *group = ini->GetGroup(grpname);
1656 if (group == nullptr) return;
1657 group->Clear();
1659 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1660 const char *name;
1661 char value[1024];
1662 config->SettingsToString(value, lastof(value));
1664 if (config->HasScript()) {
1665 name = config->GetName();
1666 } else {
1667 name = "none";
1670 IniItem *item = new IniItem(group, name);
1671 item->SetValue(value);
1675 * Save the version of OpenTTD to the ini file.
1676 * @param ini the ini to write to
1678 static void SaveVersionInConfig(IniFile *ini)
1680 IniGroup *group = ini->GetGroup("version");
1682 char version[9];
1683 seprintf(version, lastof(version), "%08X", _openttd_newgrf_version);
1685 const char * const versions[][2] = {
1686 { "version_string", _openttd_revision },
1687 { "version_number", version }
1690 for (uint i = 0; i < lengthof(versions); i++) {
1691 group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
1695 /* Save a GRF configuration to the given group name */
1696 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
1698 ini->RemoveGroup(grpname);
1699 IniGroup *group = ini->GetGroup(grpname);
1700 const GRFConfig *c;
1702 for (c = list; c != nullptr; c = c->next) {
1703 /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1704 char key[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH];
1705 char params[512];
1706 GRFBuildParamList(params, c, lastof(params));
1708 char *pos = key + seprintf(key, lastof(key), "%08X|", BSWAP32(c->ident.grfid));
1709 pos = md5sumToString(pos, lastof(key), c->ident.md5sum);
1710 seprintf(pos, lastof(key), "|%s", c->filename);
1711 group->GetItem(key, true)->SetValue(params);
1715 /* Common handler for saving/loading variables to the configuration file */
1716 static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool basic_settings = true, bool other_settings = true)
1718 if (basic_settings) {
1719 proc(ini, (const SettingDesc*)_misc_settings, "misc", nullptr);
1720 #if defined(_WIN32) && !defined(DEDICATED)
1721 proc(ini, (const SettingDesc*)_win32_settings, "win32", nullptr);
1722 #endif /* _WIN32 */
1725 if (other_settings) {
1726 proc(ini, _settings, "patches", &_settings_newgame);
1727 proc(ini, _currency_settings,"currency", &_custom_currency);
1728 proc(ini, _company_settings, "company", &_settings_client.company);
1730 proc_list(ini, "server_bind_addresses", _network_bind_list);
1731 proc_list(ini, "servers", _network_host_list);
1732 proc_list(ini, "bans", _network_ban_list);
1736 static IniFile *IniLoadConfig()
1738 IniFile *ini = new IniFile(_list_group_names);
1739 ini->LoadFromDisk(_config_file, NO_DIRECTORY);
1740 return ini;
1744 * Load the values from the configuration files
1745 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1747 void LoadFromConfig(bool minimal)
1749 IniFile *ini = IniLoadConfig();
1750 if (!minimal) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1752 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1753 HandleSettingDescs(ini, IniLoadSettings, IniLoadSettingList, minimal, !minimal);
1755 if (!minimal) {
1756 _grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
1757 _grfconfig_static = GRFLoadConfig(ini, "newgrf-static", true);
1758 AILoadConfig(ini, "ai_players");
1759 GameLoadConfig(ini, "game_scripts");
1761 PrepareOldDiffCustom();
1762 IniLoadSettings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
1763 HandleOldDiffCustom(false);
1765 ValidateSettings();
1767 /* Display scheduled errors */
1768 extern void ScheduleErrorMessage(ErrorList &datas);
1769 ScheduleErrorMessage(_settings_error_list);
1770 if (FindWindowById(WC_ERRMSG, 0) == nullptr) ShowFirstError();
1773 delete ini;
1776 /** Save the values to the configuration file */
1777 void SaveToConfig()
1779 IniFile *ini = IniLoadConfig();
1781 /* Remove some obsolete groups. These have all been loaded into other groups. */
1782 ini->RemoveGroup("patches");
1783 ini->RemoveGroup("yapf");
1784 ini->RemoveGroup("gameopt");
1786 HandleSettingDescs(ini, IniSaveSettings, IniSaveSettingList);
1787 GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
1788 GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
1789 AISaveConfig(ini, "ai_players");
1790 GameSaveConfig(ini, "game_scripts");
1791 SaveVersionInConfig(ini);
1792 ini->SaveToDisk(_config_file);
1793 delete ini;
1797 * Get the list of known NewGrf presets.
1798 * @returns List of preset names.
1800 StringList GetGRFPresetList()
1802 StringList list;
1804 std::unique_ptr<IniFile> ini(IniLoadConfig());
1805 for (IniGroup *group = ini->group; group != nullptr; group = group->next) {
1806 if (group->name.compare(0, 7, "preset-") == 0) {
1807 list.push_back(group->name.substr(7));
1811 return list;
1815 * Load a NewGRF configuration by preset-name.
1816 * @param config_name Name of the preset.
1817 * @return NewGRF configuration.
1818 * @see GetGRFPresetList
1820 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1822 size_t len = strlen(config_name) + 8;
1823 char *section = (char*)alloca(len);
1824 seprintf(section, section + len - 1, "preset-%s", config_name);
1826 IniFile *ini = IniLoadConfig();
1827 GRFConfig *config = GRFLoadConfig(ini, section, false);
1828 delete ini;
1830 return config;
1834 * Save a NewGRF configuration with a preset name.
1835 * @param config_name Name of the preset.
1836 * @param config NewGRF configuration to save.
1837 * @see GetGRFPresetList
1839 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1841 size_t len = strlen(config_name) + 8;
1842 char *section = (char*)alloca(len);
1843 seprintf(section, section + len - 1, "preset-%s", config_name);
1845 IniFile *ini = IniLoadConfig();
1846 GRFSaveConfig(ini, section, config);
1847 ini->SaveToDisk(_config_file);
1848 delete ini;
1852 * Delete a NewGRF configuration by preset name.
1853 * @param config_name Name of the preset.
1855 void DeleteGRFPresetFromConfig(const char *config_name)
1857 size_t len = strlen(config_name) + 8;
1858 char *section = (char*)alloca(len);
1859 seprintf(section, section + len - 1, "preset-%s", config_name);
1861 IniFile *ini = IniLoadConfig();
1862 ini->RemoveGroup(section);
1863 ini->SaveToDisk(_config_file);
1864 delete ini;
1867 const SettingDesc *GetSettingDescription(uint index)
1869 if (index >= lengthof(_settings)) return nullptr;
1870 return &_settings[index];
1874 * Network-safe changing of settings (server-only).
1875 * @param tile unused
1876 * @param flags operation to perform
1877 * @param p1 the index of the setting in the SettingDesc array which identifies it
1878 * @param p2 the new value for the setting
1879 * The new value is properly clamped to its minimum/maximum when setting
1880 * @param text unused
1881 * @return the cost of this operation or an error
1882 * @see _settings
1884 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1886 const SettingDesc *sd = GetSettingDescription(p1);
1888 if (sd == nullptr) return CMD_ERROR;
1889 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
1891 if (!sd->IsEditable(true)) return CMD_ERROR;
1893 if (flags & DC_EXEC) {
1894 void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
1896 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1897 int32 newval = (int32)p2;
1899 Write_ValidateSetting(var, sd, newval);
1900 newval = (int32)ReadValue(var, sd->save.conv);
1902 if (oldval == newval) return CommandCost();
1904 if (sd->desc.proc != nullptr && !sd->desc.proc(newval)) {
1905 WriteValue(var, sd->save.conv, (int64)oldval);
1906 return CommandCost();
1909 if (sd->desc.flags & SGF_NO_NETWORK) {
1910 GamelogStartAction(GLAT_SETTING);
1911 GamelogSetting(sd->desc.name, oldval, newval);
1912 GamelogStopAction();
1915 SetWindowClassesDirty(WC_GAME_OPTIONS);
1917 if (_save_config) SaveToConfig();
1920 return CommandCost();
1924 * Change one of the per-company settings.
1925 * @param tile unused
1926 * @param flags operation to perform
1927 * @param p1 the index of the setting in the _company_settings array which identifies it
1928 * @param p2 the new value for the setting
1929 * The new value is properly clamped to its minimum/maximum when setting
1930 * @param text unused
1931 * @return the cost of this operation or an error
1933 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1935 if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
1936 const SettingDesc *sd = &_company_settings[p1];
1938 if (flags & DC_EXEC) {
1939 void *var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
1941 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1942 int32 newval = (int32)p2;
1944 Write_ValidateSetting(var, sd, newval);
1945 newval = (int32)ReadValue(var, sd->save.conv);
1947 if (oldval == newval) return CommandCost();
1949 if (sd->desc.proc != nullptr && !sd->desc.proc(newval)) {
1950 WriteValue(var, sd->save.conv, (int64)oldval);
1951 return CommandCost();
1954 SetWindowClassesDirty(WC_GAME_OPTIONS);
1957 return CommandCost();
1961 * Top function to save the new value of an element of the Settings struct
1962 * @param index offset in the SettingDesc array of the Settings struct which
1963 * identifies the setting member we want to change
1964 * @param value new value of the setting
1965 * @param force_newgame force the newgame settings
1967 bool SetSettingValue(uint index, int32 value, bool force_newgame)
1969 const SettingDesc *sd = &_settings[index];
1970 /* If an item is company-based, we do not send it over the network
1971 * (if any) to change. Also *hack*hack* we update the _newgame version
1972 * of settings because changing a company-based setting in a game also
1973 * changes its defaults. At least that is the convention we have chosen */
1974 if (sd->save.conv & SLF_NO_NETWORK_SYNC) {
1975 void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
1976 Write_ValidateSetting(var, sd, value);
1978 if (_game_mode != GM_MENU) {
1979 void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1980 Write_ValidateSetting(var2, sd, value);
1982 if (sd->desc.proc != nullptr) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1984 SetWindowClassesDirty(WC_GAME_OPTIONS);
1986 if (_save_config) SaveToConfig();
1987 return true;
1990 if (force_newgame) {
1991 void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
1992 Write_ValidateSetting(var2, sd, value);
1994 if (_save_config) SaveToConfig();
1995 return true;
1998 /* send non-company-based settings over the network */
1999 if (!_networking || (_networking && _network_server)) {
2000 return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
2002 return false;
2006 * Top function to save the new value of an element of the Settings struct
2007 * @param index offset in the SettingDesc array of the CompanySettings struct
2008 * which identifies the setting member we want to change
2009 * @param value new value of the setting
2011 void SetCompanySetting(uint index, int32 value)
2013 const SettingDesc *sd = &_company_settings[index];
2014 if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
2015 DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
2016 } else {
2017 void *var = GetVariableAddress(&_settings_client.company, &sd->save);
2018 Write_ValidateSetting(var, sd, value);
2019 if (sd->desc.proc != nullptr) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
2024 * Set the company settings for a new company to their default values.
2026 void SetDefaultCompanySettings(CompanyID cid)
2028 Company *c = Company::Get(cid);
2029 const SettingDesc *sd;
2030 for (sd = _company_settings; sd->save.cmd != SL_END; sd++) {
2031 void *var = GetVariableAddress(&c->settings, &sd->save);
2032 Write_ValidateSetting(var, sd, (int32)(size_t)sd->desc.def);
2037 * Sync all company settings in a multiplayer game.
2039 void SyncCompanySettings()
2041 const SettingDesc *sd;
2042 uint i = 0;
2043 for (sd = _company_settings; sd->save.cmd != SL_END; sd++, i++) {
2044 const void *old_var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
2045 const void *new_var = GetVariableAddress(&_settings_client.company, &sd->save);
2046 uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
2047 uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
2048 if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, nullptr, nullptr, _local_company);
2053 * Get the index in the _company_settings array of a setting
2054 * @param name The name of the setting
2055 * @return The index in the _company_settings array
2057 uint GetCompanySettingIndex(const char *name)
2059 uint i;
2060 const SettingDesc *sd = GetSettingFromName(name, &i);
2061 (void)sd; // Unused without asserts
2062 assert(sd != nullptr && (sd->desc.flags & SGF_PER_COMPANY) != 0);
2063 return i;
2067 * Set a setting value with a string.
2068 * @param index the settings index.
2069 * @param value the value to write
2070 * @param force_newgame force the newgame settings
2071 * @note Strings WILL NOT be synced over the network
2073 bool SetSettingValue(uint index, const char *value, bool force_newgame)
2075 const SettingDesc *sd = &_settings[index];
2076 assert(sd->save.conv & SLF_NO_NETWORK_SYNC);
2078 if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
2079 char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
2080 free(*var);
2081 *var = strcmp(value, "(null)") == 0 ? nullptr : stredup(value);
2082 } else {
2083 char *var = (char*)GetVariableAddress(nullptr, &sd->save);
2084 strecpy(var, value, &var[sd->save.length - 1]);
2086 if (sd->desc.proc != nullptr) sd->desc.proc(0);
2088 if (_save_config) SaveToConfig();
2089 return true;
2093 * Given a name of setting, return a setting description of it.
2094 * @param name Name of the setting to return a setting description of
2095 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
2096 * @return Pointer to the setting description of setting \a name if it can be found,
2097 * \c nullptr indicates failure to obtain the description
2099 const SettingDesc *GetSettingFromName(const char *name, uint *i)
2101 const SettingDesc *sd;
2103 /* First check all full names */
2104 for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2105 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2106 if (strcmp(sd->desc.name, name) == 0) return sd;
2109 /* Then check the shortcut variant of the name. */
2110 for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2111 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2112 const char *short_name = strchr(sd->desc.name, '.');
2113 if (short_name != nullptr) {
2114 short_name++;
2115 if (strcmp(short_name, name) == 0) return sd;
2119 if (strncmp(name, "company.", 8) == 0) name += 8;
2120 /* And finally the company-based settings */
2121 for (*i = 0, sd = _company_settings; sd->save.cmd != SL_END; sd++, (*i)++) {
2122 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2123 if (strcmp(sd->desc.name, name) == 0) return sd;
2126 return nullptr;
2129 /* Those 2 functions need to be here, else we have to make some stuff non-static
2130 * and besides, it is also better to keep stuff like this at the same place */
2131 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
2133 uint index;
2134 const SettingDesc *sd = GetSettingFromName(name, &index);
2136 if (sd == nullptr) {
2137 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2138 return;
2141 bool success;
2142 if (sd->desc.cmd == SDT_STRING) {
2143 success = SetSettingValue(index, value, force_newgame);
2144 } else {
2145 uint32 val;
2146 extern bool GetArgumentInteger(uint32 *value, const char *arg);
2147 success = GetArgumentInteger(&val, value);
2148 if (!success) {
2149 IConsolePrintF(CC_ERROR, "'%s' is not an integer.", value);
2150 return;
2153 success = SetSettingValue(index, val, force_newgame);
2156 if (!success) {
2157 if (_network_server) {
2158 IConsoleError("This command/variable is not available during network games.");
2159 } else {
2160 IConsoleError("This command/variable is only available to a network server.");
2165 void IConsoleSetSetting(const char *name, int value)
2167 uint index;
2168 const SettingDesc *sd = GetSettingFromName(name, &index);
2169 (void)sd; // Unused without asserts
2170 assert(sd != nullptr);
2171 SetSettingValue(index, value);
2175 * Output value of a specific setting to the console
2176 * @param name Name of the setting to output its value
2177 * @param force_newgame force the newgame settings
2179 void IConsoleGetSetting(const char *name, bool force_newgame)
2181 char value[20];
2182 uint index;
2183 const SettingDesc *sd = GetSettingFromName(name, &index);
2184 const void *ptr;
2186 if (sd == nullptr) {
2187 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2188 return;
2191 ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
2193 if (sd->desc.cmd == SDT_STRING) {
2194 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char * const *)ptr : (const char *)ptr);
2195 } else {
2196 if (sd->desc.cmd == SDT_BOOLX) {
2197 seprintf(value, lastof(value), (*(const bool*)ptr != 0) ? "on" : "off");
2198 } else {
2199 seprintf(value, lastof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2202 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2203 name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
2208 * List all settings and their value to the console
2210 * @param prefilter If not \c nullptr, only list settings with names that begin with \a prefilter prefix
2212 void IConsoleListSettings(const char *prefilter)
2214 IConsolePrintF(CC_WARNING, "All settings with their current value:");
2216 for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
2217 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
2218 if (prefilter != nullptr && strstr(sd->desc.name, prefilter) == nullptr) continue;
2219 char value[80];
2220 const void *ptr = GetVariableAddress(&GetGameSettings(), &sd->save);
2222 if (sd->desc.cmd == SDT_BOOLX) {
2223 seprintf(value, lastof(value), (*(const bool *)ptr != 0) ? "on" : "off");
2224 } else if (sd->desc.cmd == SDT_STRING) {
2225 seprintf(value, lastof(value), "%s", (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char * const *)ptr : (const char *)ptr);
2226 } else {
2227 seprintf(value, lastof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2229 IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
2232 IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
2236 * Save and load handler for settings
2237 * @param osd SettingDesc struct containing all information
2238 * @param object can be either nullptr in which case we load global variables or
2239 * a pointer to a struct which is getting saved
2241 static void LoadSettings(const SettingDesc *osd, void *object)
2243 for (; osd->save.cmd != SL_END; osd++) {
2244 const SaveLoad *sld = &osd->save;
2245 void *ptr = GetVariableAddress(object, sld);
2247 if (!SlObjectMember(ptr, sld)) continue;
2248 if (IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
2253 * Save and load handler for settings
2254 * @param sd SettingDesc struct containing all information
2255 * @param object can be either nullptr in which case we load global variables or
2256 * a pointer to a struct which is getting saved
2258 static void SaveSettings(const SettingDesc *sd, void *object)
2260 /* We need to write the CH_RIFF header, but unfortunately can't call
2261 * SlCalcLength() because we have a different format. So do this manually */
2262 const SettingDesc *i;
2263 size_t length = 0;
2264 for (i = sd; i->save.cmd != SL_END; i++) {
2265 length += SlCalcObjMemberLength(object, &i->save);
2267 SlSetLength(length);
2269 for (i = sd; i->save.cmd != SL_END; i++) {
2270 void *ptr = GetVariableAddress(object, &i->save);
2271 SlObjectMember(ptr, &i->save);
2275 static void Load_OPTS()
2277 /* Copy over default setting since some might not get loaded in
2278 * a networking environment. This ensures for example that the local
2279 * autosave-frequency stays when joining a network-server */
2280 PrepareOldDiffCustom();
2281 LoadSettings(_gameopt_settings, &_settings_game);
2282 HandleOldDiffCustom(true);
2285 static void Load_PATS()
2287 /* Copy over default setting since some might not get loaded in
2288 * a networking environment. This ensures for example that the local
2289 * currency setting stays when joining a network-server */
2290 LoadSettings(_settings, &_settings_game);
2293 static void Check_PATS()
2295 LoadSettings(_settings, &_load_check_data.settings);
2298 static void Save_PATS()
2300 SaveSettings(_settings, &_settings_game);
2303 extern const ChunkHandler _setting_chunk_handlers[] = {
2304 { 'OPTS', nullptr, Load_OPTS, nullptr, nullptr, CH_RIFF},
2305 { 'PATS', Save_PATS, Load_PATS, nullptr, Check_PATS, CH_RIFF | CH_LAST},
2308 static bool IsSignedVarMemType(VarType vt)
2310 switch (GetVarMemType(vt)) {
2311 case SLE_VAR_I8:
2312 case SLE_VAR_I16:
2313 case SLE_VAR_I32:
2314 case SLE_VAR_I64:
2315 return true;
2317 return false;