Translations update
[openttd/fttd.git] / src / settings.cpp
blob3f6a1ed8e213bbfc517bda2f666f675003dec7f7
1 /* $Id$ */
3 /*
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/>.
8 */
10 /**
11 * @file settings.cpp
12 * All actions handling saving and loading of the settings/configuration goes on in this file.
13 * The file consists of three parts:
14 * <ol>
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.
21 * </ol>
22 * @see SettingDesc
23 * @see SaveLoad
26 #include "stdafx.h"
27 #include "string.h"
28 #include "currency.h"
29 #include "screenshot.h"
30 #include "network/network.h"
31 #include "network/network_func.h"
32 #include "settings_internal.h"
33 #include "command_func.h"
34 #include "console_func.h"
35 #include "pathfinder/yapf/yapf.h"
36 #include "genworld.h"
37 #include "train.h"
38 #include "news_func.h"
39 #include "window_func.h"
40 #include "sound_func.h"
41 #include "company_func.h"
42 #include "rev.h"
43 #ifdef WITH_FREETYPE
44 #include "fontcache.h"
45 #endif
46 #include "textbuf_gui.h"
47 #include "rail_gui.h"
48 #include "elrail_func.h"
49 #include "error.h"
50 #include "town.h"
51 #include "video/video_driver.hpp"
52 #include "sound/sound_driver.hpp"
53 #include "music/music_driver.hpp"
54 #include "blitter/factory.hpp"
55 #include "base_media_base.h"
56 #include "gamelog.h"
57 #include "settings_func.h"
58 #include "ini_type.h"
59 #include "ai/ai_config.hpp"
60 #include "ai/ai.hpp"
61 #include "game/game_config.hpp"
62 #include "game/game.hpp"
63 #include "ship.h"
64 #include "smallmap_gui.h"
65 #include "roadveh.h"
66 #include "fios.h"
67 #include "strings_func.h"
69 #include "map/ground.h"
70 #include "station_base.h"
71 #include "station_func.h"
73 #include "table/strings.h"
74 #include "table/settings.h"
76 ClientSettings _settings_client;
77 GameSettings _settings_game; ///< Game settings of a running game or the scenario editor.
78 GameSettings _settings_newgame; ///< Game settings for new games (updated from the intro screen).
79 VehicleDefaultSettings _old_vds; ///< Used for loading default vehicles settings from old savegames
80 char *_config_file; ///< Configuration file of OpenTTD
82 typedef std::list<ErrorMessageData> ErrorList;
83 static ErrorList _settings_error_list; ///< Errors while loading minimal settings.
86 typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
87 typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList *list);
89 static bool IsSignedVarMemType(VarType vt);
91 /**
92 * Groups in openttd.cfg that are actually lists.
94 static const char * const _list_group_names[] = {
95 "bans",
96 "newgrf",
97 "servers",
98 "server_bind_addresses",
99 NULL
103 * Find the index value of a ONEofMANY type in a string separated by |
104 * @param many full domain of values the ONEofMANY setting can have
105 * @param one the current value of the setting for which a value needs found
106 * @param onelen force calculation of the *one parameter
107 * @return the integer index of the full-list, or -1 if not found
109 static size_t LookupOneOfMany(const char *many, const char *one, size_t onelen = 0)
111 const char *s;
112 size_t idx;
114 if (onelen == 0) onelen = strlen(one);
116 /* check if it's an integer */
117 if (*one >= '0' && *one <= '9') return strtoul(one, NULL, 0);
119 idx = 0;
120 for (;;) {
121 /* find end of item */
122 s = many;
123 while (*s != '|' && *s != 0) s++;
124 if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
125 if (*s == 0) return (size_t)-1;
126 many = s + 1;
127 idx++;
132 * Find the set-integer value MANYofMANY type in a string
133 * @param many full domain of values the MANYofMANY setting can have
134 * @param str the current string value of the setting, each individual
135 * of separated by a whitespace,tab or | character
136 * @return the 'fully' set integer, or -1 if a set is not found
138 static size_t LookupManyOfMany(const char *many, const char *str)
140 const char *s;
141 size_t r;
142 size_t res = 0;
144 for (;;) {
145 /* skip "whitespace" */
146 while (*str == ' ' || *str == '\t' || *str == '|') str++;
147 if (*str == 0) break;
149 s = str;
150 while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
152 r = LookupOneOfMany(many, str, s - str);
153 if (r == (size_t)-1) return r;
155 SetBit(res, (uint8)r); // value found, set it
156 if (*s == 0) break;
157 str = s + 1;
159 return res;
163 * Parse an integerlist string and set each found value
164 * @param p the string to be parsed. Each element in the list is separated by a
165 * comma or a space character
166 * @param items pointer to the integerlist-array that will be filled with values
167 * @param maxitems the maximum number of elements the integerlist-array has
168 * @return returns the number of items found, or -1 on an error
170 static int ParseIntList(const char *p, int *items, int maxitems)
172 int n = 0; // number of items read so far
173 bool comma = false; // do we accept comma?
175 while (*p != '\0') {
176 switch (*p) {
177 case ',':
178 /* Do not accept multiple commas between numbers */
179 if (!comma) return -1;
180 comma = false;
181 /* FALL THROUGH */
182 case ' ':
183 p++;
184 break;
186 default: {
187 if (n == maxitems) return -1; // we don't accept that many numbers
188 char *end;
189 long v = strtol(p, &end, 0);
190 if (p == end) return -1; // invalid character (not a number)
191 if (sizeof(int) < sizeof(long)) v = ClampToI32(v);
192 items[n++] = v;
193 p = end; // first non-number
194 comma = true; // we accept comma now
195 break;
200 /* If we have read comma but no number after it, fail.
201 * We have read comma when (n != 0) and comma is not allowed */
202 if (n != 0 && !comma) return -1;
204 return n;
208 * Load parsed string-values into an integer-array (intlist)
209 * @param str the string that contains the values (and will be parsed)
210 * @param array pointer to the integer-arrays that will be filled
211 * @param nelems the number of elements the array holds. Maximum is 64 elements
212 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
213 * @return return true on success and false on error
215 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
217 int items[64];
218 int i, nitems;
220 if (str == NULL) {
221 memset(items, 0, sizeof(items));
222 nitems = nelems;
223 } else {
224 nitems = ParseIntList(str, items, lengthof(items));
225 if (nitems != nelems) return false;
228 switch (type) {
229 case SLE_VAR_BL:
230 case SLE_VAR_I8:
231 case SLE_VAR_U8:
232 for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
233 break;
235 case SLE_VAR_I16:
236 case SLE_VAR_U16:
237 for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
238 break;
240 case SLE_VAR_I32:
241 case SLE_VAR_U32:
242 for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
243 break;
245 default: NOT_REACHED();
248 return true;
252 * Convert an integer-array (intlist) to a string representation. Each value
253 * is separated by a comma or a space character
254 * @param array pointer to the integer-arrays that is read from
255 * @param nelems the number of elements the array holds.
256 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
257 * @return the string representation in newly-allocated storage
259 static char *MakeIntList (const void *array, int nelems, VarType type)
261 sstring<512> buffer;
263 int i, v = 0;
264 const byte *p = (const byte *)array;
266 for (i = 0; i != nelems; i++) {
267 switch (type) {
268 case SLE_VAR_BL:
269 case SLE_VAR_I8: v = *(const int8 *)p; p += 1; break;
270 case SLE_VAR_U8: v = *(const uint8 *)p; p += 1; break;
271 case SLE_VAR_I16: v = *(const int16 *)p; p += 2; break;
272 case SLE_VAR_U16: v = *(const uint16 *)p; p += 2; break;
273 case SLE_VAR_I32: v = *(const int32 *)p; p += 4; break;
274 case SLE_VAR_U32: v = *(const uint32 *)p; p += 4; break;
275 default: NOT_REACHED();
277 buffer.append_fmt ((i == 0) ? "%d" : ",%d", v);
280 return xstrdup (buffer.c_str());
284 * Convert a ONEofMANY structure to a string representation.
285 * @param many the full-domain string of possible values
286 * @param id the value of the variable and whose string-representation must be found
287 * @return the string representation in newly-allocated storage
289 static char *MakeOneOfMany (const char *many, int id)
291 int orig_id = id;
293 /* Look for the id'th element */
294 while (--id >= 0) {
295 many = strchr (many, '|');
296 if (many == NULL) { // not found
297 return str_fmt ("%d", orig_id);
299 many++; // pass the |-character
302 /* copy string until next item (|) or the end of the list if this is the last one */
303 const char *end = strchr (many, '|');
304 if (end == NULL) {
305 return xstrdup (many);
306 } else {
307 return xstrmemdup (many, end - many);
312 * Convert a MANYofMANY structure to a string representation.
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
316 * @return the string representation in newly-allocated storage
318 static char *MakeManyOfMany (const char *many, uint32 x)
320 sstring<512> buffer;
321 int i = 0;
323 for (; x != 0; x >>= 1, i++) {
324 const char *start = many;
325 while (*many != 0 && *many != '|') many++; // advance to the next element
327 if (HasBit(x, 0)) { // item found, copy it
328 if (!buffer.empty()) buffer.append ('|');
329 if (start == many) {
330 buffer.append_fmt ("%d", i);
331 } else {
332 buffer.append_fmt ("%.*s", (int)(many - start), start);
336 if (*many == '|') many++;
339 return xstrdup (buffer.c_str());
343 * Convert a string representation (external) of a setting to the internal rep.
344 * @param desc SettingDesc struct that holds all information about the variable
345 * @param orig_str input string that will be parsed based on the type of desc
346 * @return return the parsed value of the setting
348 static const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
350 const char *str = orig_str == NULL ? "" : orig_str;
352 switch (desc->cmd) {
353 case SDT_NUMX: {
354 char *end;
355 size_t val = strtoul(str, &end, 0);
356 if (end == str) {
357 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
358 msg.SetDParamStr(0, str);
359 msg.SetDParamStr(1, desc->name);
360 _settings_error_list.push_back(msg);
361 return desc->def;
363 if (*end != '\0') {
364 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_TRAILING_CHARACTERS);
365 msg.SetDParamStr(0, desc->name);
366 _settings_error_list.push_back(msg);
368 return (void*)val;
371 case SDT_ONEOFMANY: {
372 size_t r = LookupOneOfMany(desc->many, str);
373 /* if the first attempt of conversion from string to the appropriate value fails,
374 * look if we have defined a converter from old value to new value. */
375 if (r == (size_t)-1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
376 if (r != (size_t)-1) return (void*)r; // and here goes converted value
378 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
379 msg.SetDParamStr(0, str);
380 msg.SetDParamStr(1, desc->name);
381 _settings_error_list.push_back(msg);
382 return desc->def;
385 case SDT_MANYOFMANY: {
386 size_t r = LookupManyOfMany(desc->many, str);
387 if (r != (size_t)-1) return (void*)r;
388 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
389 msg.SetDParamStr(0, str);
390 msg.SetDParamStr(1, desc->name);
391 _settings_error_list.push_back(msg);
392 return desc->def;
395 case SDT_BOOLX: {
396 if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0) return (void*)true;
397 if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return (void*)false;
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_STRING: return orig_str;
407 case SDT_INTLIST: return str;
408 default: break;
411 return NULL;
415 * Set the value of a setting and if needed clamp the value to
416 * the preset minimum and maximum.
417 * @param ptr the variable itself
418 * @param sd pointer to the 'information'-database of the variable
419 * @param val signed long version of the new value
420 * @pre SettingDesc is of type SDT_BOOLX, SDT_NUMX,
421 * SDT_ONEOFMANY or SDT_MANYOFMANY. Other types are not supported as of now
423 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
425 const SettingDescBase *sdb = &sd->desc;
427 if (sdb->cmd != SDT_BOOLX &&
428 sdb->cmd != SDT_NUMX &&
429 sdb->cmd != SDT_ONEOFMANY &&
430 sdb->cmd != SDT_MANYOFMANY) {
431 return;
434 /* We cannot know the maximum value of a bitset variable, so just have faith */
435 if (sdb->cmd != SDT_MANYOFMANY) {
436 assert(sd->save.type == SL_VAR);
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
441 * 32-bit variable
442 * TODO: Support 64-bit settings/variables */
443 switch (GetVarMemType(sd->save.conv)) {
444 case SLE_VAR_BL:
445 case SLE_VAR_I8:
446 case SLE_VAR_U8:
447 case SLE_VAR_I16:
448 case SLE_VAR_U16:
449 case SLE_VAR_I32: {
450 /* Override the minimum value. No value below sdb->min, except special value 0 */
451 if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) val = Clamp(val, sdb->min, sdb->max);
452 break;
454 case SLE_VAR_U32: {
455 /* Override the minimum value. No value below sdb->min, except special value 0 */
456 uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
457 WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
458 return;
460 case SLE_VAR_I64:
461 case SLE_VAR_U64:
462 default: NOT_REACHED();
466 WriteValue(ptr, sd->save.conv, (int64)val);
470 * Load values from a group of an IniFile structure into the internal representation
471 * @param ini pointer to IniFile structure that holds administrative information
472 * @param sd pointer to SettingDesc structure whose internally pointed variables will
473 * be given values
474 * @param grpname the group of the IniFile to search in for the new values
475 * @param object pointer to the object been loaded
477 static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
479 const IniGroup *group_def = ini->get_group (grpname);
481 for (; sd->save.type != SL_END; sd++) {
482 const SettingDescBase *sdb = &sd->desc;
483 const SaveLoad *sld = &sd->save;
485 if (!sld->is_currently_valid()) continue;
487 /* For settings.xx.yy load the settings from [xx] yy = ? */
488 const char *s = strchr(sdb->name, '.');
489 const IniGroup *group;
490 if (s != NULL) {
491 group = ini->get_group (sdb->name, s - sdb->name);
492 s++;
493 } else {
494 s = sdb->name;
495 group = group_def;
498 const IniItem *item = group->find (s);
499 if (item == NULL && group != group_def) {
500 /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
501 * did not exist (e.g. loading old config files with a [settings] section */
502 item = group_def->find (s);
504 if (item == NULL) {
505 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
506 * did not exist (e.g. loading old config files with a [yapf] section */
507 const char *sc = strchr(s, '.');
508 if (sc != NULL) item = ini->get_group (s, sc - s)->find (sc + 1);
511 const void *p = (item == NULL) ? sdb->def : StringToVal(sdb, item->value);
512 void *ptr = sld->get_variable_address (object);
514 switch (sdb->cmd) {
515 case SDT_BOOLX: // All four are various types of (integer) numbers
516 case SDT_NUMX:
517 case SDT_ONEOFMANY:
518 case SDT_MANYOFMANY:
519 Write_ValidateSetting(ptr, sd, (int32)(size_t)p);
520 break;
522 case SDT_STRING:
523 assert (sld->type == SL_STR);
524 if (sld->length == 0) {
525 free(*(char**)ptr);
526 *(char**)ptr = p == NULL ? NULL : xstrdup((const char*)p);
527 } else {
528 if (p != NULL) ttd_strlcpy((char*)ptr, (const char*)p, sld->length);
530 break;
532 case SDT_INTLIST: {
533 if (!LoadIntList((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
534 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY);
535 msg.SetDParamStr(0, sdb->name);
536 _settings_error_list.push_back(msg);
538 /* Use default */
539 LoadIntList((const char*)sdb->def, ptr, sld->length, GetVarMemType(sld->conv));
540 } else if (sd->desc.proc_cnvt != NULL) {
541 sd->desc.proc_cnvt((const char*)p);
543 break;
545 default: NOT_REACHED();
551 * Save the values of settings to the inifile.
552 * @param ini pointer to IniFile structure
553 * @param sd read-only SettingDesc structure which contains the unmodified,
554 * loaded values of the configuration file and various information about it
555 * @param grpname holds the name of the group (eg. [network]) where these will be saved
556 * @param object pointer to the object been saved
557 * The function works as follows: for each item in the SettingDesc structure we
558 * have a look if the value has changed since we started the game (the original
559 * values are reloaded when saving). If settings indeed have changed, we get
560 * these and save them.
562 static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
564 IniGroup *group_def = NULL;
566 for (; sd->save.type != SL_END; sd++) {
567 const SettingDescBase *sdb = &sd->desc;
568 const SaveLoad *sld = &sd->save;
570 /* If the setting is not saved to the configuration
571 * file, just continue with the next setting */
572 if (!sld->is_currently_valid()) continue;
573 if (sld->flags & SLF_NOT_IN_CONFIG) continue;
575 /* XXX - wtf is this?? (group override?) */
576 const char *s = strchr(sdb->name, '.');
577 IniGroup *group;
578 if (s != NULL) {
579 group = ini->get_group (sdb->name, s - sdb->name);
580 s++;
581 } else {
582 if (group_def == NULL) group_def = ini->get_group (grpname);
583 s = sdb->name;
584 group = group_def;
587 IniItem *item = group->get_item (s);
588 void *ptr = sld->get_variable_address (object);
590 if (item->value != NULL) {
591 /* check if the value is the same as the old value */
592 const void *p = StringToVal(sdb, item->value);
594 /* The main type of a variable/setting is in bytes 8-15
595 * The subtype (what kind of numbers do we have there) is in 0-7 */
596 switch (sdb->cmd) {
597 case SDT_BOOLX:
598 case SDT_NUMX:
599 case SDT_ONEOFMANY:
600 case SDT_MANYOFMANY:
601 assert(sld->type == SL_VAR);
602 switch (GetVarMemType(sld->conv)) {
603 case SLE_VAR_BL:
604 if (*(bool*)ptr == (p != NULL)) continue;
605 break;
607 case SLE_VAR_I8:
608 case SLE_VAR_U8:
609 if (*(byte*)ptr == (byte)(size_t)p) continue;
610 break;
612 case SLE_VAR_I16:
613 case SLE_VAR_U16:
614 if (*(uint16*)ptr == (uint16)(size_t)p) continue;
615 break;
617 case SLE_VAR_I32:
618 case SLE_VAR_U32:
619 if (*(uint32*)ptr == (uint32)(size_t)p) continue;
620 break;
622 default: NOT_REACHED();
624 break;
626 default: break; // Assume the other types are always changed
630 /* Value has changed, get the new value and put it into a buffer */
631 char *new_value;
632 switch (sdb->cmd) {
633 case SDT_BOOLX:
634 case SDT_NUMX:
635 case SDT_ONEOFMANY:
636 case SDT_MANYOFMANY: {
637 uint32 i = (uint32)ReadValue(ptr, sld->conv);
639 switch (sdb->cmd) {
640 case SDT_BOOLX: new_value = xstrdup ((i != 0) ? "true" : "false"); break;
641 case SDT_NUMX: new_value = str_fmt (IsSignedVarMemType(sld->conv) ? "%d" : "%u", i); break;
642 case SDT_ONEOFMANY: new_value = MakeOneOfMany (sdb->many, i); break;
643 case SDT_MANYOFMANY: new_value = MakeManyOfMany (sdb->many, i); break;
644 default: NOT_REACHED();
646 break;
649 case SDT_STRING: {
650 assert (sld->type == SL_STR);
652 const char *s;
654 if (sld->length == 0) {
655 s = *(const char *const *)ptr;
656 } else {
657 s = (const char *)ptr;
660 if (sld->conv & SLS_QUOTED) {
661 if (s == NULL) {
662 new_value = xstrdup ("");
663 } else {
664 new_value = str_fmt ("\"%s\"", s);
666 } else {
667 new_value = xstrdup (s);
669 break;
672 case SDT_INTLIST:
673 new_value = MakeIntList (ptr, sld->length, GetVarMemType(sld->conv));
674 break;
676 default: NOT_REACHED();
679 /* The value is different, that means we have to write it to the ini */
680 free(item->value);
681 item->value = new_value;
686 * Loads all items from a 'grpname' section into a list
687 * The list parameter can be a NULL pointer, in this case nothing will be
688 * saved and a callback function should be defined that will take over the
689 * list-handling and store the data itself somewhere.
690 * @param ini IniFile handle to the ini file with the source data
691 * @param grpname character string identifying the section-header of the ini file that will be parsed
692 * @param list new list with entries of the given section
694 static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *list)
696 const IniGroup *group = ini->get_group (grpname);
698 if (group == NULL || list == NULL) return;
700 list->Clear();
702 for (IniItem::const_iterator item = group->cbegin(); item != group->cend(); item++) {
703 *list->Append() = xstrdup(item->get_name());
708 * Saves all items from a list into the 'grpname' section
709 * The list parameter can be a NULL pointer, in this case a callback function
710 * should be defined that will provide the source data to be saved.
711 * @param ini IniFile handle to the ini file where the destination data is saved
712 * @param grpname character string identifying the section-header of the ini file
713 * @param list pointer to an string(pointer) array that will be used as the
714 * source to be saved into the relevant ini section
716 static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *list)
718 IniGroup *group = ini->get_group (grpname);
720 if (group == NULL || list == NULL) return;
721 group->clear();
723 for (char **iter = list->Begin(); iter != list->End(); iter++) {
724 group->get_item(*iter)->SetValue("");
729 * Load a WindowDesc from config.
730 * @param ini IniFile handle to the ini file with the source data
731 * @param grpname character string identifying the section-header of the ini file that will be parsed
732 * @param desc Destination WindowDesc
734 void IniLoadWindowSettings(IniFile *ini, const char *grpname, void *desc)
736 IniLoadSettings(ini, _window_settings, grpname, desc);
740 * Save a WindowDesc to config.
741 * @param ini IniFile handle to the ini file where the destination data is saved
742 * @param grpname character string identifying the section-header of the ini file
743 * @param desc Source WindowDesc
745 void IniSaveWindowSettings(IniFile *ini, const char *grpname, void *desc)
747 IniSaveSettings(ini, _window_settings, grpname, desc);
751 * Check whether the setting is editable in the current gamemode.
752 * @param do_command true if this is about checking a command from the server.
753 * @return true if editable.
755 bool SettingDesc::IsEditable(bool do_command) const
757 if (!do_command && !(this->save.flags & SLF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->desc.flags & SGF_PER_COMPANY)) return false;
758 if ((this->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
759 if ((this->desc.flags & SGF_NO_NETWORK) && _networking) return false;
760 if ((this->desc.flags & SGF_NEWGAME_ONLY) &&
761 (_game_mode == GM_NORMAL ||
762 (_game_mode == GM_EDITOR && !(this->desc.flags & SGF_SCENEDIT_TOO)))) return false;
763 return true;
767 * Return the type of the setting.
768 * @return type of setting
770 SettingType SettingDesc::GetType() const
772 if (this->desc.flags & SGF_PER_COMPANY) return ST_COMPANY;
773 return (this->save.flags & SLF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
776 /* Begin - Callback Functions for the various settings. */
778 /** Reposition the main toolbar as the setting changed. */
779 static bool v_PositionMainToolbar(int32 p1)
781 if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
782 return true;
785 /** Reposition the statusbar as the setting changed. */
786 static bool v_PositionStatusbar(int32 p1)
788 if (_game_mode != GM_MENU) {
789 PositionStatusbar(NULL);
790 PositionNewsMessage(NULL);
791 PositionNetworkChatWindow(NULL);
793 return true;
796 static bool PopulationInLabelActive(int32 p1)
798 UpdateAllTownVirtCoords();
799 return true;
802 static bool RedrawScreen(int32 p1)
804 MarkWholeScreenDirty();
805 return true;
809 * Redraw the smallmap after a colour scheme change.
810 * @param p1 Callback parameter.
811 * @return Always true.
813 static bool RedrawSmallmap(int32 p1)
815 BuildLandLegend();
816 BuildOwnerLegend();
817 SetWindowClassesDirty(WC_SMALLMAP);
818 return true;
821 static bool InvalidateDetailsWindow(int32 p1)
823 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
824 return true;
827 static bool StationSpreadChanged(int32 p1)
829 InvalidateWindowData(WC_SELECT_STATION, 0);
830 InvalidateWindowData(WC_BUILD_STATION, 0);
831 return true;
834 static bool InvalidateBuildIndustryWindow(int32 p1)
836 InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
837 return true;
840 static bool CloseSignalGUI(int32 p1)
842 if (p1 == 0) {
843 DeleteWindowByClass(WC_BUILD_SIGNAL);
845 return true;
848 static bool InvalidateTownViewWindow(int32 p1)
850 InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
851 return true;
854 static bool DeleteSelectStationWindow(int32 p1)
856 DeleteWindowById(WC_SELECT_STATION, 0);
857 return true;
860 static bool UpdateConsists(int32 p1)
862 Train *t;
863 FOR_ALL_TRAINS(t) {
864 /* Update the consist of all trains so the maximum speed is set correctly. */
865 if (t->IsFrontEngine() || t->IsFreeWagon()) t->ConsistChanged(CCF_TRACK);
867 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
868 return true;
871 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
872 static bool CheckInterval(int32 p1)
874 bool update_vehicles;
875 VehicleDefaultSettings *vds;
876 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
877 vds = &_settings_client.company.vehicle;
878 update_vehicles = false;
879 } else {
880 vds = &Company::Get(_current_company)->settings.vehicle;
881 update_vehicles = true;
884 if (p1 != 0) {
885 vds->servint_trains = 50;
886 vds->servint_roadveh = 50;
887 vds->servint_aircraft = 50;
888 vds->servint_ships = 50;
889 } else {
890 vds->servint_trains = 150;
891 vds->servint_roadveh = 150;
892 vds->servint_aircraft = 100;
893 vds->servint_ships = 360;
896 if (update_vehicles) {
897 const Company *c = Company::Get(_current_company);
898 Vehicle *v;
899 FOR_ALL_VEHICLES(v) {
900 if (v->owner == _current_company && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
901 v->SetServiceInterval(CompanyServiceInterval(c, v->type));
902 v->SetServiceIntervalIsPercent(p1 != 0);
907 InvalidateDetailsWindow(0);
909 return true;
912 static bool UpdateInterval(VehicleType type, int32 p1)
914 bool update_vehicles;
915 VehicleDefaultSettings *vds;
916 if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
917 vds = &_settings_client.company.vehicle;
918 update_vehicles = false;
919 } else {
920 vds = &Company::Get(_current_company)->settings.vehicle;
921 update_vehicles = true;
924 /* Test if the interval is valid */
925 uint16 interval = GetServiceIntervalClamped(p1, vds->servint_ispercent);
926 if (interval != p1) return false;
928 if (update_vehicles) {
929 Vehicle *v;
930 FOR_ALL_VEHICLES(v) {
931 if (v->owner == _current_company && v->type == type && v->IsPrimaryVehicle() && !v->ServiceIntervalIsCustom()) {
932 v->SetServiceInterval(p1);
937 InvalidateDetailsWindow(0);
939 return true;
942 static bool UpdateIntervalTrains(int32 p1)
944 return UpdateInterval(VEH_TRAIN, p1);
947 static bool UpdateIntervalRoadVeh(int32 p1)
949 return UpdateInterval(VEH_ROAD, p1);
952 static bool UpdateIntervalShips(int32 p1)
954 return UpdateInterval(VEH_SHIP, p1);
957 static bool UpdateIntervalAircraft(int32 p1)
959 return UpdateInterval(VEH_AIRCRAFT, p1);
962 static bool TrainAccelerationModelChanged(int32 p1)
964 Train *t;
965 FOR_ALL_TRAINS(t) {
966 if (t->IsFrontEngine()) {
967 t->tcache.cached_max_curve_speed = t->GetCurveSpeedLimit();
968 t->UpdateAcceleration();
972 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
973 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
974 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
975 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
977 return true;
981 * This function updates the train acceleration cache after a steepness change.
982 * @param p1 Callback parameter.
983 * @return Always true.
985 static bool TrainSlopeSteepnessChanged(int32 p1)
987 Train *t;
988 FOR_ALL_TRAINS(t) {
989 if (t->IsFrontEngine()) t->CargoChanged();
992 return true;
996 * This function updates realistic acceleration caches when the setting "Road vehicle acceleration model" is set.
997 * @param p1 Callback parameter
998 * @return Always true
1000 static bool RoadVehAccelerationModelChanged(int32 p1)
1002 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
1003 RoadVehicle *rv;
1004 FOR_ALL_ROADVEHICLES(rv) {
1005 if (rv->IsFrontEngine()) {
1006 rv->CargoChanged();
1011 /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
1012 SetWindowClassesDirty(WC_ENGINE_PREVIEW);
1013 InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
1014 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
1016 return true;
1020 * This function updates the road vehicle acceleration cache after a steepness change.
1021 * @param p1 Callback parameter.
1022 * @return Always true.
1024 static bool RoadVehSlopeSteepnessChanged(int32 p1)
1026 RoadVehicle *rv;
1027 FOR_ALL_ROADVEHICLES(rv) {
1028 if (rv->IsFrontEngine()) rv->CargoChanged();
1031 return true;
1034 static bool DragSignalsDensityChanged(int32)
1036 InvalidateWindowData(WC_BUILD_SIGNAL, 0);
1038 return true;
1041 static bool TownFoundingChanged(int32 p1)
1043 if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
1044 DeleteWindowById(WC_FOUND_TOWN, 0);
1045 return true;
1047 InvalidateWindowData(WC_FOUND_TOWN, 0);
1048 return true;
1051 static bool InvalidateVehTimetableWindow(int32 p1)
1053 InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, VIWD_MODIFY_ORDERS);
1054 return true;
1057 static bool ZoomMinMaxChanged(int32 p1)
1059 extern void ConstrainAllViewportsZoom();
1060 ConstrainAllViewportsZoom();
1061 GfxClearSpriteCache();
1062 if (_settings_client.gui.zoom_min > _gui_zoom) {
1063 /* Restrict GUI zoom if it is no longer available. */
1064 _gui_zoom = _settings_client.gui.zoom_min;
1065 UpdateCursorSize();
1066 LoadStringWidthTable();
1068 return true;
1072 * Update any possible saveload window and delete any newgrf dialogue as
1073 * its widget parts might change. Reinit all windows as it allows access to the
1074 * newgrf debug button.
1075 * @param p1 unused.
1076 * @return Always true.
1078 static bool InvalidateNewGRFChangeWindows(int32 p1)
1080 InvalidateWindowClassesData(WC_SAVELOAD);
1081 DeleteWindowByClass(WC_GAME_OPTIONS);
1082 ReInitAllWindows();
1083 return true;
1086 static bool InvalidateCompanyLiveryWindow(int32 p1)
1088 InvalidateWindowClassesData(WC_COMPANY_COLOUR);
1089 return RedrawScreen(p1);
1092 static bool InvalidateIndustryViewWindow(int32 p1)
1094 InvalidateWindowClassesData(WC_INDUSTRY_VIEW);
1095 return true;
1098 static bool InvalidateAISettingsWindow(int32 p1)
1100 InvalidateWindowClassesData(WC_AI_SETTINGS);
1101 return true;
1105 * Update the town authority window after a town authority setting change.
1106 * @param p1 Unused.
1107 * @return Always true.
1109 static bool RedrawTownAuthority(int32 p1)
1111 SetWindowClassesDirty(WC_TOWN_AUTHORITY);
1112 return true;
1116 * Invalidate the company infrastructure details window after a infrastructure maintenance setting change.
1117 * @param p1 Unused.
1118 * @return Always true.
1120 static bool InvalidateCompanyInfrastructureWindow(int32 p1)
1122 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
1123 return true;
1127 * Invalidate the company details window after the shares setting changed.
1128 * @param p1 Unused.
1129 * @return Always true.
1131 static bool InvalidateCompanyWindow(int32 p1)
1133 InvalidateWindowClassesData(WC_COMPANY);
1134 return true;
1137 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
1138 static void ValidateSettings()
1140 /* Do not allow a custom sea level with the original land generator. */
1141 if (_settings_newgame.game_creation.land_generator == 0 &&
1142 _settings_newgame.difficulty.quantity_sea_lakes == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) {
1143 _settings_newgame.difficulty.quantity_sea_lakes = CUSTOM_SEA_LEVEL_MIN_PERCENTAGE;
1147 static bool DifficultyNoiseChange(int32 i)
1149 if (_game_mode == GM_NORMAL) {
1150 UpdateAirportsNoise();
1151 if (_settings_game.economy.station_noise_level) {
1152 InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
1156 return true;
1159 static bool MaxNoAIsChange(int32 i)
1161 if (GetGameSettings().difficulty.max_no_competitors != 0 &&
1162 AI::GetInfoList()->size() == 0 &&
1163 (!_networking || _network_server)) {
1164 ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
1167 return true;
1171 * Check whether the road side may be changed.
1172 * @param p1 unused
1173 * @return true if the road side may be changed.
1175 static bool CheckRoadSide(int p1)
1177 extern bool RoadVehiclesAreBuilt();
1178 return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
1182 * Conversion callback for _gameopt_settings_game.landscape
1183 * It converts (or try) between old values and the new ones,
1184 * without losing initial setting of the user
1185 * @param value that was read from config file
1186 * @return the "hopefully" converted value
1188 static size_t ConvertLandscape(const char *value)
1190 /* try with the old values */
1191 return LookupOneOfMany("normal|hilly|desert|candy", value);
1194 static bool CheckFreeformEdges(int32 p1)
1196 if (_game_mode == GM_MENU) return true;
1197 if (p1 != 0) {
1198 Ship *s;
1199 FOR_ALL_SHIPS(s) {
1200 /* Check if there is a ship on the northern border. */
1201 if (TileX(s->tile) == 0 || TileY(s->tile) == 0) {
1202 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1203 return false;
1206 BaseStation *st;
1207 FOR_ALL_BASE_STATIONS(st) {
1208 /* Check if there is a non-deleted buoy on the northern border. */
1209 if (st->IsInUse() && (TileX(st->xy) == 0 || TileY(st->xy) == 0)) {
1210 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
1211 return false;
1214 for (uint i = 0; i < MapSizeX(); i++) MakeVoid(TileXY(i, 0));
1215 for (uint i = 0; i < MapSizeY(); i++) MakeVoid(TileXY(0, i));
1216 } else {
1217 for (uint i = 1; i < MapMaxX(); i++) {
1218 if (TileHeight(TileXY(i, 1)) != 0) {
1219 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1220 return false;
1223 for (uint i = 1; i < MapMaxX(); i++) {
1224 if (!IsWaterTile(TileXY(i, MapMaxY() - 1)) || TileHeight(TileXY(i, MapMaxY())) != 0) {
1225 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1226 return false;
1229 for (uint i = 1; i < MapMaxY(); i++) {
1230 if (TileHeight(TileXY(1, i)) != 0) {
1231 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1232 return false;
1235 for (uint i = 1; i < MapMaxY(); i++) {
1236 if (!IsWaterTile(TileXY(MapMaxX() - 1, i)) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
1237 ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
1238 return false;
1241 /* Make tiles at the border water again. */
1242 for (uint i = 0; i < MapMaxX(); i++) {
1243 SetTileHeight(TileXY(i, 0), 0);
1244 MakeSea(TileXY(i, 0));
1246 for (uint i = 0; i < MapMaxY(); i++) {
1247 SetTileHeight(TileXY(0, i), 0);
1248 MakeSea(TileXY(0, i));
1251 MarkWholeScreenDirty();
1252 return true;
1256 * Changing the setting "allow multiple NewGRF sets" is not allowed
1257 * if there are vehicles.
1259 static bool ChangeDynamicEngines(int32 p1)
1261 if (_game_mode == GM_MENU) return true;
1263 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
1264 ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
1265 return false;
1268 return true;
1271 static bool ChangeMaxHeightLevel(int32 p1)
1273 if (_game_mode == GM_NORMAL) return false;
1274 if (_game_mode != GM_EDITOR) return true;
1276 /* Check if at least one mountain on the map is higher than the new value.
1277 * If yes, disallow the change. */
1278 for (TileIndex t = 0; t < MapSize(); t++) {
1279 if ((int32)TileHeight(t) > p1) {
1280 ShowErrorMessage(STR_CONFIG_SETTING_TOO_HIGH_MOUNTAIN, INVALID_STRING_ID, WL_ERROR);
1281 /* Return old, unchanged value */
1282 return false;
1286 /* The smallmap uses an index from heightlevels to colours. Trigger rebuilding it. */
1287 InvalidateWindowClassesData(WC_SMALLMAP, 2);
1289 return true;
1292 static bool StationCatchmentChanged(int32 p1)
1294 Station::RecomputeIndustriesNearForAll();
1295 return true;
1298 static bool MaxVehiclesChanged(int32 p1)
1300 InvalidateWindowClassesData(WC_BUILD_TOOLBAR);
1301 MarkWholeScreenDirty();
1302 return true;
1306 #ifdef ENABLE_NETWORK
1308 static bool UpdateClientName(int32 p1)
1310 NetworkUpdateClientName();
1311 return true;
1314 static bool UpdateServerPassword(int32 p1)
1316 if (strcmp(_settings_client.network.server_password, "*") == 0) {
1317 _settings_client.network.server_password[0] = '\0';
1320 return true;
1323 static bool UpdateRconPassword(int32 p1)
1325 if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
1326 _settings_client.network.rcon_password[0] = '\0';
1329 return true;
1332 static bool UpdateClientConfigValues(int32 p1)
1334 if (_network_server) NetworkServerSendConfigUpdate();
1336 return true;
1339 #endif /* ENABLE_NETWORK */
1342 /* End - Callback Functions */
1345 * Prepare for reading and old diff_custom by zero-ing the memory.
1347 static void PrepareOldDiffCustom()
1349 memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
1353 * Reading of the old diff_custom array and transforming it to the new format.
1354 * @param stv Savegame type and version; or NULL if reading from config.
1355 * In the former case we are sure there is an array;
1356 * in the latter case we have to check that.
1358 static void HandleOldDiffCustom(const SavegameTypeVersion *stv)
1360 uint options_to_load = GAME_DIFFICULTY_NUM - ((stv != NULL && stv->is_ottd_before (4)) ? 1 : 0);
1362 if (stv == NULL) {
1363 /* If we did read to old_diff_custom, then at least one value must be non 0. */
1364 bool old_diff_custom_used = false;
1365 for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
1366 old_diff_custom_used = (_old_diff_custom[i] != 0);
1369 if (!old_diff_custom_used) return;
1372 for (uint i = 0; i < options_to_load; i++) {
1373 const SettingDesc *sd = &_settings[i];
1374 /* Skip deprecated options */
1375 if (!sd->save.is_currently_valid()) continue;
1376 void *var = sd->save.get_variable_address (stv != NULL ? &_settings_game : &_settings_newgame);
1377 Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
1381 static void AILoadConfig(IniFile *ini, const char *grpname)
1383 const IniGroup *group = ini->get_group (grpname);
1385 /* Clean any configured AI */
1386 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1387 AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME)->Change(NULL);
1390 /* If no group exists, return */
1391 if (group == NULL) return;
1393 CompanyID c = COMPANY_FIRST;
1394 for (IniItem::const_iterator item = group->cbegin(); c < MAX_COMPANIES && item != group->cend(); c++, item++) {
1395 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1397 config->Change(item->get_name());
1398 if (!config->HasScript()) {
1399 if (!item->is_name("none")) {
1400 DEBUG(script, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->get_name());
1401 continue;
1404 if (item->value != NULL) config->StringToSettings(item->value);
1408 static void GameLoadConfig(IniFile *ini, const char *grpname)
1410 const IniGroup *group = ini->get_group (grpname);
1412 /* Clean any configured GameScript */
1413 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME)->Change(NULL);
1415 /* If no group exists, return */
1416 if (group == NULL) return;
1418 IniItem::const_iterator item = group->cbegin();
1419 if (item == group->cend()) return;
1421 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1423 config->Change(item->get_name());
1424 if (!config->HasScript()) {
1425 if (!item->is_name("none")) {
1426 DEBUG(script, 0, "The GameScript by the name '%s' was no longer found, and removed from the list.", item->get_name());
1427 return;
1430 if (item->value != NULL) config->StringToSettings(item->value);
1434 * Convert a character to a hex nibble value, or \c -1 otherwise.
1435 * @param c Character to convert.
1436 * @return Hex value of the character, or \c -1 if not a hex digit.
1438 static int DecodeHexNibble(char c)
1440 if (c >= '0' && c <= '9') return c - '0';
1441 if (c >= 'A' && c <= 'F') return c + 10 - 'A';
1442 if (c >= 'a' && c <= 'f') return c + 10 - 'a';
1443 return -1;
1447 * Parse a sequence of characters (supposedly hex digits) into a sequence of bytes.
1448 * After the hex number should be a \c '|' character.
1449 * @param pos First character to convert.
1450 * @param dest [out] Output byte array to write the bytes.
1451 * @param dest_size Number of bytes in \a dest.
1452 * @return Whether reading was successful.
1454 static bool DecodeHexText(const char *pos, uint8 *dest, size_t dest_size)
1456 while (dest_size > 0) {
1457 int hi = DecodeHexNibble(pos[0]);
1458 if (hi < 0) return false;
1459 int lo = DecodeHexNibble(pos[1]);
1460 if (lo < 0) return false;
1461 *dest++ = (hi << 4) | lo;
1462 pos += 2;
1463 dest_size--;
1465 return *pos == '|';
1469 * Load a GRF configuration
1470 * @param ini The configuration to read from.
1471 * @param grpname Group name containing the configuration of the GRF.
1472 * @param is_static GRF is static.
1474 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
1476 const IniGroup *group = ini->get_group (grpname);
1477 GRFConfig *first = NULL;
1478 GRFConfig **curr = &first;
1480 if (group == NULL) return NULL;
1482 for (IniItem::const_iterator item = group->cbegin(); item != group->cend(); item++) {
1483 GRFConfig *c = NULL;
1485 uint8 grfid_buf[4], md5sum[16];
1486 const char *filename = item->get_name();
1488 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1489 if (DecodeHexText(filename, grfid_buf, lengthof(grfid_buf))) {
1490 filename += 1 + 2 * lengthof(grfid_buf);
1491 uint32 grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
1493 if (DecodeHexText(filename, md5sum, lengthof(md5sum))) {
1494 filename += 1 + 2 * lengthof(md5sum);
1495 const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, md5sum);
1496 if (s != NULL) c = new GRFConfig(*s);
1498 if (c == NULL && !FioCheckFileExists(filename, NEWGRF_DIR)) {
1499 const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
1500 if (s != NULL) c = new GRFConfig(*s);
1503 if (c == NULL) c = new GRFConfig(filename);
1505 /* Parse parameters */
1506 if (!StrEmpty(item->value)) {
1507 int count = ParseIntList(item->value, (int*)c->param, lengthof(c->param));
1508 if (count < 0) {
1509 SetDParamStr(0, filename);
1510 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
1511 count = 0;
1513 c->num_params = count;
1516 /* Check if item is valid */
1517 if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
1518 if (c->status == GCS_NOT_FOUND) {
1519 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND);
1520 } else if (HasBit(c->flags, GCF_UNSAFE)) {
1521 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE);
1522 } else if (HasBit(c->flags, GCF_SYSTEM)) {
1523 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM);
1524 } else if (HasBit(c->flags, GCF_INVALID)) {
1525 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE);
1526 } else {
1527 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN);
1530 SetDParamStr(0, StrEmpty(filename) ? item->get_name() : filename);
1531 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_GRF, WL_CRITICAL);
1532 delete c;
1533 continue;
1536 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1537 bool duplicate = false;
1538 for (const GRFConfig *gc = first; gc != NULL; gc = gc->next) {
1539 if (gc->ident.grfid == c->ident.grfid) {
1540 SetDParamStr(0, c->filename);
1541 SetDParamStr(1, gc->filename);
1542 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_DUPLICATE_GRFID, WL_CRITICAL);
1543 duplicate = true;
1544 break;
1547 if (duplicate) {
1548 delete c;
1549 continue;
1552 /* Mark file as static to avoid saving in savegame. */
1553 if (is_static) SetBit(c->flags, GCF_STATIC);
1555 /* Add item to list */
1556 *curr = c;
1557 curr = &c->next;
1560 return first;
1563 static void AISaveConfig(IniFile *ini, const char *grpname)
1565 IniGroup *group = ini->get_group (grpname);
1567 if (group == NULL) return;
1568 group->clear();
1570 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1571 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1572 const char *name;
1573 char value[1024];
1574 config->SettingsToString(value, lengthof(value));
1576 if (config->HasScript()) {
1577 name = config->GetName();
1578 } else {
1579 name = "none";
1582 IniItem *item = group->append (name);
1583 item->SetValue(value);
1587 static void GameSaveConfig(IniFile *ini, const char *grpname)
1589 IniGroup *group = ini->get_group (grpname);
1591 if (group == NULL) return;
1592 group->clear();
1594 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1595 const char *name;
1596 char value[1024];
1597 config->SettingsToString(value, lengthof(value));
1599 if (config->HasScript()) {
1600 name = config->GetName();
1601 } else {
1602 name = "none";
1605 IniItem *item = group->append (name);
1606 item->SetValue(value);
1610 * Save the version of OpenTTD to the ini file.
1611 * @param ini the ini to write to
1613 static void SaveVersionInConfig(IniFile *ini)
1615 IniGroup *group = ini->get_group ("version");
1617 char version[9];
1618 bstrfmt (version, "%08X", _openttd_newgrf_version);
1620 const char * const versions[][2] = {
1621 { "version_string", _openttd_revision },
1622 { "version_number", version }
1625 for (uint i = 0; i < lengthof(versions); i++) {
1626 group->get_item(versions[i][0])->SetValue(versions[i][1]);
1630 /* Save a GRF configuration to the given group name */
1631 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
1633 ini->remove (grpname);
1634 IniGroup *group = ini->get_group (grpname);
1635 const GRFConfig *c;
1637 for (c = list; c != NULL; c = c->next) {
1638 /* Hex grfid (4 bytes in nibbles), "|", hex md5sum (16 bytes in nibbles), "|", file system path. */
1639 sstring<4 * 2 + 1 + 16 * 2 + 1 + MAX_PATH> key;
1640 key.fmt ("%08X|", BSWAP32(c->ident.grfid));
1641 key.append_md5sum (c->ident.md5sum);
1642 key.append_fmt ("|%s", c->filename);
1644 sstring<512> params;
1645 GRFBuildParamList (&params, c);
1646 group->get_item(key.c_str())->SetValue(params.c_str());
1650 /* Common handler for saving/loading variables to the configuration file */
1651 static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool basic_settings = true, bool other_settings = true)
1653 if (basic_settings) {
1654 proc(ini, (const SettingDesc*)_misc_settings, "misc", NULL);
1655 #if defined(WIN32) && !defined(DEDICATED)
1656 proc(ini, (const SettingDesc*)_win32_settings, "win32", NULL);
1657 #endif /* WIN32 */
1660 if (other_settings) {
1661 proc(ini, _settings, "patches", &_settings_newgame);
1662 proc(ini, _currency_settings,"currency", &_custom_currency);
1663 proc(ini, _company_settings, "company", &_settings_client.company);
1665 #ifdef ENABLE_NETWORK
1666 proc_list(ini, "server_bind_addresses", &_network_bind_list);
1667 proc_list(ini, "servers", &_network_host_list);
1668 proc_list(ini, "bans", &_network_ban_list);
1669 #endif /* ENABLE_NETWORK */
1673 static IniFile *IniLoadConfig()
1675 IniFile *ini = new IniFile(_list_group_names);
1676 ini->LoadFromDisk(_config_file, BASE_DIR);
1677 return ini;
1681 * Load the values from the configuration files
1682 * @param minimal Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1684 void LoadFromConfig(bool minimal)
1686 IniFile *ini = IniLoadConfig();
1687 if (!minimal) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1689 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1690 HandleSettingDescs(ini, IniLoadSettings, IniLoadSettingList, minimal, !minimal);
1692 if (!minimal) {
1693 _grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
1694 _grfconfig_static = GRFLoadConfig(ini, "newgrf-static", true);
1695 AILoadConfig(ini, "ai_players");
1696 GameLoadConfig(ini, "game_scripts");
1698 PrepareOldDiffCustom();
1699 IniLoadSettings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
1700 HandleOldDiffCustom(NULL);
1702 ValidateSettings();
1704 /* Display sheduled errors */
1705 extern void ScheduleErrorMessage(ErrorList &datas);
1706 ScheduleErrorMessage(_settings_error_list);
1707 if (FindWindowById(WC_ERRMSG, 0) == NULL) ShowFirstError();
1710 delete ini;
1713 /** Save the values to the configuration file */
1714 void SaveToConfig()
1716 IniFile *ini = IniLoadConfig();
1718 /* Remove some obsolete groups. These have all been loaded into other groups. */
1719 ini->remove ("patches");
1720 ini->remove ("yapf");
1721 ini->remove ("gameopt");
1723 HandleSettingDescs(ini, IniSaveSettings, IniSaveSettingList);
1724 GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
1725 GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
1726 AISaveConfig(ini, "ai_players");
1727 GameSaveConfig(ini, "game_scripts");
1728 SaveVersionInConfig(ini);
1729 ini->SaveToDisk(_config_file);
1730 delete ini;
1734 * Get the list of known NewGrf presets.
1735 * @param list[inout] Pointer to list for storing the preset names.
1737 void GetGRFPresetList(GRFPresetList *list)
1739 list->Clear();
1741 IniFile *ini = IniLoadConfig();
1742 for (IniGroup::const_iterator group = ini->cbegin(); group != ini->cend(); group++) {
1743 if (strncmp(group->get_name(), "preset-", 7) == 0) {
1744 *list->Append() = xstrdup(group->get_name() + 7);
1748 delete ini;
1752 * Load a NewGRF configuration by preset-name.
1753 * @param config_name Name of the preset.
1754 * @return NewGRF configuration.
1755 * @see GetGRFPresetList
1757 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1759 char *section = (char*)alloca(strlen(config_name) + 8);
1760 sprintf(section, "preset-%s", config_name);
1762 IniFile *ini = IniLoadConfig();
1763 GRFConfig *config = GRFLoadConfig(ini, section, false);
1764 delete ini;
1766 return config;
1770 * Save a NewGRF configuration with a preset name.
1771 * @param config_name Name of the preset.
1772 * @param config NewGRF configuration to save.
1773 * @see GetGRFPresetList
1775 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1777 char *section = (char*)alloca(strlen(config_name) + 8);
1778 sprintf(section, "preset-%s", config_name);
1780 IniFile *ini = IniLoadConfig();
1781 GRFSaveConfig(ini, section, config);
1782 ini->SaveToDisk(_config_file);
1783 delete ini;
1787 * Delete a NewGRF configuration by preset name.
1788 * @param config_name Name of the preset.
1790 void DeleteGRFPresetFromConfig(const char *config_name)
1792 char *section = (char*)alloca(strlen(config_name) + 8);
1793 sprintf(section, "preset-%s", config_name);
1795 IniFile *ini = IniLoadConfig();
1796 ini->remove (section);
1797 ini->SaveToDisk(_config_file);
1798 delete ini;
1801 const SettingDesc *GetSettingDescription(uint index)
1803 if (index >= lengthof(_settings)) return NULL;
1804 return &_settings[index];
1808 * Network-safe changing of settings (server-only).
1809 * @param tile unused
1810 * @param flags operation to perform
1811 * @param p1 the index of the setting in the SettingDesc array which identifies it
1812 * @param p2 the new value for the setting
1813 * The new value is properly clamped to its minimum/maximum when setting
1814 * @param text unused
1815 * @return the cost of this operation or an error
1816 * @see _settings
1818 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1820 const SettingDesc *sd = GetSettingDescription(p1);
1822 if (sd == NULL) return CMD_ERROR;
1823 if (!sd->save.is_currently_valid()) return CMD_ERROR;
1825 if (!sd->IsEditable(true)) return CMD_ERROR;
1827 if (flags & DC_EXEC) {
1828 void *var = sd->save.get_variable_address (&GetGameSettings());
1830 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1831 int32 newval = (int32)p2;
1833 Write_ValidateSetting(var, sd, newval);
1834 newval = (int32)ReadValue(var, sd->save.conv);
1836 if (oldval == newval) return CommandCost();
1838 if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1839 WriteValue(var, sd->save.conv, (int64)oldval);
1840 return CommandCost();
1843 if (sd->desc.flags & SGF_NO_NETWORK) {
1844 GamelogSetting(sd->desc.name, oldval, newval);
1847 SetWindowClassesDirty(WC_GAME_OPTIONS);
1850 return CommandCost();
1854 * Change one of the per-company settings.
1855 * @param tile unused
1856 * @param flags operation to perform
1857 * @param p1 the index of the setting in the _company_settings 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
1863 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1865 if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
1866 const SettingDesc *sd = &_company_settings[p1];
1868 if (flags & DC_EXEC) {
1869 void *var = sd->save.get_variable_address (&Company::Get(_current_company)->settings);
1871 int32 oldval = (int32)ReadValue(var, sd->save.conv);
1872 int32 newval = (int32)p2;
1874 Write_ValidateSetting(var, sd, newval);
1875 newval = (int32)ReadValue(var, sd->save.conv);
1877 if (oldval == newval) return CommandCost();
1879 if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
1880 WriteValue(var, sd->save.conv, (int64)oldval);
1881 return CommandCost();
1884 SetWindowClassesDirty(WC_GAME_OPTIONS);
1887 return CommandCost();
1891 * Top function to save the new value of an element of the Settings struct
1892 * @param index offset in the SettingDesc array of the Settings struct which
1893 * identifies the setting member we want to change
1894 * @param value new value of the setting
1895 * @param force_newgame force the newgame settings
1897 bool SetSettingValue(uint index, int32 value, bool force_newgame)
1899 const SettingDesc *sd = &_settings[index];
1900 /* If an item is company-based, we do not send it over the network
1901 * (if any) to change. Also *hack*hack* we update the _newgame version
1902 * of settings because changing a company-based setting in a game also
1903 * changes its defaults. At least that is the convention we have chosen */
1904 if (sd->save.flags & SLF_NO_NETWORK_SYNC) {
1905 void *var = sd->save.get_variable_address (&GetGameSettings());
1906 Write_ValidateSetting(var, sd, value);
1908 if (_game_mode != GM_MENU) {
1909 void *var2 = sd->save.get_variable_address (&_settings_newgame);
1910 Write_ValidateSetting(var2, sd, value);
1912 if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1914 SetWindowClassesDirty(WC_GAME_OPTIONS);
1916 return true;
1919 if (force_newgame) {
1920 void *var2 = sd->save.get_variable_address (&_settings_newgame);
1921 Write_ValidateSetting(var2, sd, value);
1922 return true;
1925 /* send non-company-based settings over the network */
1926 if (!_networking || (_networking && _network_server)) {
1927 return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
1929 return false;
1933 * Top function to save the new value of an element of the Settings struct
1934 * @param index offset in the SettingDesc array of the CompanySettings struct
1935 * which identifies the setting member we want to change
1936 * @param value new value of the setting
1938 void SetCompanySetting(uint index, int32 value)
1940 const SettingDesc *sd = &_company_settings[index];
1941 if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
1942 DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
1943 } else {
1944 void *var = sd->save.get_variable_address (&_settings_client.company);
1945 Write_ValidateSetting(var, sd, value);
1946 if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
1951 * Set the company settings for a new company to their default values.
1953 void SetDefaultCompanySettings(CompanyID cid)
1955 Company *c = Company::Get(cid);
1956 const SettingDesc *sd;
1957 for (sd = _company_settings; sd->save.type != SL_END; sd++) {
1958 void *var = sd->save.get_variable_address (&c->settings);
1959 Write_ValidateSetting(var, sd, (int32)(size_t)sd->desc.def);
1963 #if defined(ENABLE_NETWORK)
1965 * Sync all company settings in a multiplayer game.
1967 void SyncCompanySettings()
1969 const SettingDesc *sd;
1970 uint i = 0;
1971 for (sd = _company_settings; sd->save.type != SL_END; sd++, i++) {
1972 const void *old_var = sd->save.get_variable_address (&Company::Get(_current_company)->settings);
1973 const void *new_var = sd->save.get_variable_address (&_settings_client.company);
1974 uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
1975 uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
1976 if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, NULL, _local_company);
1979 #endif /* ENABLE_NETWORK */
1982 * Get the index in the _company_settings array of a setting
1983 * @param name The name of the setting
1984 * @return The index in the _company_settings array
1986 uint GetCompanySettingIndex(const char *name)
1988 uint i;
1989 const SettingDesc *sd = GetSettingFromName(name, &i);
1990 assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
1991 return i;
1995 * Set a setting value with a string.
1996 * @param index the settings index.
1997 * @param value the value to write
1998 * @param force_newgame force the newgame settings
1999 * @note Strings WILL NOT be synced over the network
2001 bool SetSettingValue(uint index, const char *value, bool force_newgame)
2003 const SettingDesc *sd = &_settings[index];
2004 assert(sd->save.flags & SLF_NO_NETWORK_SYNC);
2005 assert(sd->save.type == SL_STR);
2007 if (sd->save.length == 0) {
2008 char **var = (char**) sd->save.get_variable_address ((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game);
2009 free(*var);
2010 *var = strcmp(value, "(null)") == 0 ? NULL : xstrdup(value);
2011 } else {
2012 char *var = (char*) sd->save.get_variable_address();
2013 ttd_strlcpy(var, value, sd->save.length);
2015 if (sd->desc.proc != NULL) sd->desc.proc(0);
2017 return true;
2021 * Given a name of setting, return a setting description of it.
2022 * @param name Name of the setting to return a setting description of
2023 * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful.
2024 * @return Pointer to the setting description of setting \a name if it can be found,
2025 * \c NULL indicates failure to obtain the description
2027 const SettingDesc *GetSettingFromName(const char *name, uint *i)
2029 const SettingDesc *sd;
2031 /* First check all full names */
2032 for (*i = 0, sd = _settings; sd->save.type != SL_END; sd++, (*i)++) {
2033 if (!sd->save.is_currently_valid()) continue;
2034 if (strcmp(sd->desc.name, name) == 0) return sd;
2037 /* Then check the shortcut variant of the name. */
2038 for (*i = 0, sd = _settings; sd->save.type != SL_END; sd++, (*i)++) {
2039 if (!sd->save.is_currently_valid()) continue;
2040 const char *short_name = strchr(sd->desc.name, '.');
2041 if (short_name != NULL) {
2042 short_name++;
2043 if (strcmp(short_name, name) == 0) return sd;
2047 if (strncmp(name, "company.", 8) == 0) name += 8;
2048 /* And finally the company-based settings */
2049 for (*i = 0, sd = _company_settings; sd->save.type != SL_END; sd++, (*i)++) {
2050 if (!sd->save.is_currently_valid()) continue;
2051 if (strcmp(sd->desc.name, name) == 0) return sd;
2054 return NULL;
2057 /* Those 2 functions need to be here, else we have to make some stuff non-static
2058 * and besides, it is also better to keep stuff like this at the same place */
2059 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
2061 uint index;
2062 const SettingDesc *sd = GetSettingFromName(name, &index);
2064 if (sd == NULL) {
2065 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2066 return;
2069 bool success;
2070 if (sd->desc.cmd == SDT_STRING) {
2071 success = SetSettingValue(index, value, force_newgame);
2072 } else {
2073 uint32 val;
2074 extern bool GetArgumentInteger(uint32 *value, const char *arg);
2075 success = GetArgumentInteger(&val, value);
2076 if (!success) {
2077 IConsolePrintF(CC_ERROR, "'%s' is not an integer.", value);
2078 return;
2081 success = SetSettingValue(index, val, force_newgame);
2084 if (!success) {
2085 if (_network_server) {
2086 IConsoleError("This command/variable is not available during network games.");
2087 } else {
2088 IConsoleError("This command/variable is only available to a network server.");
2093 void IConsoleSetSetting(const char *name, int value)
2095 uint index;
2096 const SettingDesc *sd = GetSettingFromName(name, &index);
2097 assert(sd != NULL);
2098 SetSettingValue(index, value);
2102 * Output value of a specific setting to the console
2103 * @param name Name of the setting to output its value
2104 * @param force_newgame force the newgame settings
2106 void IConsoleGetSetting(const char *name, bool force_newgame)
2108 char value[20];
2109 uint index;
2110 const SettingDesc *sd = GetSettingFromName(name, &index);
2111 const void *ptr;
2113 if (sd == NULL) {
2114 IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
2115 return;
2118 ptr = sd->save.get_variable_address ((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game);
2120 if (sd->desc.cmd == SDT_STRING) {
2121 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (sd->save.length == 0) ? *(const char * const *)ptr : (const char *)ptr);
2122 } else {
2123 if (sd->desc.cmd == SDT_BOOLX) {
2124 bstrfmt (value, (*(const bool*)ptr != 0) ? "on" : "off");
2125 } else {
2126 bstrfmt (value, sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2129 IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
2130 name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
2135 * List all settings and their value to the console
2137 * @param prefilter If not \c NULL, only list settings with names that begin with \a prefilter prefix
2139 void IConsoleListSettings(const char *prefilter)
2141 IConsolePrintF(CC_WARNING, "All settings with their current value:");
2143 for (const SettingDesc *sd = _settings; sd->save.type != SL_END; sd++) {
2144 if (!sd->save.is_currently_valid()) continue;
2145 if (prefilter != NULL && strstr(sd->desc.name, prefilter) == NULL) continue;
2146 char value[80];
2147 const void *ptr = sd->save.get_variable_address (&GetGameSettings());
2149 if (sd->desc.cmd == SDT_BOOLX) {
2150 bstrfmt (value, (*(const bool *)ptr != 0) ? "on" : "off");
2151 } else if (sd->desc.cmd == SDT_STRING) {
2152 bstrfmt (value, "%s", (sd->save.length == 0) ? *(const char * const *)ptr : (const char *)ptr);
2153 } else {
2154 bstrfmt (value, sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
2156 IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
2159 IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
2163 * Save and load handler for settings
2164 * @param osd SettingDesc struct containing all information
2165 * @param object can be either NULL in which case we load global variables or
2166 * a pointer to a struct which is getting saved
2168 static void LoadSettings(LoadBuffer *reader, const SettingDesc *osd, void *object)
2170 for (; osd->save.type != SL_END; osd++) {
2171 const SaveLoad *sld = &osd->save;
2172 if (!reader->ReadObjectMember(object, sld)) continue;
2174 void *ptr = sld->get_variable_address (object);
2175 if ((sld->type == SL_VAR) && IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
2180 * Save and load handler for settings
2181 * @param sd SettingDesc struct containing all information
2182 * @param object can be either NULL in which case we load global variables or
2183 * a pointer to a struct which is getting saved
2185 static void SaveSettings(SaveDumper *dumper, const SettingDesc *sd, void *object)
2187 SaveDumper temp(1024);
2189 for (const SettingDesc *i = sd; i->save.type != SL_END; i++) {
2190 temp.WriteObjectMember(object, &i->save);
2193 dumper->WriteRIFFSize(temp.GetSize());
2194 temp.Dump(dumper);
2197 static void Load_OPTS(LoadBuffer *reader)
2199 /* Copy over default setting since some might not get loaded in
2200 * a networking environment. This ensures for example that the local
2201 * autosave-frequency stays when joining a network-server */
2202 PrepareOldDiffCustom();
2203 LoadSettings(reader, _gameopt_settings, &_settings_game);
2204 HandleOldDiffCustom(reader->stv);
2207 static void Load_PATS(LoadBuffer *reader)
2209 /* Copy over default setting since some might not get loaded in
2210 * a networking environment. This ensures for example that the local
2211 * currency setting stays when joining a network-server */
2212 LoadSettings(reader, _settings, &_settings_game);
2215 static void Check_PATS(LoadBuffer *reader)
2217 LoadSettings(reader, _settings, &_load_check_data.settings);
2220 static void Save_PATS(SaveDumper *dumper)
2222 SaveSettings(dumper, _settings, &_settings_game);
2225 void CheckConfig()
2228 * Increase old default values for pf_maxdepth and pf_maxlength
2229 * to support big networks.
2231 if (_settings_newgame.pf.opf.pf_maxdepth == 16 && _settings_newgame.pf.opf.pf_maxlength == 512) {
2232 _settings_newgame.pf.opf.pf_maxdepth = 48;
2233 _settings_newgame.pf.opf.pf_maxlength = 4096;
2237 extern const ChunkHandler _setting_chunk_handlers[] = {
2238 { 'OPTS', NULL, Load_OPTS, NULL, NULL, CH_RIFF},
2239 { 'PATS', Save_PATS, Load_PATS, NULL, Check_PATS, CH_RIFF | CH_LAST},
2242 static bool IsSignedVarMemType(VarType vt)
2244 switch (GetVarMemType(vt)) {
2245 case SLE_VAR_I8:
2246 case SLE_VAR_I16:
2247 case SLE_VAR_I32:
2248 case SLE_VAR_I64:
2249 return true;
2251 return false;