4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
12 * All actions handling saving and loading of the settings/configuration goes on in this file.
13 * The file consists of three parts:
15 * <li>Parsing the configuration file (openttd.cfg). This is achieved with the ini_ functions which
16 * handle various types, such as normal 'key = value' pairs, lists and value combinations of
17 * lists, strings, integers, 'bit'-masks and element selections.
18 * <li>Handle reading and writing to the setting-structures from inside the game either from
19 * the console for example or through the gui with CMD_ functions.
20 * <li>Handle saving/loading of the PATS chunk inside the savegame.
28 #include "screenshot.h"
29 #include "network/network.h"
30 #include "network/network_func.h"
31 #include "settings_internal.h"
32 #include "command_func.h"
33 #include "console_func.h"
34 #include "pathfinder/pathfinder_type.h"
37 #include "news_func.h"
38 #include "window_func.h"
39 #include "sound_func.h"
40 #include "company_func.h"
43 #include "fontcache.h"
45 #include "textbuf_gui.h"
47 #include "elrail_func.h"
50 #include "video/video_driver.hpp"
51 #include "sound/sound_driver.hpp"
52 #include "music/music_driver.hpp"
53 #include "blitter/factory.hpp"
54 #include "base_media_base.h"
56 #include "settings_func.h"
58 #include "ai/ai_config.hpp"
60 #include "game/game_config.hpp"
61 #include "game/game.hpp"
63 #include "smallmap_gui.h"
66 #include "strings_func.h"
67 #include "statusbar_gui.h"
70 #include "station_base.h"
72 #include "table/strings.h"
73 #include "table/settings.h"
75 #include "safeguards.h"
77 ClientSettings _settings_client
;
78 GameSettings _settings_game
; ///< Game settings of a running game or the scenario editor.
79 GameSettings _settings_newgame
; ///< Game settings for new games (updated from the intro screen).
80 VehicleDefaultSettings _old_vds
; ///< Used for loading default vehicles settings from old savegames
81 char *_config_file
; ///< Configuration file of OpenTTD
83 typedef std::list
<ErrorMessageData
> ErrorList
;
84 static ErrorList _settings_error_list
; ///< Errors while loading minimal settings.
87 typedef void SettingDescProc(IniFile
*ini
, const SettingDesc
*desc
, const char *grpname
, void *object
);
88 typedef void SettingDescProcList(IniFile
*ini
, const char *grpname
, StringList
*list
);
90 static bool IsSignedVarMemType(VarType vt
);
93 * Groups in openttd.cfg that are actually lists.
95 static const char * const _list_group_names
[] = {
99 "server_bind_addresses",
104 * Find the index value of a ONEofMANY type in a string separated by |
105 * @param many full domain of values the ONEofMANY setting can have
106 * @param one the current value of the setting for which a value needs found
107 * @param onelen force calculation of the *one parameter
108 * @return the integer index of the full-list, or -1 if not found
110 static size_t LookupOneOfMany(const char *many
, const char *one
, size_t onelen
= 0)
115 if (onelen
== 0) onelen
= strlen(one
);
117 /* check if it's an integer */
118 if (*one
>= '0' && *one
<= '9') return strtoul(one
, nullptr, 0);
122 /* find end of item */
124 while (*s
!= '|' && *s
!= 0) s
++;
125 if ((size_t)(s
- many
) == onelen
&& !memcmp(one
, many
, onelen
)) return idx
;
126 if (*s
== 0) return (size_t)-1;
133 * Find the set-integer value MANYofMANY type in a string
134 * @param many full domain of values the MANYofMANY setting can have
135 * @param str the current string value of the setting, each individual
136 * of separated by a whitespace,tab or | character
137 * @return the 'fully' set integer, or -1 if a set is not found
139 static size_t LookupManyOfMany(const char *many
, const char *str
)
146 /* skip "whitespace" */
147 while (*str
== ' ' || *str
== '\t' || *str
== '|') str
++;
148 if (*str
== 0) break;
151 while (*s
!= 0 && *s
!= ' ' && *s
!= '\t' && *s
!= '|') s
++;
153 r
= LookupOneOfMany(many
, str
, s
- str
);
154 if (r
== (size_t)-1) return r
;
156 SetBit(res
, (uint8
)r
); // value found, set it
164 * Parse an integerlist string and set each found value
165 * @param p the string to be parsed. Each element in the list is separated by a
166 * comma or a space character
167 * @param items pointer to the integerlist-array that will be filled with values
168 * @param maxitems the maximum number of elements the integerlist-array has
169 * @return returns the number of items found, or -1 on an error
171 static int ParseIntList(const char *p
, int *items
, int maxitems
)
173 int n
= 0; // number of items read so far
174 bool comma
= false; // do we accept comma?
179 /* Do not accept multiple commas between numbers */
180 if (!comma
) return -1;
189 if (n
== maxitems
) return -1; // we don't accept that many numbers
191 long v
= strtol(p
, &end
, 0);
192 if (p
== end
) return -1; // invalid character (not a number)
193 if (sizeof(int) < sizeof(long)) v
= ClampToI32(v
);
195 p
= end
; // first non-number
196 comma
= true; // we accept comma now
202 /* If we have read comma but no number after it, fail.
203 * We have read comma when (n != 0) and comma is not allowed */
204 if (n
!= 0 && !comma
) return -1;
210 * Load parsed string-values into an integer-array (intlist)
211 * @param str the string that contains the values (and will be parsed)
212 * @param array pointer to the integer-arrays that will be filled
213 * @param nelems the number of elements the array holds. Maximum is 64 elements
214 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
215 * @return return true on success and false on error
217 static bool LoadIntList(const char *str
, void *array
, int nelems
, VarType type
)
222 if (str
== nullptr) {
223 memset(items
, 0, sizeof(items
));
226 nitems
= ParseIntList(str
, items
, lengthof(items
));
227 if (nitems
!= nelems
) return false;
234 for (i
= 0; i
!= nitems
; i
++) ((byte
*)array
)[i
] = items
[i
];
239 for (i
= 0; i
!= nitems
; i
++) ((uint16
*)array
)[i
] = items
[i
];
244 for (i
= 0; i
!= nitems
; i
++) ((uint32
*)array
)[i
] = items
[i
];
247 default: NOT_REACHED();
254 * Convert an integer-array (intlist) to a string representation. Each value
255 * is separated by a comma or a space character
256 * @param buf output buffer where the string-representation will be stored
257 * @param last last item to write to in the output buffer
258 * @param array pointer to the integer-arrays that is read from
259 * @param nelems the number of elements the array holds.
260 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
262 static void MakeIntList(char *buf
, const char *last
, const void *array
, int nelems
, VarType type
)
265 const byte
*p
= (const byte
*)array
;
267 for (i
= 0; i
!= nelems
; i
++) {
270 case SLE_VAR_I8
: v
= *(const int8
*)p
; p
+= 1; break;
271 case SLE_VAR_U8
: v
= *(const uint8
*)p
; p
+= 1; break;
272 case SLE_VAR_I16
: v
= *(const int16
*)p
; p
+= 2; break;
273 case SLE_VAR_U16
: v
= *(const uint16
*)p
; p
+= 2; break;
274 case SLE_VAR_I32
: v
= *(const int32
*)p
; p
+= 4; break;
275 case SLE_VAR_U32
: v
= *(const uint32
*)p
; p
+= 4; break;
276 default: NOT_REACHED();
278 buf
+= seprintf(buf
, last
, (i
== 0) ? "%d" : ",%d", v
);
283 * Convert a ONEofMANY structure to a string representation.
284 * @param buf output buffer where the string-representation will be stored
285 * @param last last item to write to in the output buffer
286 * @param many the full-domain string of possible values
287 * @param id the value of the variable and whose string-representation must be found
289 static void MakeOneOfMany(char *buf
, const char *last
, const char *many
, int id
)
293 /* Look for the id'th element */
295 for (; *many
!= '|'; many
++) {
296 if (*many
== '\0') { // not found
297 seprintf(buf
, last
, "%d", orig_id
);
301 many
++; // pass the |-character
304 /* copy string until next item (|) or the end of the list if this is the last one */
305 while (*many
!= '\0' && *many
!= '|' && buf
< last
) *buf
++ = *many
++;
310 * Convert a MANYofMANY structure to a string representation.
311 * @param buf output buffer where the string-representation will be stored
312 * @param last last item to write to in the output buffer
313 * @param many the full-domain string of possible values
314 * @param x the value of the variable and whose string-representation must
315 * be found in the bitmasked many string
317 static void MakeManyOfMany(char *buf
, const char *last
, const char *many
, uint32 x
)
323 for (; x
!= 0; x
>>= 1, i
++) {
325 while (*many
!= 0 && *many
!= '|') many
++; // advance to the next element
327 if (HasBit(x
, 0)) { // item found, copy it
328 if (!init
) buf
+= seprintf(buf
, last
, "|");
331 buf
+= seprintf(buf
, last
, "%d", i
);
333 memcpy(buf
, start
, many
- start
);
338 if (*many
== '|') many
++;
345 * Convert a string representation (external) of a setting to the internal rep.
346 * @param desc SettingDesc struct that holds all information about the variable
347 * @param orig_str input string that will be parsed based on the type of desc
348 * @return return the parsed value of the setting
350 static const void *StringToVal(const SettingDescBase
*desc
, const char *orig_str
)
352 const char *str
= orig_str
== nullptr ? "" : orig_str
;
357 size_t val
= strtoul(str
, &end
, 0);
359 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
360 msg
.SetDParamStr(0, str
);
361 msg
.SetDParamStr(1, desc
->name
);
362 _settings_error_list
.push_back(msg
);
366 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_TRAILING_CHARACTERS
);
367 msg
.SetDParamStr(0, desc
->name
);
368 _settings_error_list
.push_back(msg
);
373 case SDT_ONEOFMANY
: {
374 size_t r
= LookupOneOfMany(desc
->many
, str
);
375 /* if the first attempt of conversion from string to the appropriate value fails,
376 * look if we have defined a converter from old value to new value. */
377 if (r
== (size_t)-1 && desc
->proc_cnvt
!= nullptr) r
= desc
->proc_cnvt(str
);
378 if (r
!= (size_t)-1) return (void*)r
; // and here goes converted value
380 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
381 msg
.SetDParamStr(0, str
);
382 msg
.SetDParamStr(1, desc
->name
);
383 _settings_error_list
.push_back(msg
);
387 case SDT_MANYOFMANY
: {
388 size_t r
= LookupManyOfMany(desc
->many
, str
);
389 if (r
!= (size_t)-1) return (void*)r
;
390 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
391 msg
.SetDParamStr(0, str
);
392 msg
.SetDParamStr(1, desc
->name
);
393 _settings_error_list
.push_back(msg
);
398 if (strcmp(str
, "true") == 0 || strcmp(str
, "on") == 0 || strcmp(str
, "1") == 0) return (void*)true;
399 if (strcmp(str
, "false") == 0 || strcmp(str
, "off") == 0 || strcmp(str
, "0") == 0) return (void*)false;
401 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_VALUE
);
402 msg
.SetDParamStr(0, str
);
403 msg
.SetDParamStr(1, desc
->name
);
404 _settings_error_list
.push_back(msg
);
408 case SDT_STRING
: return orig_str
;
409 case SDT_INTLIST
: return str
;
417 * Set the value of a setting and if needed clamp the value to
418 * the preset minimum and maximum.
419 * @param ptr the variable itself
420 * @param sd pointer to the 'information'-database of the variable
421 * @param val signed long version of the new value
422 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
423 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
425 static void Write_ValidateSetting(void *ptr
, const SettingDesc
*sd
, int32 val
)
427 const SettingDescBase
*sdb
= &sd
->desc
;
429 if (sdb
->cmd
!= SDT_BOOLX
&&
430 sdb
->cmd
!= SDT_NUMX
&&
431 sdb
->cmd
!= SDT_ONEOFMANY
&&
432 sdb
->cmd
!= SDT_MANYOFMANY
) {
436 /* We cannot know the maximum value of a bitset variable, so just have faith */
437 if (sdb
->cmd
!= SDT_MANYOFMANY
) {
438 /* We need to take special care of the uint32 type as we receive from the function
439 * a signed integer. While here also bail out on 64-bit settings as those are not
440 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
442 * TODO: Support 64-bit settings/variables */
443 switch (GetVarMemType(sd
->save
.conv
)) {
444 case SLE_VAR_NULL
: return;
451 /* Override the minimum value. No value below sdb->min, except special value 0 */
452 if (!(sdb
->flags
& SGF_0ISDISABLED
) || val
!= 0) val
= Clamp(val
, sdb
->min
, sdb
->max
);
456 /* Override the minimum value. No value below sdb->min, except special value 0 */
457 uint min
= ((sdb
->flags
& SGF_0ISDISABLED
) && (uint
)val
<= (uint
)sdb
->min
) ? 0 : sdb
->min
;
458 WriteValue(ptr
, SLE_VAR_U32
, (int64
)ClampU(val
, min
, sdb
->max
));
463 default: NOT_REACHED();
467 WriteValue(ptr
, sd
->save
.conv
, (int64
)val
);
471 * Load values from a group of an IniFile structure into the internal representation
472 * @param ini pointer to IniFile structure that holds administrative information
473 * @param sd pointer to SettingDesc structure whose internally pointed variables will
475 * @param grpname the group of the IniFile to search in for the new values
476 * @param object pointer to the object been loaded
478 static void IniLoadSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
481 IniGroup
*group_def
= ini
->GetGroup(grpname
);
487 for (; sd
->save
.cmd
!= SL_END
; sd
++) {
488 const SettingDescBase
*sdb
= &sd
->desc
;
489 const SaveLoad
*sld
= &sd
->save
;
491 if (!SlIsObjectCurrentlyValid(sld
->version_from
, sld
->version_to
)) continue;
493 /* For settings.xx.yy load the settings from [xx] yy = ? */
494 s
= strchr(sdb
->name
, '.');
496 group
= ini
->GetGroup(sdb
->name
, s
- sdb
->name
);
503 item
= group
->GetItem(s
, false);
504 if (item
== nullptr && group
!= group_def
) {
505 /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
506 * did not exist (e.g. loading old config files with a [settings] section */
507 item
= group_def
->GetItem(s
, false);
509 if (item
== nullptr) {
510 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
511 * did not exist (e.g. loading old config files with a [yapf] section */
512 const char *sc
= strchr(s
, '.');
513 if (sc
!= nullptr) item
= ini
->GetGroup(s
, sc
- s
)->GetItem(sc
+ 1, false);
516 p
= (item
== nullptr) ? sdb
->def
: StringToVal(sdb
, item
->value
);
517 ptr
= GetVariableAddress(object
, sld
);
520 case SDT_BOOLX
: // All four are various types of (integer) numbers
524 Write_ValidateSetting(ptr
, sd
, (int32
)(size_t)p
);
528 switch (GetVarMemType(sld
->conv
)) {
531 if (p
!= nullptr) strecpy((char*)ptr
, (const char*)p
, (char*)ptr
+ sld
->length
- 1);
537 *(char**)ptr
= p
== nullptr ? nullptr : stredup((const char*)p
);
540 case SLE_VAR_CHAR
: if (p
!= nullptr) *(char *)ptr
= *(const char *)p
; break;
542 default: NOT_REACHED();
547 if (!LoadIntList((const char*)p
, ptr
, sld
->length
, GetVarMemType(sld
->conv
))) {
548 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
);
549 msg
.SetDParamStr(0, sdb
->name
);
550 _settings_error_list
.push_back(msg
);
553 LoadIntList((const char*)sdb
->def
, ptr
, sld
->length
, GetVarMemType(sld
->conv
));
554 } else if (sd
->desc
.proc_cnvt
!= nullptr) {
555 sd
->desc
.proc_cnvt((const char*)p
);
559 default: NOT_REACHED();
565 * Save the values of settings to the inifile.
566 * @param ini pointer to IniFile structure
567 * @param sd read-only SettingDesc structure which contains the unmodified,
568 * loaded values of the configuration file and various information about it
569 * @param grpname holds the name of the group (eg. [network]) where these will be saved
570 * @param object pointer to the object been saved
571 * The function works as follows: for each item in the SettingDesc structure we
572 * have a look if the value has changed since we started the game (the original
573 * values are reloaded when saving). If settings indeed have changed, we get
574 * these and save them.
576 static void IniSaveSettings(IniFile
*ini
, const SettingDesc
*sd
, const char *grpname
, void *object
)
578 IniGroup
*group_def
= nullptr, *group
;
584 for (; sd
->save
.cmd
!= SL_END
; sd
++) {
585 const SettingDescBase
*sdb
= &sd
->desc
;
586 const SaveLoad
*sld
= &sd
->save
;
588 /* If the setting is not saved to the configuration
589 * file, just continue with the next setting */
590 if (!SlIsObjectCurrentlyValid(sld
->version_from
, sld
->version_to
)) continue;
591 if (sld
->conv
& SLF_NOT_IN_CONFIG
) continue;
593 /* XXX - wtf is this?? (group override?) */
594 s
= strchr(sdb
->name
, '.');
596 group
= ini
->GetGroup(sdb
->name
, s
- sdb
->name
);
599 if (group_def
== nullptr) group_def
= ini
->GetGroup(grpname
);
604 item
= group
->GetItem(s
, true);
605 ptr
= GetVariableAddress(object
, sld
);
607 if (item
->value
!= nullptr) {
608 /* check if the value is the same as the old value */
609 const void *p
= StringToVal(sdb
, item
->value
);
611 /* The main type of a variable/setting is in bytes 8-15
612 * The subtype (what kind of numbers do we have there) is in 0-7 */
618 switch (GetVarMemType(sld
->conv
)) {
620 if (*(bool*)ptr
== (p
!= nullptr)) continue;
625 if (*(byte
*)ptr
== (byte
)(size_t)p
) continue;
630 if (*(uint16
*)ptr
== (uint16
)(size_t)p
) continue;
635 if (*(uint32
*)ptr
== (uint32
)(size_t)p
) continue;
638 default: NOT_REACHED();
642 default: break; // Assume the other types are always changed
646 /* Value has changed, get the new value and put it into a buffer */
651 case SDT_MANYOFMANY
: {
652 uint32 i
= (uint32
)ReadValue(ptr
, sld
->conv
);
655 case SDT_BOOLX
: strecpy(buf
, (i
!= 0) ? "true" : "false", lastof(buf
)); break;
656 case SDT_NUMX
: seprintf(buf
, lastof(buf
), IsSignedVarMemType(sld
->conv
) ? "%d" : "%u", i
); break;
657 case SDT_ONEOFMANY
: MakeOneOfMany(buf
, lastof(buf
), sdb
->many
, i
); break;
658 case SDT_MANYOFMANY
: MakeManyOfMany(buf
, lastof(buf
), sdb
->many
, i
); break;
659 default: NOT_REACHED();
665 switch (GetVarMemType(sld
->conv
)) {
666 case SLE_VAR_STRB
: strecpy(buf
, (char*)ptr
, lastof(buf
)); break;
667 case SLE_VAR_STRBQ
:seprintf(buf
, lastof(buf
), "\"%s\"", (char*)ptr
); break;
668 case SLE_VAR_STR
: strecpy(buf
, *(char**)ptr
, lastof(buf
)); break;
671 if (*(char**)ptr
== nullptr) {
674 seprintf(buf
, lastof(buf
), "\"%s\"", *(char**)ptr
);
678 case SLE_VAR_CHAR
: buf
[0] = *(char*)ptr
; buf
[1] = '\0'; break;
679 default: NOT_REACHED();
684 MakeIntList(buf
, lastof(buf
), ptr
, sld
->length
, GetVarMemType(sld
->conv
));
687 default: NOT_REACHED();
690 /* The value is different, that means we have to write it to the ini */
692 item
->value
= stredup(buf
);
697 * Loads all items from a 'grpname' section into a list
698 * The list parameter can be a nullptr pointer, in this case nothing will be
699 * saved and a callback function should be defined that will take over the
700 * list-handling and store the data itself somewhere.
701 * @param ini IniFile handle to the ini file with the source data
702 * @param grpname character string identifying the section-header of the ini file that will be parsed
703 * @param list new list with entries of the given section
705 static void IniLoadSettingList(IniFile
*ini
, const char *grpname
, StringList
*list
)
707 IniGroup
*group
= ini
->GetGroup(grpname
);
709 if (group
== nullptr || list
== nullptr) return;
713 for (const IniItem
*item
= group
->item
; item
!= nullptr; item
= item
->next
) {
714 if (item
->name
!= nullptr) *list
->Append() = stredup(item
->name
);
719 * Saves all items from a list into the 'grpname' section
720 * The list parameter can be a nullptr pointer, in this case a callback function
721 * should be defined that will provide the source data to be saved.
722 * @param ini IniFile handle to the ini file where the destination data is saved
723 * @param grpname character string identifying the section-header of the ini file
724 * @param list pointer to an string(pointer) array that will be used as the
725 * source to be saved into the relevant ini section
727 static void IniSaveSettingList(IniFile
*ini
, const char *grpname
, StringList
*list
)
729 IniGroup
*group
= ini
->GetGroup(grpname
);
731 if (group
== nullptr || list
== nullptr) return;
734 for (char **iter
= list
->Begin(); iter
!= list
->End(); iter
++) {
735 group
->GetItem(*iter
, true)->SetValue("");
740 * Load a WindowDesc from config.
741 * @param ini IniFile handle to the ini file with the source data
742 * @param grpname character string identifying the section-header of the ini file that will be parsed
743 * @param desc Destination WindowDesc
745 void IniLoadWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
747 IniLoadSettings(ini
, _window_settings
, grpname
, desc
);
751 * Save a WindowDesc to config.
752 * @param ini IniFile handle to the ini file where the destination data is saved
753 * @param grpname character string identifying the section-header of the ini file
754 * @param desc Source WindowDesc
756 void IniSaveWindowSettings(IniFile
*ini
, const char *grpname
, void *desc
)
758 IniSaveSettings(ini
, _window_settings
, grpname
, desc
);
762 * Check whether the setting is editable in the current gamemode.
763 * @param do_command true if this is about checking a command from the server.
764 * @return true if editable.
766 bool SettingDesc::IsEditable(bool do_command
) const
768 if (!do_command
&& !(this->save
.conv
& SLF_NO_NETWORK_SYNC
) && _networking
&& !_network_server
&& !(this->desc
.flags
& SGF_PER_COMPANY
)) return false;
769 if ((this->desc
.flags
& SGF_NETWORK_ONLY
) && !_networking
&& _game_mode
!= GM_MENU
) return false;
770 if ((this->desc
.flags
& SGF_NO_NETWORK
) && _networking
) return false;
771 if ((this->desc
.flags
& SGF_NEWGAME_ONLY
) &&
772 (_game_mode
== GM_NORMAL
||
773 (_game_mode
== GM_EDITOR
&& !(this->desc
.flags
& SGF_SCENEDIT_TOO
)))) return false;
778 * Return the type of the setting.
779 * @return type of setting
781 SettingType
SettingDesc::GetType() const
783 if (this->desc
.flags
& SGF_PER_COMPANY
) return ST_COMPANY
;
784 return (this->save
.conv
& SLF_NOT_IN_SAVE
) ? ST_CLIENT
: ST_GAME
;
787 /* Begin - Callback Functions for the various settings. */
789 /** Reposition the main toolbar as the setting changed. */
790 static bool v_PositionMainToolbar(int32 p1
)
792 if (_game_mode
!= GM_MENU
) PositionMainToolbar(nullptr);
796 /** Reposition the statusbar as the setting changed. */
797 static bool v_PositionStatusbar(int32 p1
)
799 if (_game_mode
!= GM_MENU
) {
800 PositionStatusbar(nullptr);
801 PositionNewsMessage(nullptr);
802 PositionNetworkChatWindow(nullptr);
807 static bool PopulationInLabelActive(int32 p1
)
809 UpdateAllTownVirtCoords();
813 static bool RedrawScreen(int32 p1
)
815 MarkWholeScreenDirty();
820 * Redraw the smallmap after a colour scheme change.
821 * @param p1 Callback parameter.
822 * @return Always true.
824 static bool RedrawSmallmap(int32 p1
)
828 SetWindowClassesDirty(WC_SMALLMAP
);
832 static bool InvalidateDetailsWindow(int32 p1
)
834 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
838 static bool StationSpreadChanged(int32 p1
)
840 InvalidateWindowData(WC_SELECT_STATION
, 0);
841 InvalidateWindowData(WC_BUILD_STATION
, 0);
845 static bool InvalidateBuildIndustryWindow(int32 p1
)
847 InvalidateWindowData(WC_BUILD_INDUSTRY
, 0);
851 static bool CloseSignalGUI(int32 p1
)
854 DeleteWindowByClass(WC_BUILD_SIGNAL
);
859 static bool InvalidateTownViewWindow(int32 p1
)
861 InvalidateWindowClassesData(WC_TOWN_VIEW
, p1
);
865 static bool DeleteSelectStationWindow(int32 p1
)
867 DeleteWindowById(WC_SELECT_STATION
, 0);
871 static bool UpdateConsists(int32 p1
)
875 /* Update the consist of all trains so the maximum speed is set correctly. */
876 if (t
->IsFrontEngine() || t
->IsFreeWagon()) t
->ConsistChanged(CCF_TRACK
);
878 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
882 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
883 static bool CheckInterval(int32 p1
)
885 bool update_vehicles
;
886 VehicleDefaultSettings
*vds
;
887 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
888 vds
= &_settings_client
.company
.vehicle
;
889 update_vehicles
= false;
891 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
892 update_vehicles
= true;
896 vds
->servint_trains
= 50;
897 vds
->servint_roadveh
= 50;
898 vds
->servint_aircraft
= 50;
899 vds
->servint_ships
= 50;
901 vds
->servint_trains
= 150;
902 vds
->servint_roadveh
= 150;
903 vds
->servint_aircraft
= 100;
904 vds
->servint_ships
= 360;
907 if (update_vehicles
) {
908 const Company
*c
= Company::Get(_current_company
);
910 FOR_ALL_VEHICLES(v
) {
911 if (v
->owner
== _current_company
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
912 v
->SetServiceInterval(CompanyServiceInterval(c
, v
->type
));
913 v
->SetServiceIntervalIsPercent(p1
!= 0);
918 InvalidateDetailsWindow(0);
923 static bool UpdateInterval(VehicleType type
, int32 p1
)
925 bool update_vehicles
;
926 VehicleDefaultSettings
*vds
;
927 if (_game_mode
== GM_MENU
|| !Company::IsValidID(_current_company
)) {
928 vds
= &_settings_client
.company
.vehicle
;
929 update_vehicles
= false;
931 vds
= &Company::Get(_current_company
)->settings
.vehicle
;
932 update_vehicles
= true;
935 /* Test if the interval is valid */
936 uint16 interval
= GetServiceIntervalClamped(p1
, vds
->servint_ispercent
);
937 if (interval
!= p1
) return false;
939 if (update_vehicles
) {
941 FOR_ALL_VEHICLES(v
) {
942 if (v
->owner
== _current_company
&& v
->type
== type
&& v
->IsPrimaryVehicle() && !v
->ServiceIntervalIsCustom()) {
943 v
->SetServiceInterval(p1
);
948 InvalidateDetailsWindow(0);
953 static bool UpdateIntervalTrains(int32 p1
)
955 return UpdateInterval(VEH_TRAIN
, p1
);
958 static bool UpdateIntervalRoadVeh(int32 p1
)
960 return UpdateInterval(VEH_ROAD
, p1
);
963 static bool UpdateIntervalShips(int32 p1
)
965 return UpdateInterval(VEH_SHIP
, p1
);
968 static bool UpdateIntervalAircraft(int32 p1
)
970 return UpdateInterval(VEH_AIRCRAFT
, p1
);
973 static bool TrainAccelerationModelChanged(int32 p1
)
977 if (t
->IsFrontEngine()) {
978 t
->tcache
.cached_max_curve_speed
= t
->GetCurveSpeedLimit();
979 t
->UpdateAcceleration();
983 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
984 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
985 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
986 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
992 * This function updates the train acceleration cache after a steepness change.
993 * @param p1 Callback parameter.
994 * @return Always true.
996 static bool TrainSlopeSteepnessChanged(int32 p1
)
1000 if (t
->IsFrontEngine()) t
->CargoChanged();
1007 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
1008 * @param p1 Callback parameter
1009 * @return Always true
1011 static bool RoadVehAccelerationModelChanged(int32 p1
)
1013 if (_settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) {
1015 FOR_ALL_ROADVEHICLES(rv
) {
1016 if (rv
->IsFrontEngine()) {
1022 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1023 SetWindowClassesDirty(WC_ENGINE_PREVIEW
);
1024 InvalidateWindowClassesData(WC_BUILD_VEHICLE
, 0);
1025 SetWindowClassesDirty(WC_VEHICLE_DETAILS
);
1031 * This function updates the road vehicle acceleration cache after a steepness change.
1032 * @param p1 Callback parameter.
1033 * @return Always true.
1035 static bool RoadVehSlopeSteepnessChanged(int32 p1
)
1038 FOR_ALL_ROADVEHICLES(rv
) {
1039 if (rv
->IsFrontEngine()) rv
->CargoChanged();
1045 static bool DragSignalsDensityChanged(int32
)
1047 InvalidateWindowData(WC_BUILD_SIGNAL
, 0);
1052 static bool TownFoundingChanged(int32 p1
)
1054 if (_game_mode
!= GM_EDITOR
&& _settings_game
.economy
.found_town
== TF_FORBIDDEN
) {
1055 DeleteWindowById(WC_FOUND_TOWN
, 0);
1058 InvalidateWindowData(WC_FOUND_TOWN
, 0);
1062 static bool InvalidateVehTimetableWindow(int32 p1
)
1064 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE
, VIWD_MODIFY_ORDERS
);
1068 static bool InvalidateTicksPerMinute(int32 p1
)
1070 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE
, VIWD_MODIFY_ORDERS
);
1071 InvalidateWindowClassesData(WC_TRAINS_LIST
);
1072 InvalidateWindowClassesData(WC_TRACE_RESTRICT_SLOTS
);
1073 InvalidateWindowClassesData(WC_ROADVEH_LIST
);
1074 InvalidateWindowClassesData(WC_SHIPS_LIST
);
1075 InvalidateWindowClassesData(WC_AIRCRAFT_LIST
);
1076 InvalidateWindowClassesData(WC_DEPARTURES_BOARD
);
1077 InvalidateWindowClassesData(WC_STATUS_BAR
, SBI_TICKS_PER_MINUTE
);
1078 InvalidateWindowClassesData(WC_VEHICLE_TRIP_HISTORY
);
1083 static bool ZoomMinMaxChanged(int32 p1
)
1085 extern void ConstrainAllViewportsZoom();
1086 extern void UpdateFontHeightCache();
1087 ConstrainAllViewportsZoom();
1088 GfxClearSpriteCache();
1089 if (_settings_client
.gui
.zoom_min
> _gui_zoom
) {
1090 /* Restrict GUI zoom if it is no longer available. */
1091 _gui_zoom
= _settings_client
.gui
.zoom_min
;
1093 UpdateFontHeightCache();
1094 LoadStringWidthTable();
1100 * Update any possible saveload window and delete any newgrf dialogue as
1101 * its widget parts might change. Reinit all windows as it allows access to the
1102 * newgrf debug button.
1104 * @return Always true.
1106 static bool InvalidateNewGRFChangeWindows(int32 p1
)
1108 InvalidateWindowClassesData(WC_SAVELOAD
);
1109 DeleteWindowByClass(WC_GAME_OPTIONS
);
1114 static bool InvalidateCompanyLiveryWindow(int32 p1
)
1116 InvalidateWindowClassesData(WC_COMPANY_COLOUR
);
1117 return RedrawScreen(p1
);
1120 static bool InvalidateIndustryViewWindow(int32 p1
)
1122 InvalidateWindowClassesData(WC_INDUSTRY_VIEW
);
1126 static bool InvalidateAISettingsWindow(int32 p1
)
1128 InvalidateWindowClassesData(WC_AI_SETTINGS
);
1133 * Update the town authority window after a town authority setting change.
1135 * @return Always true.
1137 static bool RedrawTownAuthority(int32 p1
)
1139 SetWindowClassesDirty(WC_TOWN_AUTHORITY
);
1144 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1146 * @return Always true.
1148 static bool InvalidateCompanyInfrastructureWindow(int32 p1
)
1150 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE
);
1155 * Invalidate the company details window after the shares setting changed.
1157 * @return Always true.
1159 static bool InvalidateCompanyWindow(int32 p1
)
1161 InvalidateWindowClassesData(WC_COMPANY
);
1165 static bool SimulatedWormholeSignalsChanged(int32 p1
)
1167 extern void AfterLoadCompanyStats();
1168 AfterLoadCompanyStats();
1169 MarkWholeScreenDirty();
1173 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1174 static void ValidateSettings()
1176 /* Do not allow a custom sea level with the original land generator. */
1177 if (_settings_newgame
.game_creation
.land_generator
== LG_ORIGINAL
&&
1178 _settings_newgame
.difficulty
.quantity_sea_lakes
== CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
) {
1179 _settings_newgame
.difficulty
.quantity_sea_lakes
= CUSTOM_SEA_LEVEL_MIN_PERCENTAGE
;
1183 static bool DifficultyNoiseChange(int32 i
)
1185 if (_game_mode
== GM_NORMAL
) {
1186 UpdateAirportsNoise();
1187 if (_settings_game
.economy
.station_noise_level
) {
1188 InvalidateWindowClassesData(WC_TOWN_VIEW
, 0);
1195 static bool MaxNoAIsChange(int32 i
)
1197 if (GetGameSettings().difficulty
.max_no_competitors
!= 0 &&
1198 AI::GetInfoList()->size() == 0 &&
1199 (!_networking
|| _network_server
)) {
1200 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI
, INVALID_STRING_ID
, WL_CRITICAL
);
1207 * Check whether the road side may be changed.
1209 * @return true if the road side may be changed.
1211 static bool CheckRoadSide(int p1
)
1213 extern bool RoadVehiclesAreBuilt();
1214 return _game_mode
== GM_MENU
|| !RoadVehiclesAreBuilt();
1218 * Conversion callback for _gameopt_settings_game.landscape
1219 * It converts (or try) between old values and the new ones,
1220 * without losing initial setting of the user
1221 * @param value that was read from config file
1222 * @return the "hopefully" converted value
1224 static size_t ConvertLandscape(const char *value
)
1226 /* try with the old values */
1227 return LookupOneOfMany("normal|hilly|desert|candy", value
);
1230 static bool CheckFreeformEdges(int32 p1
)
1232 if (_game_mode
== GM_MENU
) return true;
1236 /* Check if there is a ship on the northern border. */
1237 if (TileX(s
->tile
) == 0 || TileY(s
->tile
) == 0) {
1238 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1243 FOR_ALL_BASE_STATIONS(st
) {
1244 /* Check if there is a non-deleted buoy on the northern border. */
1245 if (st
->IsInUse() && (TileX(st
->xy
) == 0 || TileY(st
->xy
) == 0)) {
1246 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY
, INVALID_STRING_ID
, WL_ERROR
);
1250 for (uint i
= 0; i
< MapSizeX(); i
++) MakeVoid(TileXY(i
, 0));
1251 for (uint i
= 0; i
< MapSizeY(); i
++) MakeVoid(TileXY(0, i
));
1253 for (uint i
= 0; i
< MapMaxX(); i
++) {
1254 if (TileHeight(TileXY(i
, 1)) != 0) {
1255 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1259 for (uint i
= 1; i
< MapMaxX(); i
++) {
1260 if (!IsTileType(TileXY(i
, MapMaxY() - 1), MP_WATER
) || TileHeight(TileXY(1, MapMaxY())) != 0) {
1261 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1265 for (uint i
= 0; i
< MapMaxY(); i
++) {
1266 if (TileHeight(TileXY(1, i
)) != 0) {
1267 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1271 for (uint i
= 1; i
< MapMaxY(); i
++) {
1272 if (!IsTileType(TileXY(MapMaxX() - 1, i
), MP_WATER
) || TileHeight(TileXY(MapMaxX(), i
)) != 0) {
1273 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER
, INVALID_STRING_ID
, WL_ERROR
);
1277 /* Make tiles at the border water again. */
1278 for (uint i
= 0; i
< MapMaxX(); i
++) {
1279 SetTileHeight(TileXY(i
, 0), 0);
1280 MakeSea(TileXY(i
, 0));
1282 for (uint i
= 0; i
< MapMaxY(); i
++) {
1283 SetTileHeight(TileXY(0, i
), 0);
1284 MakeSea(TileXY(0, i
));
1287 MarkWholeScreenDirty();
1292 * Changing the setting "allow multiple NewGRF sets" is not allowed
1293 * if there are vehicles.
1295 static bool ChangeDynamicEngines(int32 p1
)
1297 if (_game_mode
== GM_MENU
) return true;
1299 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1300 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES
, INVALID_STRING_ID
, WL_ERROR
);
1307 static bool ChangeMaxHeightLevel(int32 p1
)
1309 if (_game_mode
== GM_NORMAL
) return false;
1310 if (_game_mode
!= GM_EDITOR
) return true;
1312 /* Check if at least one mountain on the map is higher than the new value.
1313 * If yes, disallow the change. */
1314 for (TileIndex t
= 0; t
< MapSize(); t
++) {
1315 if ((int32
)TileHeight(t
) > p1
) {
1316 ShowErrorMessage(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN
, INVALID_STRING_ID
, WL_ERROR
);
1317 /* Return old, unchanged value */
1322 /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1323 InvalidateWindowClassesData(WC_SMALLMAP
, 2);
1328 static bool StationCatchmentChanged(int32 p1
)
1330 Station::RecomputeIndustriesNearForAll();
1334 static bool MaxVehiclesChanged(int32 p1
)
1336 InvalidateWindowClassesData(WC_BUILD_TOOLBAR
);
1337 MarkWholeScreenDirty();
1342 #ifdef ENABLE_NETWORK
1344 static bool UpdateClientName(int32 p1
)
1346 NetworkUpdateClientName();
1350 static bool UpdateServerPassword(int32 p1
)
1352 if (strcmp(_settings_client
.network
.server_password
, "*") == 0) {
1353 _settings_client
.network
.server_password
[0] = '\0';
1359 static bool UpdateRconPassword(int32 p1
)
1361 if (strcmp(_settings_client
.network
.rcon_password
, "*") == 0) {
1362 _settings_client
.network
.rcon_password
[0] = '\0';
1368 static bool UpdateClientConfigValues(int32 p1
)
1370 if (_network_server
) NetworkServerSendConfigUpdate();
1375 #endif /* ENABLE_NETWORK */
1378 /* End - Callback Functions */
1381 * Prepare for reading and old diff_custom by zero-ing the memory.
1383 static void PrepareOldDiffCustom()
1385 memset(_old_diff_custom
, 0, sizeof(_old_diff_custom
));
1389 * Reading of the old diff_custom array and transforming it to the new format.
1390 * @param savegame is it read from the config or savegame. In the latter case
1391 * we are sure there is an array; in the former case we have
1394 static void HandleOldDiffCustom(bool savegame
)
1396 uint options_to_load
= GAME_DIFFICULTY_NUM
- ((savegame
&& IsSavegameVersionBefore(4)) ? 1 : 0);
1399 /* If we did read to old_diff_custom, then at least one value must be non 0. */
1400 bool old_diff_custom_used
= false;
1401 for (uint i
= 0; i
< options_to_load
&& !old_diff_custom_used
; i
++) {
1402 old_diff_custom_used
= (_old_diff_custom
[i
] != 0);
1405 if (!old_diff_custom_used
) return;
1408 for (uint i
= 0; i
< options_to_load
; i
++) {
1409 const SettingDesc
*sd
= &_settings
[i
];
1410 /* Skip deprecated options */
1411 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
1412 void *var
= GetVariableAddress(savegame
? &_settings_game
: &_settings_newgame
, &sd
->save
);
1413 Write_ValidateSetting(var
, sd
, (int32
)((i
== 4 ? 1000 : 1) * _old_diff_custom
[i
]));
1417 static void AILoadConfig(IniFile
*ini
, const char *grpname
)
1419 IniGroup
*group
= ini
->GetGroup(grpname
);
1422 /* Clean any configured AI */
1423 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1424 AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
)->Change(nullptr);
1427 /* If no group exists, return */
1428 if (group
== nullptr) return;
1430 CompanyID c
= COMPANY_FIRST
;
1431 for (item
= group
->item
; c
< MAX_COMPANIES
&& item
!= nullptr; c
++, item
= item
->next
) {
1432 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1434 config
->Change(item
->name
);
1435 if (!config
->HasScript()) {
1436 if (strcmp(item
->name
, "none") != 0) {
1437 DEBUG(script
, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item
->name
);
1441 if (item
->value
!= nullptr) config
->StringToSettings(item
->value
);
1445 static void GameLoadConfig(IniFile
*ini
, const char *grpname
)
1447 IniGroup
*group
= ini
->GetGroup(grpname
);
1450 /* Clean any configured GameScript */
1451 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME
)->Change(nullptr);
1453 /* If no group exists, return */
1454 if (group
== nullptr) return;
1457 if (item
== nullptr) return;
1459 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1461 config
->Change(item
->name
);
1462 if (!config
->HasScript()) {
1463 if (strcmp(item
->name
, "none") != 0) {
1464 DEBUG(script
, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item
->name
);
1468 if (item
->value
!= nullptr) config
->StringToSettings(item
->value
);
1472 * Convert a character to a hex nibble value, or \c -1 otherwise.
1473 * @param c Character to convert.
1474 * @return Hex value of the character, or \c -1 if not a hex digit.
1476 static int DecodeHexNibble(char c
)
1478 if (c
>= '0' && c
<= '9') return c
- '0';
1479 if (c
>= 'A' && c
<= 'F') return c
+ 10 - 'A';
1480 if (c
>= 'a' && c
<= 'f') return c
+ 10 - 'a';
1485 * Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
1486 * After the hex number should be a \c '|' character.
1487 * @param pos First character to convert.
1488 * @param dest [out] Output byte array to write the bytes.
1489 * @param dest_size Number of bytes in \a dest.
1490 * @return Whether reading was successful.
1492 static bool DecodeHexText(char *pos
, uint8
*dest
, size_t dest_size
)
1494 while (dest_size
> 0) {
1495 int hi
= DecodeHexNibble(pos
[0]);
1496 int lo
= (hi
>= 0) ? DecodeHexNibble(pos
[1]) : -1;
1497 if (lo
< 0) return false;
1498 *dest
++ = (hi
<< 4) | lo
;
1506 * Load a GRF configuration
1507 * @param ini The configuration to read from.
1508 * @param grpname Group name containing the configuration of the GRF.
1509 * @param is_static GRF is static.
1511 static GRFConfig
*GRFLoadConfig(IniFile
*ini
, const char *grpname
, bool is_static
)
1513 IniGroup
*group
= ini
->GetGroup(grpname
);
1515 GRFConfig
*first
= nullptr;
1516 GRFConfig
**curr
= &first
;
1518 if (group
== nullptr) return nullptr;
1520 for (item
= group
->item
; item
!= nullptr; item
= item
->next
) {
1521 GRFConfig
*c
= nullptr;
1523 uint8 grfid_buf
[4], md5sum
[16];
1524 char *filename
= item
->name
;
1525 bool has_grfid
= false;
1526 bool has_md5sum
= false;
1528 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1529 has_grfid
= DecodeHexText(filename
, grfid_buf
, lengthof(grfid_buf
));
1531 filename
+= 1 + 2 * lengthof(grfid_buf
);
1532 has_md5sum
= DecodeHexText(filename
, md5sum
, lengthof(md5sum
));
1533 if (has_md5sum
) filename
+= 1 + 2 * lengthof(md5sum
);
1535 uint32 grfid
= grfid_buf
[0] | (grfid_buf
[1] << 8) | (grfid_buf
[2] << 16) | (grfid_buf
[3] << 24);
1537 const GRFConfig
*s
= FindGRFConfig(grfid
, FGCM_EXACT
, md5sum
);
1538 if (s
!= nullptr) c
= new GRFConfig(*s
);
1540 if (c
== nullptr && !FioCheckFileExists(filename
, NEWGRF_DIR
)) {
1541 const GRFConfig
*s
= FindGRFConfig(grfid
, FGCM_NEWEST_VALID
);
1542 if (s
!= nullptr) c
= new GRFConfig(*s
);
1545 if (c
== nullptr) c
= new GRFConfig(filename
);
1547 /* Parse parameters */
1548 if (!StrEmpty(item
->value
)) {
1549 int count
= ParseIntList(item
->value
, (int*)c
->param
, lengthof(c
->param
));
1551 SetDParamStr(0, filename
);
1552 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_ARRAY
, WL_CRITICAL
);
1555 c
->num_params
= count
;
1558 /* Check if item is valid */
1559 if (!FillGRFDetails(c
, is_static
) || HasBit(c
->flags
, GCF_INVALID
)) {
1560 if (c
->status
== GCS_NOT_FOUND
) {
1561 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND
);
1562 } else if (HasBit(c
->flags
, GCF_UNSAFE
)) {
1563 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE
);
1564 } else if (HasBit(c
->flags
, GCF_SYSTEM
)) {
1565 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM
);
1566 } else if (HasBit(c
->flags
, GCF_INVALID
)) {
1567 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE
);
1569 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN
);
1572 SetDParamStr(0, StrEmpty(filename
) ? item
->name
: filename
);
1573 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_GRF
, WL_CRITICAL
);
1578 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1579 bool duplicate
= false;
1580 for (const GRFConfig
*gc
= first
; gc
!= nullptr; gc
= gc
->next
) {
1581 if (gc
->ident
.grfid
== c
->ident
.grfid
) {
1582 SetDParamStr(0, c
->filename
);
1583 SetDParamStr(1, gc
->filename
);
1584 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_DUPLICATE_GRFID
, WL_CRITICAL
);
1594 /* Mark file as static to avoid saving in savegame. */
1595 if (is_static
) SetBit(c
->flags
, GCF_STATIC
);
1597 /* Add item to list */
1605 static void AISaveConfig(IniFile
*ini
, const char *grpname
)
1607 IniGroup
*group
= ini
->GetGroup(grpname
);
1609 if (group
== nullptr) return;
1612 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
1613 AIConfig
*config
= AIConfig::GetConfig(c
, AIConfig::SSS_FORCE_NEWGAME
);
1616 config
->SettingsToString(value
, lastof(value
));
1618 if (config
->HasScript()) {
1619 name
= config
->GetName();
1624 IniItem
*item
= new IniItem(group
, name
);
1625 item
->SetValue(value
);
1629 static void GameSaveConfig(IniFile
*ini
, const char *grpname
)
1631 IniGroup
*group
= ini
->GetGroup(grpname
);
1633 if (group
== nullptr) return;
1636 GameConfig
*config
= GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME
);
1639 config
->SettingsToString(value
, lastof(value
));
1641 if (config
->HasScript()) {
1642 name
= config
->GetName();
1647 IniItem
*item
= new IniItem(group
, name
);
1648 item
->SetValue(value
);
1652 * Save the version of OpenTTD to the ini file.
1653 * @param ini the ini to write to
1655 static void SaveVersionInConfig(IniFile
*ini
)
1657 IniGroup
*group
= ini
->GetGroup("version");
1660 seprintf(version
, lastof(version
), "%08X", _openttd_newgrf_version
);
1662 const char * const versions
[][2] = {
1663 { "version_string", _openttd_revision
},
1664 { "version_number", version
}
1667 for (uint i
= 0; i
< lengthof(versions
); i
++) {
1668 group
->GetItem(versions
[i
][0], true)->SetValue(versions
[i
][1]);
1672 /* Save a GRF configuration to the given group name */
1673 static void GRFSaveConfig(IniFile
*ini
, const char *grpname
, const GRFConfig
*list
)
1675 ini
->RemoveGroup(grpname
);
1676 IniGroup
*group
= ini
->GetGroup(grpname
);
1679 for (c
= list
; c
!= nullptr; c
= c
->next
) {
1680 /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1681 char key
[4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH
];
1683 GRFBuildParamList(params
, c
, lastof(params
));
1685 char *pos
= key
+ seprintf(key
, lastof(key
), "%08X|", BSWAP32(c
->ident
.grfid
));
1686 pos
= md5sumToString(pos
, lastof(key
), c
->ident
.md5sum
);
1687 seprintf(pos
, lastof(key
), "|%s", c
->filename
);
1688 group
->GetItem(key
, true)->SetValue(params
);
1692 /* Common handler for saving/loading variables to the configuration file */
1693 static void HandleSettingDescs(IniFile
*ini
, SettingDescProc
*proc
, SettingDescProcList
*proc_list
, bool basic_settings
= true, bool other_settings
= true)
1695 if (basic_settings
) {
1696 proc(ini
, (const SettingDesc
*)_misc_settings
, "misc", nullptr);
1697 #if defined(WIN32) && !defined(DEDICATED)
1698 proc(ini
, (const SettingDesc
*)_win32_settings
, "win32", nullptr);
1702 if (other_settings
) {
1703 proc(ini
, _settings
, "patches", &_settings_newgame
);
1704 proc(ini
, _currency_settings
,"currency", &_custom_currency
);
1705 proc(ini
, _company_settings
, "company", &_settings_client
.company
);
1707 #ifdef ENABLE_NETWORK
1708 proc_list(ini
, "server_bind_addresses", &_network_bind_list
);
1709 proc_list(ini
, "servers", &_network_host_list
);
1710 proc_list(ini
, "bans", &_network_ban_list
);
1711 #endif /* ENABLE_NETWORK */
1715 static IniFile
*IniLoadConfig()
1717 IniFile
*ini
= new IniFile(_list_group_names
);
1718 ini
->LoadFromDisk(_config_file
, NO_DIRECTORY
);
1723 * Load the values from the configuration files
1724 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1726 void LoadFromConfig(bool minimal
)
1728 IniFile
*ini
= IniLoadConfig();
1729 if (!minimal
) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1731 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1732 HandleSettingDescs(ini
, IniLoadSettings
, IniLoadSettingList
, minimal
, !minimal
);
1735 _grfconfig_newgame
= GRFLoadConfig(ini
, "newgrf", false);
1736 _grfconfig_static
= GRFLoadConfig(ini
, "newgrf-static", true);
1737 AILoadConfig(ini
, "ai_players");
1738 GameLoadConfig(ini
, "game_scripts");
1740 PrepareOldDiffCustom();
1741 IniLoadSettings(ini
, _gameopt_settings
, "gameopt", &_settings_newgame
);
1742 HandleOldDiffCustom(false);
1746 /* Display sheduled errors */
1747 extern void ScheduleErrorMessage(ErrorList
&datas
);
1748 ScheduleErrorMessage(_settings_error_list
);
1749 if (FindWindowById(WC_ERRMSG
, 0) == nullptr) ShowFirstError();
1755 /** Save the values to the configuration file */
1758 IniFile
*ini
= IniLoadConfig();
1760 /* Remove some obsolete groups. These have all been loaded into other groups. */
1761 ini
->RemoveGroup("patches");
1762 ini
->RemoveGroup("yapf");
1763 ini
->RemoveGroup("gameopt");
1765 HandleSettingDescs(ini
, IniSaveSettings
, IniSaveSettingList
);
1766 GRFSaveConfig(ini
, "newgrf", _grfconfig_newgame
);
1767 GRFSaveConfig(ini
, "newgrf-static", _grfconfig_static
);
1768 AISaveConfig(ini
, "ai_players");
1769 GameSaveConfig(ini
, "game_scripts");
1770 SaveVersionInConfig(ini
);
1771 ini
->SaveToDisk(_config_file
);
1776 * Get the list of known NewGrf presets.
1777 * @param list[inout] Pointer to list for storing the preset names.
1779 void GetGRFPresetList(GRFPresetList
*list
)
1783 IniFile
*ini
= IniLoadConfig();
1785 for (group
= ini
->group
; group
!= nullptr; group
= group
->next
) {
1786 if (strncmp(group
->name
, "preset-", 7) == 0) {
1787 *list
->Append() = stredup(group
->name
+ 7);
1795 * Load a NewGRF configuration by preset-name.
1796 * @param config_name Name of the preset.
1797 * @return NewGRF configuration.
1798 * @see GetGRFPresetList
1800 GRFConfig
*LoadGRFPresetFromConfig(const char *config_name
)
1802 size_t len
= strlen(config_name
) + 8;
1803 char *section
= (char*)alloca(len
);
1804 seprintf(section
, section
+ len
- 1, "preset-%s", config_name
);
1806 IniFile
*ini
= IniLoadConfig();
1807 GRFConfig
*config
= GRFLoadConfig(ini
, section
, false);
1814 * Save a NewGRF configuration with a preset name.
1815 * @param config_name Name of the preset.
1816 * @param config NewGRF configuration to save.
1817 * @see GetGRFPresetList
1819 void SaveGRFPresetToConfig(const char *config_name
, GRFConfig
*config
)
1821 size_t len
= strlen(config_name
) + 8;
1822 char *section
= (char*)alloca(len
);
1823 seprintf(section
, section
+ len
- 1, "preset-%s", config_name
);
1825 IniFile
*ini
= IniLoadConfig();
1826 GRFSaveConfig(ini
, section
, config
);
1827 ini
->SaveToDisk(_config_file
);
1832 * Delete a NewGRF configuration by preset name.
1833 * @param config_name Name of the preset.
1835 void DeleteGRFPresetFromConfig(const char *config_name
)
1837 size_t len
= strlen(config_name
) + 8;
1838 char *section
= (char*)alloca(len
);
1839 seprintf(section
, section
+ len
- 1, "preset-%s", config_name
);
1841 IniFile
*ini
= IniLoadConfig();
1842 ini
->RemoveGroup(section
);
1843 ini
->SaveToDisk(_config_file
);
1847 const SettingDesc
*GetSettingDescription(uint index
)
1849 if (index
>= lengthof(_settings
)) return nullptr;
1850 return &_settings
[index
];
1854 * Network-safe changing of settings (server-only).
1855 * @param tile unused
1856 * @param flags operation to perform
1857 * @param p1 the index of the setting in the SettingDesc array which identifies it
1858 * @param p2 the new value for the setting
1859 * The new value is properly clamped to its minimum/maximum when setting
1860 * @param text unused
1861 * @return the cost of this operation or an error
1864 CommandCost
CmdChangeSetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1866 const SettingDesc
*sd
= GetSettingDescription(p1
);
1868 if (sd
== nullptr) return CommandError();
1869 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) return CommandError();
1871 if (!sd
->IsEditable(true)) return CommandError();
1873 if (flags
& DC_EXEC
) {
1874 void *var
= GetVariableAddress(&GetGameSettings(), &sd
->save
);
1876 int32 oldval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1877 int32 newval
= (int32
)p2
;
1879 Write_ValidateSetting(var
, sd
, newval
);
1880 newval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1882 if (oldval
== newval
) return CommandCost();
1884 if (sd
->desc
.proc
!= nullptr && !sd
->desc
.proc(newval
)) {
1885 WriteValue(var
, sd
->save
.conv
, (int64
)oldval
);
1886 return CommandCost();
1889 if (sd
->desc
.flags
& SGF_NO_NETWORK
) {
1890 GamelogStartAction(GLAT_SETTING
);
1891 GamelogSetting(sd
->desc
.name
, oldval
, newval
);
1892 GamelogStopAction();
1895 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1898 return CommandCost();
1902 * Change one of the per-company settings.
1903 * @param tile unused
1904 * @param flags operation to perform
1905 * @param p1 the index of the setting in the _company_settings array which identifies it
1906 * @param p2 the new value for the setting
1907 * The new value is properly clamped to its minimum/maximum when setting
1908 * @param text unused
1909 * @return the cost of this operation or an error
1911 CommandCost
CmdChangeCompanySetting(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1913 if (p1
>= lengthof(_company_settings
)) return CommandError();
1914 const SettingDesc
*sd
= &_company_settings
[p1
];
1916 if (flags
& DC_EXEC
) {
1917 void *var
= GetVariableAddress(&Company::Get(_current_company
)->settings
, &sd
->save
);
1919 int32 oldval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1920 int32 newval
= (int32
)p2
;
1922 Write_ValidateSetting(var
, sd
, newval
);
1923 newval
= (int32
)ReadValue(var
, sd
->save
.conv
);
1925 if (oldval
== newval
) return CommandCost();
1927 if (sd
->desc
.proc
!= nullptr && !sd
->desc
.proc(newval
)) {
1928 WriteValue(var
, sd
->save
.conv
, (int64
)oldval
);
1929 return CommandCost();
1932 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1935 return CommandCost();
1939 * Top function to save the new value of an element of the Settings struct
1940 * @param index offset in the SettingDesc array of the Settings struct which
1941 * identifies the setting member we want to change
1942 * @param value new value of the setting
1943 * @param force_newgame force the newgame settings
1945 bool SetSettingValue(uint index
, int32 value
, bool force_newgame
)
1947 const SettingDesc
*sd
= &_settings
[index
];
1948 /* If an item is company-based, we do not send it over the network
1949 * (if any) to change. Also *hack*hack* we update the _newgame version
1950 * of settings because changing a company-based setting in a game also
1951 * changes its defaults. At least that is the convention we have chosen */
1952 if (sd
->save
.conv
& SLF_NO_NETWORK_SYNC
) {
1953 void *var
= GetVariableAddress(&GetGameSettings(), &sd
->save
);
1954 Write_ValidateSetting(var
, sd
, value
);
1956 if (_game_mode
!= GM_MENU
) {
1957 void *var2
= GetVariableAddress(&_settings_newgame
, &sd
->save
);
1958 Write_ValidateSetting(var2
, sd
, value
);
1960 if (sd
->desc
.proc
!= nullptr) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
1962 SetWindowClassesDirty(WC_GAME_OPTIONS
);
1967 if (force_newgame
) {
1968 void *var2
= GetVariableAddress(&_settings_newgame
, &sd
->save
);
1969 Write_ValidateSetting(var2
, sd
, value
);
1973 /* send non-company-based settings over the network */
1974 if (!_networking
|| (_networking
&& _network_server
)) {
1975 return DoCommandP(0, index
, value
, CMD_CHANGE_SETTING
);
1981 * Top function to save the new value of an element of the Settings struct
1982 * @param index offset in the SettingDesc array of the CompanySettings struct
1983 * which identifies the setting member we want to change
1984 * @param value new value of the setting
1986 void SetCompanySetting(uint index
, int32 value
)
1988 const SettingDesc
*sd
= &_company_settings
[index
];
1989 if (Company::IsValidID(_local_company
) && _game_mode
!= GM_MENU
) {
1990 DoCommandP(0, index
, value
, CMD_CHANGE_COMPANY_SETTING
);
1992 void *var
= GetVariableAddress(&_settings_client
.company
, &sd
->save
);
1993 Write_ValidateSetting(var
, sd
, value
);
1994 if (sd
->desc
.proc
!= nullptr) sd
->desc
.proc((int32
)ReadValue(var
, sd
->save
.conv
));
1999 * Set the company settings for a new company to their default values.
2001 void SetDefaultCompanySettings(CompanyID cid
)
2003 Company
*c
= Company::Get(cid
);
2004 const SettingDesc
*sd
;
2005 for (sd
= _company_settings
; sd
->save
.cmd
!= SL_END
; sd
++) {
2006 void *var
= GetVariableAddress(&c
->settings
, &sd
->save
);
2007 Write_ValidateSetting(var
, sd
, (int32
)(size_t)sd
->desc
.def
);
2011 #if defined(ENABLE_NETWORK)
2013 * Sync all company settings in a multiplayer game.
2015 void SyncCompanySettings()
2017 const SettingDesc
*sd
;
2019 for (sd
= _company_settings
; sd
->save
.cmd
!= SL_END
; sd
++, i
++) {
2020 const void *old_var
= GetVariableAddress(&Company::Get(_current_company
)->settings
, &sd
->save
);
2021 const void *new_var
= GetVariableAddress(&_settings_client
.company
, &sd
->save
);
2022 uint32 old_value
= (uint32
)ReadValue(old_var
, sd
->save
.conv
);
2023 uint32 new_value
= (uint32
)ReadValue(new_var
, sd
->save
.conv
);
2024 if (old_value
!= new_value
) NetworkSendCommand(0, i
, new_value
, CMD_CHANGE_COMPANY_SETTING
, nullptr, nullptr, _local_company
, 0);
2027 #endif /* ENABLE_NETWORK */
2030 * Get the index in the _company_settings array of a setting
2031 * @param name The name of the setting
2032 * @return The index in the _company_settings array
2034 uint
GetCompanySettingIndex(const char *name
)
2037 const SettingDesc
*sd
= GetSettingFromName(name
, &i
);
2038 assert(sd
!= nullptr && (sd
->desc
.flags
& SGF_PER_COMPANY
) != 0);
2043 * Set a setting value with a string.
2044 * @param index the settings index.
2045 * @param value the value to write
2046 * @param force_newgame force the newgame settings
2047 * @note Strings WILL NOT be synced over the network
2049 bool SetSettingValue(uint index
, const char *value
, bool force_newgame
)
2051 const SettingDesc
*sd
= &_settings
[index
];
2052 assert(sd
->save
.conv
& SLF_NO_NETWORK_SYNC
);
2054 if (GetVarMemType(sd
->save
.conv
) == SLE_VAR_STRQ
) {
2055 char **var
= (char**)GetVariableAddress((_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
, &sd
->save
);
2057 *var
= strcmp(value
, "(null)") == 0 ? nullptr : stredup(value
);
2059 char *var
= (char*)GetVariableAddress(nullptr, &sd
->save
);
2060 strecpy(var
, value
, &var
[sd
->save
.length
- 1]);
2062 if (sd
->desc
.proc
!= nullptr) sd
->desc
.proc(0);
2068 * Given a name of setting, return a setting description of it.
2069 * @param name Name of the setting to return a setting description of
2070 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
2071 * @return Pointer to the setting description of setting \a name if it can be found,
2072 * \c nullptr indicates failure to obtain the description
2074 const SettingDesc
*GetSettingFromName(const char *name
, uint
*i
)
2076 const SettingDesc
*sd
;
2078 /* First check all full names */
2079 for (*i
= 0, sd
= _settings
; sd
->save
.cmd
!= SL_END
; sd
++, (*i
)++) {
2080 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2081 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
2084 /* Then check the shortcut variant of the name. */
2085 for (*i
= 0, sd
= _settings
; sd
->save
.cmd
!= SL_END
; sd
++, (*i
)++) {
2086 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2087 const char *short_name
= strchr(sd
->desc
.name
, '.');
2088 if (short_name
!= nullptr) {
2090 if (strcmp(short_name
, name
) == 0) return sd
;
2094 if (strncmp(name
, "company.", 8) == 0) name
+= 8;
2095 /* And finally the company-based settings */
2096 for (*i
= 0, sd
= _company_settings
; sd
->save
.cmd
!= SL_END
; sd
++, (*i
)++) {
2097 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2098 if (strcmp(sd
->desc
.name
, name
) == 0) return sd
;
2104 /* Those 2 functions need to be here, else we have to make some stuff non-static
2105 * and besides, it is also better to keep stuff like this at the same place */
2106 void IConsoleSetSetting(const char *name
, const char *value
, bool force_newgame
)
2109 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2111 if (sd
== nullptr) {
2112 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
2117 if (sd
->desc
.cmd
== SDT_STRING
) {
2118 success
= SetSettingValue(index
, value
, force_newgame
);
2121 extern bool GetArgumentInteger(uint32
*value
, const char *arg
);
2122 success
= GetArgumentInteger(&val
, value
);
2124 IConsolePrintF(CC_ERROR
, "'%s' is not an integer.", value
);
2128 success
= SetSettingValue(index
, val
, force_newgame
);
2132 if (_network_server
) {
2133 IConsoleError("This command/variable is not available during network games.");
2135 IConsoleError("This command/variable is only available to a network server.");
2140 void IConsoleSetSetting(const char *name
, int value
)
2143 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2144 assert(sd
!= nullptr);
2145 SetSettingValue(index
, value
);
2149 * Output value of a specific setting to the console
2150 * @param name Name of the setting to output its value
2151 * @param force_newgame force the newgame settings
2153 void IConsoleGetSetting(const char *name
, bool force_newgame
)
2157 const SettingDesc
*sd
= GetSettingFromName(name
, &index
);
2160 if (sd
== nullptr) {
2161 IConsolePrintF(CC_WARNING
, "'%s' is an unknown setting.", name
);
2165 ptr
= GetVariableAddress((_game_mode
== GM_MENU
|| force_newgame
) ? &_settings_newgame
: &_settings_game
, &sd
->save
);
2167 if (sd
->desc
.cmd
== SDT_STRING
) {
2168 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s'", name
, (GetVarMemType(sd
->save
.conv
) == SLE_VAR_STRQ
) ? *(const char * const *)ptr
: (const char *)ptr
);
2170 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2171 seprintf(value
, lastof(value
), (*(const bool*)ptr
!= 0) ? "on" : "off");
2173 seprintf(value
, lastof(value
), sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2176 IConsolePrintF(CC_WARNING
, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2177 name
, value
, (sd
->desc
.flags
& SGF_0ISDISABLED
) ? "(0) " : "", sd
->desc
.min
, sd
->desc
.max
);
2182 * List all settings and their value to the console
2184 * @param prefilter If not \c nullptr, only list settings with names that begin with \a prefilter prefix
2186 void IConsoleListSettings(const char *prefilter
)
2188 IConsolePrintF(CC_WARNING
, "All settings with their current value:");
2190 for (const SettingDesc
*sd
= _settings
; sd
->save
.cmd
!= SL_END
; sd
++) {
2191 if (!SlIsObjectCurrentlyValid(sd
->save
.version_from
, sd
->save
.version_to
)) continue;
2192 if (prefilter
!= nullptr && strstr(sd
->desc
.name
, prefilter
) == nullptr) continue;
2194 const void *ptr
= GetVariableAddress(&GetGameSettings(), &sd
->save
);
2196 if (sd
->desc
.cmd
== SDT_BOOLX
) {
2197 seprintf(value
, lastof(value
), (*(const bool *)ptr
!= 0) ? "on" : "off");
2198 } else if (sd
->desc
.cmd
== SDT_STRING
) {
2199 seprintf(value
, lastof(value
), "%s", (GetVarMemType(sd
->save
.conv
) == SLE_VAR_STRQ
) ? *(const char * const *)ptr
: (const char *)ptr
);
2201 seprintf(value
, lastof(value
), sd
->desc
.min
< 0 ? "%d" : "%u", (int32
)ReadValue(ptr
, sd
->save
.conv
));
2203 IConsolePrintF(CC_DEFAULT
, "%s = %s", sd
->desc
.name
, value
);
2206 IConsolePrintF(CC_WARNING
, "Use 'setting' command to change a value");
2210 * Save and load handler for settings
2211 * @param osd SettingDesc struct containing all information
2212 * @param object can be either nullptr in which case we load global variables or
2213 * a pointer to a struct which is getting saved
2215 static void LoadSettings(const SettingDesc
*osd
, void *object
)
2217 for (; osd
->save
.cmd
!= SL_END
; osd
++) {
2218 const SaveLoad
*sld
= &osd
->save
;
2219 void *ptr
= GetVariableAddress(object
, sld
);
2221 if (!SlObjectMember(ptr
, sld
)) continue;
2222 if (IsNumericType(sld
->conv
)) Write_ValidateSetting(ptr
, osd
, ReadValue(ptr
, sld
->conv
));
2227 * Save and load handler for settings
2228 * @param sd SettingDesc struct containing all information
2229 * @param object can be either nullptr in which case we load global variables or
2230 * a pointer to a struct which is getting saved
2232 static void SaveSettings(const SettingDesc
*sd
, void *object
)
2234 /* We need to write the CH_RIFF header, but unfortunately can't call
2235 * SlCalcLength() because we have a different format. So do this manually */
2236 const SettingDesc
*i
;
2238 for (i
= sd
; i
->save
.cmd
!= SL_END
; i
++) {
2239 length
+= SlCalcObjMemberLength(object
, &i
->save
);
2241 SlSetLength(length
);
2243 for (i
= sd
; i
->save
.cmd
!= SL_END
; i
++) {
2244 void *ptr
= GetVariableAddress(object
, &i
->save
);
2245 SlObjectMember(ptr
, &i
->save
);
2249 static void Load_OPTS()
2251 /* Copy over default setting since some might not get loaded in
2252 * a networking environment. This ensures for example that the local
2253 * autosave-frequency stays when joining a network-server */
2254 PrepareOldDiffCustom();
2255 LoadSettings(_gameopt_settings
, &_settings_game
);
2256 HandleOldDiffCustom(true);
2259 static void Load_PATS()
2261 /* Copy over default setting since some might not get loaded in
2262 * a networking environment. This ensures for example that the local
2263 * currency setting stays when joining a network-server */
2264 LoadSettings(_settings
, &_settings_game
);
2267 static void Check_PATS()
2269 LoadSettings(_settings
, &_load_check_data
.settings
);
2272 static void Save_PATS()
2274 SaveSettings(_settings
, &_settings_game
);
2280 * Increase old default values for pf_maxdepth and pf_maxlength
2281 * to support big networks.
2283 if (_settings_newgame
.pf
.opf
.pf_maxdepth
== 16 && _settings_newgame
.pf
.opf
.pf_maxlength
== 512) {
2284 _settings_newgame
.pf
.opf
.pf_maxdepth
= 48;
2285 _settings_newgame
.pf
.opf
.pf_maxlength
= 4096;
2289 extern const ChunkHandler _setting_chunk_handlers
[] = {
2290 { 'OPTS', nullptr, Load_OPTS
, nullptr, nullptr, CH_RIFF
},
2291 { 'PATS', Save_PATS
, Load_PATS
, nullptr, Check_PATS
, CH_RIFF
| CH_LAST
},
2294 static bool IsSignedVarMemType(VarType vt
)
2296 switch (GetVarMemType(vt
)) {