settings.cpp

Go to the documentation of this file.
00001 /* $Id: settings.cpp 23259 2011-11-18 21:19:18Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00026 #include "stdafx.h"
00027 #include "currency.h"
00028 #include "screenshot.h"
00029 #include "network/network.h"
00030 #include "network/network_func.h"
00031 #include "settings_internal.h"
00032 #include "command_func.h"
00033 #include "console_func.h"
00034 #include "pathfinder/pathfinder_type.h"
00035 #include "genworld.h"
00036 #include "train.h"
00037 #include "news_func.h"
00038 #include "window_func.h"
00039 #include "sound_func.h"
00040 #include "company_func.h"
00041 #include "rev.h"
00042 #ifdef WITH_FREETYPE
00043 #include "fontcache.h"
00044 #endif
00045 #include "textbuf_gui.h"
00046 #include "rail_gui.h"
00047 #include "elrail_func.h"
00048 #include "gui.h"
00049 #include "town.h"
00050 #include "video/video_driver.hpp"
00051 #include "sound/sound_driver.hpp"
00052 #include "music/music_driver.hpp"
00053 #include "blitter/factory.hpp"
00054 #include "base_media_base.h"
00055 #include "gamelog.h"
00056 #include "settings_func.h"
00057 #include "ini_type.h"
00058 #include "ai/ai_config.hpp"
00059 #include "ai/ai.hpp"
00060 #include "ship.h"
00061 #include "smallmap_gui.h"
00062 #include "roadveh.h"
00063 #include "fios.h"
00064 
00065 #include "void_map.h"
00066 #include "station_base.h"
00067 
00068 #include "table/strings.h"
00069 #include "table/settings.h"
00070 
00071 ClientSettings _settings_client;
00072 GameSettings _settings_game;     
00073 GameSettings _settings_newgame;  
00074 VehicleDefaultSettings _old_vds; 
00075 char *_config_file; 
00076 
00077 typedef void SettingDescProc(IniFile *ini, const SettingDesc *desc, const char *grpname, void *object);
00078 typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList *list);
00079 
00080 static bool IsSignedVarMemType(VarType vt);
00081 
00085 static const char * const _list_group_names[] = {
00086   "bans",
00087   "newgrf",
00088   "servers",
00089   "server_bind_addresses",
00090   NULL
00091 };
00092 
00100 static size_t LookupOneOfMany(const char *many, const char *one, size_t onelen = 0)
00101 {
00102   const char *s;
00103   size_t idx;
00104 
00105   if (onelen == 0) onelen = strlen(one);
00106 
00107   /* check if it's an integer */
00108   if (*one >= '0' && *one <= '9') return strtoul(one, NULL, 0);
00109 
00110   idx = 0;
00111   for (;;) {
00112     /* find end of item */
00113     s = many;
00114     while (*s != '|' && *s != 0) s++;
00115     if ((size_t)(s - many) == onelen && !memcmp(one, many, onelen)) return idx;
00116     if (*s == 0) return (size_t)-1;
00117     many = s + 1;
00118     idx++;
00119   }
00120 }
00121 
00129 static size_t LookupManyOfMany(const char *many, const char *str)
00130 {
00131   const char *s;
00132   size_t r;
00133   size_t res = 0;
00134 
00135   for (;;) {
00136     /* skip "whitespace" */
00137     while (*str == ' ' || *str == '\t' || *str == '|') str++;
00138     if (*str == 0) break;
00139 
00140     s = str;
00141     while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
00142 
00143     r = LookupOneOfMany(many, str, s - str);
00144     if (r == (size_t)-1) return r;
00145 
00146     SetBit(res, (uint8)r); // value found, set it
00147     if (*s == 0) break;
00148     str = s + 1;
00149   }
00150   return res;
00151 }
00152 
00161 static int ParseIntList(const char *p, int *items, int maxitems)
00162 {
00163   int n = 0; // number of items read so far
00164   bool comma = false; // do we accept comma?
00165 
00166   while (*p != '\0') {
00167     switch (*p) {
00168       case ',':
00169         /* Do not accept multiple commas between numbers */
00170         if (!comma) return -1;
00171         comma = false;
00172         /* FALL THROUGH */
00173       case ' ':
00174         p++;
00175         break;
00176 
00177       default: {
00178         if (n == maxitems) return -1; // we don't accept that many numbers
00179         char *end;
00180         long v = strtol(p, &end, 0);
00181         if (p == end) return -1; // invalid character (not a number)
00182         if (sizeof(int) < sizeof(long)) v = ClampToI32(v);
00183         items[n++] = v;
00184         p = end; // first non-number
00185         comma = true; // we accept comma now
00186         break;
00187       }
00188     }
00189   }
00190 
00191   /* If we have read comma but no number after it, fail.
00192    * We have read comma when (n != 0) and comma is not allowed */
00193   if (n != 0 && !comma) return -1;
00194 
00195   return n;
00196 }
00197 
00206 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
00207 {
00208   int items[64];
00209   int i, nitems;
00210 
00211   if (str == NULL) {
00212     memset(items, 0, sizeof(items));
00213     nitems = nelems;
00214   } else {
00215     nitems = ParseIntList(str, items, lengthof(items));
00216     if (nitems != nelems) return false;
00217   }
00218 
00219   switch (type) {
00220   case SLE_VAR_BL:
00221   case SLE_VAR_I8:
00222   case SLE_VAR_U8:
00223     for (i = 0; i != nitems; i++) ((byte*)array)[i] = items[i];
00224     break;
00225   case SLE_VAR_I16:
00226   case SLE_VAR_U16:
00227     for (i = 0; i != nitems; i++) ((uint16*)array)[i] = items[i];
00228     break;
00229   case SLE_VAR_I32:
00230   case SLE_VAR_U32:
00231     for (i = 0; i != nitems; i++) ((uint32*)array)[i] = items[i];
00232     break;
00233   default: NOT_REACHED();
00234   }
00235 
00236   return true;
00237 }
00238 
00248 static void MakeIntList(char *buf, const char *last, const void *array, int nelems, VarType type)
00249 {
00250   int i, v = 0;
00251   byte *p = (byte*)array;
00252 
00253   for (i = 0; i != nelems; i++) {
00254     switch (type) {
00255     case SLE_VAR_BL:
00256     case SLE_VAR_I8:  v = *(int8*)p;   p += 1; break;
00257     case SLE_VAR_U8:  v = *(byte*)p;   p += 1; break;
00258     case SLE_VAR_I16: v = *(int16*)p;  p += 2; break;
00259     case SLE_VAR_U16: v = *(uint16*)p; p += 2; break;
00260     case SLE_VAR_I32: v = *(int32*)p;  p += 4; break;
00261     case SLE_VAR_U32: v = *(uint32*)p; p += 4; break;
00262     default: NOT_REACHED();
00263     }
00264     buf += seprintf(buf, last, (i == 0) ? "%d" : ",%d", v);
00265   }
00266 }
00267 
00275 static void MakeOneOfMany(char *buf, const char *last, const char *many, int id)
00276 {
00277   int orig_id = id;
00278 
00279   /* Look for the id'th element */
00280   while (--id >= 0) {
00281     for (; *many != '|'; many++) {
00282       if (*many == '\0') { // not found
00283         seprintf(buf, last, "%d", orig_id);
00284         return;
00285       }
00286     }
00287     many++; // pass the |-character
00288   }
00289 
00290   /* copy string until next item (|) or the end of the list if this is the last one */
00291   while (*many != '\0' && *many != '|' && buf < last) *buf++ = *many++;
00292   *buf = '\0';
00293 }
00294 
00303 static void MakeManyOfMany(char *buf, const char *last, const char *many, uint32 x)
00304 {
00305   const char *start;
00306   int i = 0;
00307   bool init = true;
00308 
00309   for (; x != 0; x >>= 1, i++) {
00310     start = many;
00311     while (*many != 0 && *many != '|') many++; // advance to the next element
00312 
00313     if (HasBit(x, 0)) { // item found, copy it
00314       if (!init) buf += seprintf(buf, last, "|");
00315       init = false;
00316       if (start == many) {
00317         buf += seprintf(buf, last, "%d", i);
00318       } else {
00319         memcpy(buf, start, many - start);
00320         buf += many - start;
00321       }
00322     }
00323 
00324     if (*many == '|') many++;
00325   }
00326 
00327   *buf = '\0';
00328 }
00329 
00336 static const void *StringToVal(const SettingDescBase *desc, const char *orig_str)
00337 {
00338   const char *str = orig_str == NULL ? "" : orig_str;
00339   switch (desc->cmd) {
00340   case SDT_NUMX: {
00341     char *end;
00342     size_t val = strtoul(str, &end, 0);
00343     if (*end != '\0') ShowInfoF("ini: trailing characters at end of setting '%s'", desc->name);
00344     return (void*)val;
00345   }
00346   case SDT_ONEOFMANY: {
00347     size_t r = LookupOneOfMany(desc->many, str);
00348     /* if the first attempt of conversion from string to the appropriate value fails,
00349      * look if we have defined a converter from old value to new value. */
00350     if (r == (size_t)-1 && desc->proc_cnvt != NULL) r = desc->proc_cnvt(str);
00351     if (r != (size_t)-1) return (void*)r; // and here goes converted value
00352     ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name); // sorry, we failed
00353     return 0;
00354   }
00355   case SDT_MANYOFMANY: {
00356     size_t r = LookupManyOfMany(desc->many, str);
00357     if (r != (size_t)-1) return (void*)r;
00358     ShowInfoF("ini: invalid value '%s' for '%s'", str, desc->name);
00359     return NULL;
00360   }
00361   case SDT_BOOLX:
00362     if (strcmp(str, "true")  == 0 || strcmp(str, "on")  == 0 || strcmp(str, "1") == 0) return (void*)true;
00363     if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return (void*)false;
00364     ShowInfoF("ini: invalid setting value '%s' for '%s'", str, desc->name);
00365     break;
00366 
00367   case SDT_STRING: return orig_str;
00368   case SDT_INTLIST: return str;
00369   default: break;
00370   }
00371 
00372   return NULL;
00373 }
00374 
00384 static void Write_ValidateSetting(void *ptr, const SettingDesc *sd, int32 val)
00385 {
00386   const SettingDescBase *sdb = &sd->desc;
00387 
00388   if (sdb->cmd != SDT_BOOLX &&
00389       sdb->cmd != SDT_NUMX &&
00390       sdb->cmd != SDT_ONEOFMANY &&
00391       sdb->cmd != SDT_MANYOFMANY) {
00392     return;
00393   }
00394 
00395   /* We cannot know the maximum value of a bitset variable, so just have faith */
00396   if (sdb->cmd != SDT_MANYOFMANY) {
00397     /* We need to take special care of the uint32 type as we receive from the function
00398      * a signed integer. While here also bail out on 64-bit settings as those are not
00399      * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
00400      * 32-bit variable
00401      * TODO: Support 64-bit settings/variables */
00402     switch (GetVarMemType(sd->save.conv)) {
00403       case SLE_VAR_NULL: return;
00404       case SLE_VAR_BL:
00405       case SLE_VAR_I8:
00406       case SLE_VAR_U8:
00407       case SLE_VAR_I16:
00408       case SLE_VAR_U16:
00409       case SLE_VAR_I32: {
00410         /* Override the minimum value. No value below sdb->min, except special value 0 */
00411         if (!(sdb->flags & SGF_0ISDISABLED) || val != 0) val = Clamp(val, sdb->min, sdb->max);
00412         break;
00413       }
00414       case SLE_VAR_U32: {
00415         /* Override the minimum value. No value below sdb->min, except special value 0 */
00416         uint min = ((sdb->flags & SGF_0ISDISABLED) && (uint)val <= (uint)sdb->min) ? 0 : sdb->min;
00417         WriteValue(ptr, SLE_VAR_U32, (int64)ClampU(val, min, sdb->max));
00418         return;
00419       }
00420       case SLE_VAR_I64:
00421       case SLE_VAR_U64:
00422       default: NOT_REACHED();
00423     }
00424   }
00425 
00426   WriteValue(ptr, sd->save.conv, (int64)val);
00427 }
00428 
00437 static void IniLoadSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
00438 {
00439   IniGroup *group;
00440   IniGroup *group_def = ini->GetGroup(grpname);
00441   IniItem *item;
00442   const void *p;
00443   void *ptr;
00444   const char *s;
00445 
00446   for (; sd->save.cmd != SL_END; sd++) {
00447     const SettingDescBase *sdb = &sd->desc;
00448     const SaveLoad        *sld = &sd->save;
00449 
00450     if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
00451 
00452     /* For settings.xx.yy load the settings from [xx] yy = ? */
00453     s = strchr(sdb->name, '.');
00454     if (s != NULL) {
00455       group = ini->GetGroup(sdb->name, s - sdb->name);
00456       s++;
00457     } else {
00458       s = sdb->name;
00459       group = group_def;
00460     }
00461 
00462     item = group->GetItem(s, false);
00463     if (item == NULL && group != group_def) {
00464       /* For settings.xx.yy load the settings from [settingss] yy = ? in case the previous
00465        * did not exist (e.g. loading old config files with a [settings] section */
00466       item = group_def->GetItem(s, false);
00467     }
00468     if (item == NULL) {
00469       /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
00470        * did not exist (e.g. loading old config files with a [yapf] section */
00471       const char *sc = strchr(s, '.');
00472       if (sc != NULL) item = ini->GetGroup(s, sc - s)->GetItem(sc + 1, false);
00473     }
00474 
00475     p = (item == NULL) ? sdb->def : StringToVal(sdb, item->value);
00476     ptr = GetVariableAddress(object, sld);
00477 
00478     switch (sdb->cmd) {
00479     case SDT_BOOLX: // All four are various types of (integer) numbers
00480     case SDT_NUMX:
00481     case SDT_ONEOFMANY:
00482     case SDT_MANYOFMANY:
00483       Write_ValidateSetting(ptr, sd, (int32)(size_t)p); break;
00484 
00485     case SDT_STRING:
00486       switch (GetVarMemType(sld->conv)) {
00487         case SLE_VAR_STRB:
00488         case SLE_VAR_STRBQ:
00489           if (p != NULL) ttd_strlcpy((char*)ptr, (const char*)p, sld->length);
00490           break;
00491         case SLE_VAR_STR:
00492         case SLE_VAR_STRQ:
00493           free(*(char**)ptr);
00494           *(char**)ptr = p == NULL ? NULL : strdup((const char*)p);
00495           break;
00496         case SLE_VAR_CHAR: if (p != NULL) *(char*)ptr = *(char*)p; break;
00497         default: NOT_REACHED();
00498       }
00499       break;
00500 
00501     case SDT_INTLIST: {
00502       if (!LoadIntList((const char*)p, ptr, sld->length, GetVarMemType(sld->conv))) {
00503         ShowInfoF("ini: error in array '%s'", sdb->name);
00504       } else if (sd->desc.proc_cnvt != NULL) {
00505         sd->desc.proc_cnvt((const char*)p);
00506       }
00507       break;
00508     }
00509     default: NOT_REACHED();
00510     }
00511   }
00512 }
00513 
00526 static void IniSaveSettings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
00527 {
00528   IniGroup *group_def = NULL, *group;
00529   IniItem *item;
00530   char buf[512];
00531   const char *s;
00532   void *ptr;
00533 
00534   for (; sd->save.cmd != SL_END; sd++) {
00535     const SettingDescBase *sdb = &sd->desc;
00536     const SaveLoad        *sld = &sd->save;
00537 
00538     /* If the setting is not saved to the configuration
00539      * file, just continue with the next setting */
00540     if (!SlIsObjectCurrentlyValid(sld->version_from, sld->version_to)) continue;
00541     if (sld->conv & SLF_CONFIG_NO) continue;
00542 
00543     /* XXX - wtf is this?? (group override?) */
00544     s = strchr(sdb->name, '.');
00545     if (s != NULL) {
00546       group = ini->GetGroup(sdb->name, s - sdb->name);
00547       s++;
00548     } else {
00549       if (group_def == NULL) group_def = ini->GetGroup(grpname);
00550       s = sdb->name;
00551       group = group_def;
00552     }
00553 
00554     item = group->GetItem(s, true);
00555     ptr = GetVariableAddress(object, sld);
00556 
00557     if (item->value != NULL) {
00558       /* check if the value is the same as the old value */
00559       const void *p = StringToVal(sdb, item->value);
00560 
00561       /* The main type of a variable/setting is in bytes 8-15
00562        * The subtype (what kind of numbers do we have there) is in 0-7 */
00563       switch (sdb->cmd) {
00564       case SDT_BOOLX:
00565       case SDT_NUMX:
00566       case SDT_ONEOFMANY:
00567       case SDT_MANYOFMANY:
00568         switch (GetVarMemType(sld->conv)) {
00569         case SLE_VAR_BL:
00570           if (*(bool*)ptr == (p != NULL)) continue;
00571           break;
00572         case SLE_VAR_I8:
00573         case SLE_VAR_U8:
00574           if (*(byte*)ptr == (byte)(size_t)p) continue;
00575           break;
00576         case SLE_VAR_I16:
00577         case SLE_VAR_U16:
00578           if (*(uint16*)ptr == (uint16)(size_t)p) continue;
00579           break;
00580         case SLE_VAR_I32:
00581         case SLE_VAR_U32:
00582           if (*(uint32*)ptr == (uint32)(size_t)p) continue;
00583           break;
00584         default: NOT_REACHED();
00585         }
00586         break;
00587       default: break; // Assume the other types are always changed
00588       }
00589     }
00590 
00591     /* Value has changed, get the new value and put it into a buffer */
00592     switch (sdb->cmd) {
00593     case SDT_BOOLX:
00594     case SDT_NUMX:
00595     case SDT_ONEOFMANY:
00596     case SDT_MANYOFMANY: {
00597       uint32 i = (uint32)ReadValue(ptr, sld->conv);
00598 
00599       switch (sdb->cmd) {
00600       case SDT_BOOLX:      strecpy(buf, (i != 0) ? "true" : "false", lastof(buf)); break;
00601       case SDT_NUMX:       seprintf(buf, lastof(buf), IsSignedVarMemType(sld->conv) ? "%d" : "%u", i); break;
00602       case SDT_ONEOFMANY:  MakeOneOfMany(buf, lastof(buf), sdb->many, i); break;
00603       case SDT_MANYOFMANY: MakeManyOfMany(buf, lastof(buf), sdb->many, i); break;
00604       default: NOT_REACHED();
00605       }
00606       break;
00607     }
00608 
00609     case SDT_STRING:
00610       switch (GetVarMemType(sld->conv)) {
00611       case SLE_VAR_STRB: strecpy(buf, (char*)ptr, lastof(buf)); break;
00612       case SLE_VAR_STRBQ:seprintf(buf, lastof(buf), "\"%s\"", (char*)ptr); break;
00613       case SLE_VAR_STR:  strecpy(buf, *(char**)ptr, lastof(buf)); break;
00614       case SLE_VAR_STRQ:
00615         if (*(char**)ptr == NULL) {
00616           buf[0] = '\0';
00617         } else {
00618           seprintf(buf, lastof(buf), "\"%s\"", *(char**)ptr);
00619         }
00620         break;
00621       case SLE_VAR_CHAR: buf[0] = *(char*)ptr; buf[1] = '\0'; break;
00622       default: NOT_REACHED();
00623       }
00624       break;
00625 
00626     case SDT_INTLIST:
00627       MakeIntList(buf, lastof(buf), ptr, sld->length, GetVarMemType(sld->conv));
00628       break;
00629     default: NOT_REACHED();
00630     }
00631 
00632     /* The value is different, that means we have to write it to the ini */
00633     free(item->value);
00634     item->value = strdup(buf);
00635   }
00636 }
00637 
00647 static void IniLoadSettingList(IniFile *ini, const char *grpname, StringList *list)
00648 {
00649   IniGroup *group = ini->GetGroup(grpname);
00650 
00651   if (group == NULL || list == NULL) return;
00652 
00653   list->Clear();
00654 
00655   for (const IniItem *item = group->item; item != NULL; item = item->next) {
00656     if (item->name != NULL) *list->Append() = strdup(item->name);
00657   }
00658 }
00659 
00669 static void IniSaveSettingList(IniFile *ini, const char *grpname, StringList *list)
00670 {
00671   IniGroup *group = ini->GetGroup(grpname);
00672 
00673   if (group == NULL || list == NULL) return;
00674   group->Clear();
00675 
00676   for (char **iter = list->Begin(); iter != list->End(); iter++) {
00677     group->GetItem(*iter, true)->SetValue("");
00678   }
00679 }
00680 
00681 /* Begin - Callback Functions for the various settings. */
00682 
00684 static bool v_PositionMainToolbar(int32 p1)
00685 {
00686   if (_game_mode != GM_MENU) PositionMainToolbar(NULL);
00687   return true;
00688 }
00689 
00691 static bool v_PositionStatusbar(int32 p1)
00692 {
00693   if (_game_mode != GM_MENU) {
00694     PositionStatusbar(NULL);
00695     PositionNewsMessage(NULL);
00696     PositionNetworkChatWindow(NULL);
00697   }
00698   return true;
00699 }
00700 
00701 static bool PopulationInLabelActive(int32 p1)
00702 {
00703   UpdateAllTownVirtCoords();
00704   return true;
00705 }
00706 
00707 static bool RedrawScreen(int32 p1)
00708 {
00709   MarkWholeScreenDirty();
00710   return true;
00711 }
00712 
00718 static bool RedrawSmallmap(int32 p1)
00719 {
00720   BuildLandLegend();
00721   BuildOwnerLegend();
00722   SetWindowClassesDirty(WC_SMALLMAP);
00723   return true;
00724 }
00725 
00726 static bool InvalidateDetailsWindow(int32 p1)
00727 {
00728   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00729   return true;
00730 }
00731 
00732 static bool InvalidateStationBuildWindow(int32 p1)
00733 {
00734   SetWindowDirty(WC_BUILD_STATION, 0);
00735   return true;
00736 }
00737 
00738 static bool InvalidateBuildIndustryWindow(int32 p1)
00739 {
00740   InvalidateWindowData(WC_BUILD_INDUSTRY, 0);
00741   return true;
00742 }
00743 
00744 static bool CloseSignalGUI(int32 p1)
00745 {
00746   if (p1 == 0) {
00747     DeleteWindowByClass(WC_BUILD_SIGNAL);
00748   }
00749   return true;
00750 }
00751 
00752 static bool InvalidateTownViewWindow(int32 p1)
00753 {
00754   InvalidateWindowClassesData(WC_TOWN_VIEW, p1);
00755   return true;
00756 }
00757 
00758 static bool DeleteSelectStationWindow(int32 p1)
00759 {
00760   DeleteWindowById(WC_SELECT_STATION, 0);
00761   return true;
00762 }
00763 
00764 static bool UpdateConsists(int32 p1)
00765 {
00766   Train *t;
00767   FOR_ALL_TRAINS(t) {
00768     /* Update the consist of all trains so the maximum speed is set correctly. */
00769     if (t->IsFrontEngine() || t->IsFreeWagon()) t->ConsistChanged(true);
00770   }
00771   InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
00772   return true;
00773 }
00774 
00775 /* Check service intervals of vehicles, p1 is value of % or day based servicing */
00776 static bool CheckInterval(int32 p1)
00777 {
00778   VehicleDefaultSettings *vds;
00779   if (_game_mode == GM_MENU || !Company::IsValidID(_current_company)) {
00780     vds = &_settings_client.company.vehicle;
00781   } else {
00782     vds = &Company::Get(_current_company)->settings.vehicle;
00783   }
00784 
00785   if (p1) {
00786     vds->servint_trains   = 50;
00787     vds->servint_roadveh  = 50;
00788     vds->servint_aircraft = 50;
00789     vds->servint_ships    = 50;
00790   } else {
00791     vds->servint_trains   = 150;
00792     vds->servint_roadveh  = 150;
00793     vds->servint_aircraft = 100;
00794     vds->servint_ships    = 360;
00795   }
00796 
00797   InvalidateDetailsWindow(0);
00798 
00799   return true;
00800 }
00801 
00802 static bool TrainAccelerationModelChanged(int32 p1)
00803 {
00804   Train *t;
00805   FOR_ALL_TRAINS(t) {
00806     if (t->IsFrontEngine()) {
00807       t->tcache.cached_max_curve_speed = t->GetCurveSpeedLimit();
00808       t->UpdateAcceleration();
00809     }
00810   }
00811 
00812   /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
00813   SetWindowClassesDirty(WC_ENGINE_PREVIEW);
00814   InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
00815   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00816 
00817   return true;
00818 }
00819 
00825 static bool TrainSlopeSteepnessChanged(int32 p1)
00826 {
00827   Train *t;
00828   FOR_ALL_TRAINS(t) {
00829     if (t->IsFrontEngine()) t->CargoChanged();
00830   }
00831 
00832   return true;
00833 }
00834 
00840 static bool RoadVehAccelerationModelChanged(int32 p1)
00841 {
00842   if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
00843     RoadVehicle *rv;
00844     FOR_ALL_ROADVEHICLES(rv) {
00845       if (rv->IsFrontEngine()) {
00846         rv->CargoChanged();
00847       }
00848     }
00849   }
00850 
00851   /* These windows show acceleration values only when realistic acceleration is on. They must be redrawn after a setting change. */
00852   SetWindowClassesDirty(WC_ENGINE_PREVIEW);
00853   InvalidateWindowClassesData(WC_BUILD_VEHICLE, 0);
00854   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00855 
00856   return true;
00857 }
00858 
00864 static bool RoadVehSlopeSteepnessChanged(int32 p1)
00865 {
00866   RoadVehicle *rv;
00867   FOR_ALL_ROADVEHICLES(rv) {
00868     if (rv->IsFrontEngine()) rv->CargoChanged();
00869   }
00870 
00871   return true;
00872 }
00873 
00874 static bool DragSignalsDensityChanged(int32)
00875 {
00876   InvalidateWindowData(WC_BUILD_SIGNAL, 0);
00877 
00878   return true;
00879 }
00880 
00881 static bool TownFoundingChanged(int32 p1)
00882 {
00883   if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) {
00884     DeleteWindowById(WC_FOUND_TOWN, 0);
00885     return true;
00886   }
00887   InvalidateWindowData(WC_FOUND_TOWN, 0);
00888   return true;
00889 }
00890 
00891 static bool InvalidateVehTimetableWindow(int32 p1)
00892 {
00893   InvalidateWindowClassesData(WC_VEHICLE_TIMETABLE, -2);
00894   return true;
00895 }
00896 
00904 static bool InvalidateNewGRFChangeWindows(int32 p1)
00905 {
00906   InvalidateWindowClassesData(WC_SAVELOAD);
00907   DeleteWindowByClass(WC_GAME_OPTIONS);
00908   ReInitAllWindows();
00909   return true;
00910 }
00911 
00912 static bool InvalidateCompanyLiveryWindow(int32 p1)
00913 {
00914   InvalidateWindowClassesData(WC_COMPANY_COLOUR);
00915   return RedrawScreen(p1);
00916 }
00917 
00918 static bool InvalidateIndustryViewWindow(int32 p1)
00919 {
00920   InvalidateWindowClassesData(WC_INDUSTRY_VIEW);
00921   return true;
00922 }
00923 
00929 static bool RedrawTownAuthority(int32 p1)
00930 {
00931   SetWindowClassesDirty(WC_TOWN_AUTHORITY);
00932   return true;
00933 }
00934 
00935 /*
00936  * A: competitors
00937  * B: competitor start time. Deprecated since savegame version 110.
00938  * C: town count (3 = high, 0 = very low)
00939  * D: industry count (4 = high, 0 = none)
00940  * E: inital loan (in GBP)
00941  * F: interest rate
00942  * G: running costs (0 = low, 2 = high)
00943  * H: construction speed of competitors (0 = very slow, 4 = very fast)
00944  * I: competitor intelligence. Deprecated since savegame version 110.
00945  * J: breakdowns (0 = off, 2 = normal)
00946  * K: subsidy multiplier (0 = 1.5, 3 = 4.0)
00947  * L: construction cost (0-2)
00948  * M: terrain type (0 = very flat, 3 = mountainous)
00949  * N: amount of water (0 = very low, 3 = high)
00950  * O: economy (0 = steady, 1 = fluctuating)
00951  * P: Train reversing (0 = end of line + stations, 1 = end of line)
00952  * Q: disasters
00953  * R: area restructuring (0 = permissive, 2 = hostile)
00954  * S: the difficulty level
00955  */
00956 static const DifficultySettings _default_game_diff[3] = { /*
00957    A, C, D,      E, F, G, H, J, K, L, M, N, O, P, Q, R, S*/
00958   {2, 2, 4, 300000, 2, 0, 2, 1, 2, 0, 1, 0, 0, 0, 0, 0, 0}, 
00959   {4, 2, 3, 150000, 3, 1, 3, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1}, 
00960   {7, 3, 3, 100000, 4, 1, 3, 2, 0, 2, 3, 2, 1, 1, 1, 2, 2}, 
00961 };
00962 
00963 void SetDifficultyLevel(int mode, DifficultySettings *gm_opt)
00964 {
00965   assert(mode <= 3);
00966 
00967   if (mode != 3) {
00968     *gm_opt = _default_game_diff[mode];
00969   } else {
00970     gm_opt->diff_level = 3;
00971   }
00972 }
00973 
00975 static void ValidateSettings()
00976 {
00977   /* Force the difficulty levels to correct values if they are invalid. */
00978   if (_settings_newgame.difficulty.diff_level != 3) {
00979     SetDifficultyLevel(_settings_newgame.difficulty.diff_level, &_settings_newgame.difficulty);
00980   }
00981 
00982   /* Do not allow a custom sea level with the original land generator. */
00983   if (_settings_newgame.game_creation.land_generator == 0 &&
00984       _settings_newgame.difficulty.quantity_sea_lakes == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) {
00985     _settings_newgame.difficulty.quantity_sea_lakes = CUSTOM_SEA_LEVEL_MIN_PERCENTAGE;
00986   }
00987 }
00988 
00989 static bool DifficultyReset(int32 level)
00990 {
00991   /* In game / in the scenario editor you can set the difficulty level only to custom. This is
00992    * needed by the AI Gui code that sets the difficulty level when you change any AI settings. */
00993   if (_game_mode != GM_MENU && level != 3) return false;
00994   SetDifficultyLevel(level, &GetGameSettings().difficulty);
00995   return true;
00996 }
00997 
00998 static bool DifficultyChange(int32)
00999 {
01000   if (_game_mode == GM_MENU) {
01001     if (_settings_newgame.difficulty.diff_level != 3) {
01002       ShowErrorMessage(STR_WARNING_DIFFICULTY_TO_CUSTOM, INVALID_STRING_ID, WL_WARNING);
01003       _settings_newgame.difficulty.diff_level = 3;
01004     }
01005     SetWindowClassesDirty(WC_SELECT_GAME);
01006   } else {
01007     _settings_game.difficulty.diff_level = 3;
01008   }
01009 
01010   /* If we are a network-client, update the difficult setting (if it is open).
01011    * Use this instead of just dirtying the window because we need to load in
01012    * the new difficulty settings */
01013   if (_networking) InvalidateWindowClassesData(WC_GAME_OPTIONS, GOID_DIFFICULTY_CHANGED);
01014 
01015   return true;
01016 }
01017 
01018 static bool DifficultyNoiseChange(int32 i)
01019 {
01020   if (_game_mode == GM_NORMAL) {
01021     UpdateAirportsNoise();
01022     if (_settings_game.economy.station_noise_level) {
01023       InvalidateWindowClassesData(WC_TOWN_VIEW, 0);
01024     }
01025   }
01026 
01027   return DifficultyChange(i);
01028 }
01029 
01030 static bool MaxNoAIsChange(int32 i)
01031 {
01032   if (GetGameSettings().difficulty.max_no_competitors != 0 &&
01033 #ifdef ENABLE_AI
01034       AI::GetInfoList()->size() == 0 &&
01035 #endif /* ENABLE_AI */
01036       (!_networking || _network_server)) {
01037     ShowErrorMessage(STR_WARNING_NO_SUITABLE_AI, INVALID_STRING_ID, WL_CRITICAL);
01038   }
01039 
01040   return DifficultyChange(i);
01041 }
01042 
01048 static bool CheckRoadSide(int p1)
01049 {
01050   extern bool RoadVehiclesAreBuilt();
01051   return _game_mode == GM_MENU || !RoadVehiclesAreBuilt();
01052 }
01053 
01061 static size_t ConvertLandscape(const char *value)
01062 {
01063   /* try with the old values */
01064   return LookupOneOfMany("normal|hilly|desert|candy", value);
01065 }
01066 
01067 static bool CheckFreeformEdges(int32 p1)
01068 {
01069   if (_game_mode == GM_MENU) return true;
01070   if (p1 != 0) {
01071     Ship *s;
01072     FOR_ALL_SHIPS(s) {
01073       /* Check if there is a ship on the northern border. */
01074       if (TileX(s->tile) == 0 || TileY(s->tile) == 0) {
01075         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
01076         return false;
01077       }
01078     }
01079     BaseStation *st;
01080     FOR_ALL_BASE_STATIONS(st) {
01081       /* Check if there is a buoy on the northern border. */
01082       if (TileX(st->xy) == 0 || TileY(st->xy) == 0) {
01083         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_EMPTY, INVALID_STRING_ID, WL_ERROR);
01084         return false;
01085       }
01086     }
01087     for (uint i = 0; i < MapSizeX(); i++) MakeVoid(TileXY(i, 0));
01088     for (uint i = 0; i < MapSizeY(); i++) MakeVoid(TileXY(0, i));
01089   } else {
01090     for (uint i = 0; i < MapMaxX(); i++) {
01091       if (TileHeight(TileXY(i, 1)) != 0) {
01092         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01093         return false;
01094       }
01095     }
01096     for (uint i = 1; i < MapMaxX(); i++) {
01097       if (!IsTileType(TileXY(i, MapMaxY() - 1), MP_WATER) || TileHeight(TileXY(1, MapMaxY())) != 0) {
01098         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01099         return false;
01100       }
01101     }
01102     for (uint i = 0; i < MapMaxY(); i++) {
01103       if (TileHeight(TileXY(1, i)) != 0) {
01104         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01105         return false;
01106       }
01107     }
01108     for (uint i = 1; i < MapMaxY(); i++) {
01109       if (!IsTileType(TileXY(MapMaxX() - 1, i), MP_WATER) || TileHeight(TileXY(MapMaxX(), i)) != 0) {
01110         ShowErrorMessage(STR_CONFIG_SETTING_EDGES_NOT_WATER, INVALID_STRING_ID, WL_ERROR);
01111         return false;
01112       }
01113     }
01114     /* Make tiles at the border water again. */
01115     for (uint i = 0; i < MapMaxX(); i++) {
01116       SetTileHeight(TileXY(i, 0), 0);
01117       SetTileType(TileXY(i, 0), MP_WATER);
01118     }
01119     for (uint i = 0; i < MapMaxY(); i++) {
01120       SetTileHeight(TileXY(0, i), 0);
01121       SetTileType(TileXY(0, i), MP_WATER);
01122     }
01123   }
01124   MarkWholeScreenDirty();
01125   return true;
01126 }
01127 
01132 static bool ChangeDynamicEngines(int32 p1)
01133 {
01134   if (_game_mode == GM_MENU) return true;
01135 
01136   if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
01137     ShowErrorMessage(STR_CONFIG_SETTING_DYNAMIC_ENGINES_EXISTING_VEHICLES, INVALID_STRING_ID, WL_ERROR);
01138     return false;
01139   }
01140 
01141   return true;
01142 }
01143 
01144 static bool StationCatchmentChanged(int32 p1)
01145 {
01146   Station::RecomputeIndustriesNearForAll();
01147   return true;
01148 }
01149 
01150 
01151 #ifdef ENABLE_NETWORK
01152 
01153 static bool UpdateClientName(int32 p1)
01154 {
01155   NetworkUpdateClientName();
01156   return true;
01157 }
01158 
01159 static bool UpdateServerPassword(int32 p1)
01160 {
01161   if (strcmp(_settings_client.network.server_password, "*") == 0) {
01162     _settings_client.network.server_password[0] = '\0';
01163   }
01164 
01165   return true;
01166 }
01167 
01168 static bool UpdateRconPassword(int32 p1)
01169 {
01170   if (strcmp(_settings_client.network.rcon_password, "*") == 0) {
01171     _settings_client.network.rcon_password[0] = '\0';
01172   }
01173 
01174   return true;
01175 }
01176 
01177 static bool UpdateClientConfigValues(int32 p1)
01178 {
01179   if (_network_server) NetworkServerSendConfigUpdate();
01180 
01181   return true;
01182 }
01183 
01184 #endif /* ENABLE_NETWORK */
01185 
01186 
01187 /* End - Callback Functions */
01188 
01192 static void PrepareOldDiffCustom()
01193 {
01194   memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
01195 }
01196 
01203 static void HandleOldDiffCustom(bool savegame)
01204 {
01205   uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && IsSavegameVersionBefore(4)) ? 1 : 0);
01206 
01207   if (!savegame) {
01208     /* If we did read to old_diff_custom, then at least one value must be non 0. */
01209     bool old_diff_custom_used = false;
01210     for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
01211       old_diff_custom_used = (_old_diff_custom[i] != 0);
01212     }
01213 
01214     if (!old_diff_custom_used) return;
01215   }
01216 
01217   for (uint i = 0; i < options_to_load; i++) {
01218     const SettingDesc *sd = &_settings[i];
01219     /* Skip deprecated options */
01220     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01221     void *var = GetVariableAddress(savegame ? &_settings_game : &_settings_newgame, &sd->save);
01222     Write_ValidateSetting(var, sd, (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]));
01223   }
01224 }
01225 
01232 static bool ConvertOldNewsSetting(const char *name, const char *value)
01233 {
01234   if (strcasecmp(name, "openclose") == 0) {
01235     /* openclose has been split in "open" and "close".
01236      * So the job is now to decrypt the value of the old news config
01237      * and give it to the two newly introduced ones*/
01238 
01239     NewsDisplay display = ND_OFF; // default
01240     if (strcasecmp(value, "full") == 0) {
01241       display = ND_FULL;
01242     } else if (strcasecmp(value, "summarized") == 0) {
01243       display = ND_SUMMARY;
01244     }
01245     /* tranfert of values */
01246     _news_type_data[NT_INDUSTRY_OPEN].display = display;
01247     _news_type_data[NT_INDUSTRY_CLOSE].display = display;
01248     return true;
01249   }
01250   return false;
01251 }
01252 
01258 static void NewsDisplayLoadConfig(IniFile *ini, const char *grpname)
01259 {
01260   IniGroup *group = ini->GetGroup(grpname);
01261   IniItem *item;
01262 
01263   /* If no group exists, return */
01264   if (group == NULL) return;
01265 
01266   for (item = group->item; item != NULL; item = item->next) {
01267     int news_item = -1;
01268     for (int i = 0; i < NT_END; i++) {
01269       if (strcasecmp(item->name, _news_type_data[i].name) == 0) {
01270         news_item = i;
01271         break;
01272       }
01273     }
01274 
01275     /* the config been read is not within current aceptable config */
01276     if (news_item == -1) {
01277       /* if the conversion function cannot process it, advice by a debug warning*/
01278       if (!ConvertOldNewsSetting(item->name, item->value)) {
01279         DEBUG(misc, 0, "Invalid display option: %s", item->name);
01280       }
01281       /* in all cases, there is nothing left to do */
01282       continue;
01283     }
01284 
01285     if (StrEmpty(item->value)) {
01286       DEBUG(misc, 0, "Empty display value for newstype %s", item->name);
01287       continue;
01288     } else if (strcasecmp(item->value, "full") == 0) {
01289       _news_type_data[news_item].display = ND_FULL;
01290     } else if (strcasecmp(item->value, "off") == 0) {
01291       _news_type_data[news_item].display = ND_OFF;
01292     } else if (strcasecmp(item->value, "summarized") == 0) {
01293       _news_type_data[news_item].display = ND_SUMMARY;
01294     } else {
01295       DEBUG(misc, 0, "Invalid display value for newstype %s: %s", item->name, item->value);
01296       continue;
01297     }
01298   }
01299 }
01300 
01301 static void AILoadConfig(IniFile *ini, const char *grpname)
01302 {
01303 #ifdef ENABLE_AI
01304   IniGroup *group = ini->GetGroup(grpname);
01305   IniItem *item;
01306 
01307   /* Clean any configured AI */
01308   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
01309     AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME)->ChangeAI(NULL);
01310   }
01311 
01312   /* If no group exists, return */
01313   if (group == NULL) return;
01314 
01315   CompanyID c = COMPANY_FIRST;
01316   for (item = group->item; c < MAX_COMPANIES && item != NULL; c++, item = item->next) {
01317     AIConfig *config = AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME);
01318 
01319     config->ChangeAI(item->name);
01320     if (!config->HasAI()) {
01321       if (strcmp(item->name, "none") != 0) {
01322         DEBUG(ai, 0, "The AI by the name '%s' was no longer found, and removed from the list.", item->name);
01323         continue;
01324       }
01325     }
01326     if (item->value != NULL) config->StringToSettings(item->value);
01327   }
01328 #endif /* ENABLE_AI */
01329 }
01330 
01337 static GRFConfig *GRFLoadConfig(IniFile *ini, const char *grpname, bool is_static)
01338 {
01339   IniGroup *group = ini->GetGroup(grpname);
01340   IniItem *item;
01341   GRFConfig *first = NULL;
01342   GRFConfig **curr = &first;
01343 
01344   if (group == NULL) return NULL;
01345 
01346   for (item = group->item; item != NULL; item = item->next) {
01347     GRFConfig *c = new GRFConfig(item->name);
01348 
01349     /* Parse parameters */
01350     if (!StrEmpty(item->value)) {
01351       c->num_params = ParseIntList(item->value, (int*)c->param, lengthof(c->param));
01352       if (c->num_params == (byte)-1) {
01353         ShowInfoF("ini: error in array '%s'", item->name);
01354         c->num_params = 0;
01355       }
01356     }
01357 
01358     /* Check if item is valid */
01359     if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
01360       const char *msg;
01361 
01362       if (c->status == GCS_NOT_FOUND) {
01363         msg = "not found";
01364       } else if (HasBit(c->flags, GCF_UNSAFE)) {
01365         msg = "unsafe for static use";
01366       } else if (HasBit(c->flags, GCF_SYSTEM)) {
01367         msg = "system NewGRF";
01368       } else if (HasBit(c->flags, GCF_INVALID)) {
01369         msg = "incompatible to this version of OpenTTD";
01370       } else {
01371         msg = "unknown";
01372       }
01373 
01374       ShowInfoF("ini: ignoring invalid NewGRF '%s': %s", item->name, msg);
01375       delete c;
01376       continue;
01377     }
01378 
01379     /* Check for duplicate GRFID (will also check for duplicate filenames) */
01380     bool duplicate = false;
01381     for (const GRFConfig *gc = first; gc != NULL; gc = gc->next) {
01382       if (gc->ident.grfid == c->ident.grfid) {
01383         ShowInfoF("ini: ignoring  NewGRF '%s': duplicate GRF ID with '%s'", item->name, gc->filename);
01384         duplicate = true;
01385         break;
01386       }
01387     }
01388     if (duplicate) {
01389       delete c;
01390       continue;
01391     }
01392 
01393     /* Mark file as static to avoid saving in savegame. */
01394     if (is_static) SetBit(c->flags, GCF_STATIC);
01395 
01396     /* Add item to list */
01397     *curr = c;
01398     curr = &c->next;
01399   }
01400 
01401   return first;
01402 }
01403 
01409 static void NewsDisplaySaveConfig(IniFile *ini, const char *grpname)
01410 {
01411   IniGroup *group = ini->GetGroup(grpname);
01412 
01413   for (int i = 0; i < NT_END; i++) {
01414     const char *value;
01415     int v = _news_type_data[i].display;
01416 
01417     value = (v == ND_OFF ? "off" : (v == ND_SUMMARY ? "summarized" : "full"));
01418 
01419     group->GetItem(_news_type_data[i].name, true)->SetValue(value);
01420   }
01421 }
01422 
01423 static void AISaveConfig(IniFile *ini, const char *grpname)
01424 {
01425 #ifdef ENABLE_AI
01426   IniGroup *group = ini->GetGroup(grpname);
01427 
01428   if (group == NULL) return;
01429   group->Clear();
01430 
01431   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
01432     AIConfig *config = AIConfig::GetConfig(c, AIConfig::AISS_FORCE_NEWGAME);
01433     const char *name;
01434     char value[1024];
01435     config->SettingsToString(value, lengthof(value));
01436 
01437     if (config->HasAI()) {
01438       name = config->GetName();
01439     } else {
01440       name = "none";
01441     }
01442 
01443     IniItem *item = new IniItem(group, name, strlen(name));
01444     item->SetValue(value);
01445   }
01446 #endif /* ENABLE_AI */
01447 }
01448 
01453 static void SaveVersionInConfig(IniFile *ini)
01454 {
01455   IniGroup *group = ini->GetGroup("version");
01456 
01457   char version[9];
01458   snprintf(version, lengthof(version), "%08X", _openttd_newgrf_version);
01459 
01460   const char * const versions[][2] = {
01461     { "version_string", _openttd_revision },
01462     { "version_number", version }
01463   };
01464 
01465   for (uint i = 0; i < lengthof(versions); i++) {
01466     group->GetItem(versions[i][0], true)->SetValue(versions[i][1]);
01467   }
01468 }
01469 
01470 /* Save a GRF configuration to the given group name */
01471 static void GRFSaveConfig(IniFile *ini, const char *grpname, const GRFConfig *list)
01472 {
01473   ini->RemoveGroup(grpname);
01474   IniGroup *group = ini->GetGroup(grpname);
01475   const GRFConfig *c;
01476 
01477   for (c = list; c != NULL; c = c->next) {
01478     char params[512];
01479     GRFBuildParamList(params, c, lastof(params));
01480 
01481     group->GetItem(c->filename, true)->SetValue(params);
01482   }
01483 }
01484 
01485 /* Common handler for saving/loading variables to the configuration file */
01486 static void HandleSettingDescs(IniFile *ini, SettingDescProc *proc, SettingDescProcList *proc_list)
01487 {
01488   proc(ini, (const SettingDesc*)_misc_settings,    "misc",  NULL);
01489   proc(ini, (const SettingDesc*)_music_settings,   "music", &_msf);
01490 #if defined(WIN32) && !defined(DEDICATED)
01491   proc(ini, (const SettingDesc*)_win32_settings,   "win32", NULL);
01492 #endif /* WIN32 */
01493 
01494   proc(ini, _settings,         "patches",  &_settings_newgame);
01495   proc(ini, _currency_settings,"currency", &_custom_currency);
01496   proc(ini, _company_settings, "company",  &_settings_client.company);
01497 
01498 #ifdef ENABLE_NETWORK
01499   proc_list(ini, "server_bind_addresses", &_network_bind_list);
01500   proc_list(ini, "servers", &_network_host_list);
01501   proc_list(ini, "bans",    &_network_ban_list);
01502 #endif /* ENABLE_NETWORK */
01503 }
01504 
01505 static IniFile *IniLoadConfig()
01506 {
01507   IniFile *ini = new IniFile(_list_group_names);
01508   ini->LoadFromDisk(_config_file);
01509   return ini;
01510 }
01511 
01513 void LoadFromConfig()
01514 {
01515   IniFile *ini = IniLoadConfig();
01516   ResetCurrencies(false); // Initialize the array of curencies, without preserving the custom one
01517 
01518   HandleSettingDescs(ini, IniLoadSettings, IniLoadSettingList);
01519   _grfconfig_newgame = GRFLoadConfig(ini, "newgrf", false);
01520   _grfconfig_static  = GRFLoadConfig(ini, "newgrf-static", true);
01521   NewsDisplayLoadConfig(ini, "news_display");
01522   AILoadConfig(ini, "ai_players");
01523 
01524   PrepareOldDiffCustom();
01525   IniLoadSettings(ini, _gameopt_settings, "gameopt", &_settings_newgame);
01526   HandleOldDiffCustom(false);
01527 
01528   ValidateSettings();
01529   delete ini;
01530 }
01531 
01533 void SaveToConfig()
01534 {
01535   IniFile *ini = IniLoadConfig();
01536 
01537   /* Remove some obsolete groups. These have all been loaded into other groups. */
01538   ini->RemoveGroup("patches");
01539   ini->RemoveGroup("yapf");
01540   ini->RemoveGroup("gameopt");
01541 
01542   HandleSettingDescs(ini, IniSaveSettings, IniSaveSettingList);
01543   GRFSaveConfig(ini, "newgrf", _grfconfig_newgame);
01544   GRFSaveConfig(ini, "newgrf-static", _grfconfig_static);
01545   NewsDisplaySaveConfig(ini, "news_display");
01546   AISaveConfig(ini, "ai_players");
01547   SaveVersionInConfig(ini);
01548   ini->SaveToDisk(_config_file);
01549   delete ini;
01550 }
01551 
01556 void GetGRFPresetList(GRFPresetList *list)
01557 {
01558   list->Clear();
01559 
01560   IniFile *ini = IniLoadConfig();
01561   IniGroup *group;
01562   for (group = ini->group; group != NULL; group = group->next) {
01563     if (strncmp(group->name, "preset-", 7) == 0) {
01564       *list->Append() = strdup(group->name + 7);
01565     }
01566   }
01567 
01568   delete ini;
01569 }
01570 
01577 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
01578 {
01579   char *section = (char*)alloca(strlen(config_name) + 8);
01580   sprintf(section, "preset-%s", config_name);
01581 
01582   IniFile *ini = IniLoadConfig();
01583   GRFConfig *config = GRFLoadConfig(ini, section, false);
01584   delete ini;
01585 
01586   return config;
01587 }
01588 
01595 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
01596 {
01597   char *section = (char*)alloca(strlen(config_name) + 8);
01598   sprintf(section, "preset-%s", config_name);
01599 
01600   IniFile *ini = IniLoadConfig();
01601   GRFSaveConfig(ini, section, config);
01602   ini->SaveToDisk(_config_file);
01603   delete ini;
01604 }
01605 
01610 void DeleteGRFPresetFromConfig(const char *config_name)
01611 {
01612   char *section = (char*)alloca(strlen(config_name) + 8);
01613   sprintf(section, "preset-%s", config_name);
01614 
01615   IniFile *ini = IniLoadConfig();
01616   ini->RemoveGroup(section);
01617   ini->SaveToDisk(_config_file);
01618   delete ini;
01619 }
01620 
01621 static const SettingDesc *GetSettingDescription(uint index)
01622 {
01623   if (index >= lengthof(_settings)) return NULL;
01624   return &_settings[index];
01625 }
01626 
01638 CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01639 {
01640   const SettingDesc *sd = GetSettingDescription(p1);
01641 
01642   if (sd == NULL) return CMD_ERROR;
01643   if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
01644 
01645   if ((sd->desc.flags & SGF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return CMD_ERROR;
01646   if ((sd->desc.flags & SGF_NO_NETWORK) && _networking) return CMD_ERROR;
01647   if ((sd->desc.flags & SGF_NEWGAME_ONLY) &&
01648       (_game_mode == GM_NORMAL ||
01649       (_game_mode == GM_EDITOR && (sd->desc.flags & SGF_SCENEDIT_TOO) == 0))) {
01650     return CMD_ERROR;
01651   }
01652 
01653   if (flags & DC_EXEC) {
01654     void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
01655 
01656     int32 oldval = (int32)ReadValue(var, sd->save.conv);
01657     int32 newval = (int32)p2;
01658 
01659     Write_ValidateSetting(var, sd, newval);
01660     newval = (int32)ReadValue(var, sd->save.conv);
01661 
01662     if (oldval == newval) return CommandCost();
01663 
01664     if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
01665       WriteValue(var, sd->save.conv, (int64)oldval);
01666       return CommandCost();
01667     }
01668 
01669     if (sd->desc.flags & SGF_NO_NETWORK) {
01670       GamelogStartAction(GLAT_SETTING);
01671       GamelogSetting(sd->desc.name, oldval, newval);
01672       GamelogStopAction();
01673     }
01674 
01675     SetWindowDirty(WC_GAME_OPTIONS, 0);
01676   }
01677 
01678   return CommandCost();
01679 }
01680 
01691 CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01692 {
01693   if (p1 >= lengthof(_company_settings)) return CMD_ERROR;
01694   const SettingDesc *sd = &_company_settings[p1];
01695 
01696   if (flags & DC_EXEC) {
01697     void *var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
01698 
01699     int32 oldval = (int32)ReadValue(var, sd->save.conv);
01700     int32 newval = (int32)p2;
01701 
01702     Write_ValidateSetting(var, sd, newval);
01703     newval = (int32)ReadValue(var, sd->save.conv);
01704 
01705     if (oldval == newval) return CommandCost();
01706 
01707     if (sd->desc.proc != NULL && !sd->desc.proc(newval)) {
01708       WriteValue(var, sd->save.conv, (int64)oldval);
01709       return CommandCost();
01710     }
01711 
01712     SetWindowDirty(WC_GAME_OPTIONS, 0);
01713   }
01714 
01715   return CommandCost();
01716 }
01717 
01725 bool SetSettingValue(uint index, int32 value, bool force_newgame)
01726 {
01727   const SettingDesc *sd = &_settings[index];
01728   /* If an item is company-based, we do not send it over the network
01729    * (if any) to change. Also *hack*hack* we update the _newgame version
01730    * of settings because changing a company-based setting in a game also
01731    * changes its defaults. At least that is the convention we have chosen */
01732   if (sd->save.conv & SLF_NETWORK_NO) {
01733     void *var = GetVariableAddress(&GetGameSettings(), &sd->save);
01734     Write_ValidateSetting(var, sd, value);
01735 
01736     if (_game_mode != GM_MENU) {
01737       void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
01738       Write_ValidateSetting(var2, sd, value);
01739     }
01740     if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
01741     SetWindowDirty(WC_GAME_OPTIONS, 0);
01742     return true;
01743   }
01744 
01745   if (force_newgame) {
01746     void *var2 = GetVariableAddress(&_settings_newgame, &sd->save);
01747     Write_ValidateSetting(var2, sd, value);
01748     return true;
01749   }
01750 
01751   /* send non-company-based settings over the network */
01752   if (!_networking || (_networking && _network_server)) {
01753     return DoCommandP(0, index, value, CMD_CHANGE_SETTING);
01754   }
01755   return false;
01756 }
01757 
01764 void SetCompanySetting(uint index, int32 value)
01765 {
01766   const SettingDesc *sd = &_company_settings[index];
01767   if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
01768     DoCommandP(0, index, value, CMD_CHANGE_COMPANY_SETTING);
01769   } else {
01770     void *var = GetVariableAddress(&_settings_client.company, &sd->save);
01771     Write_ValidateSetting(var, sd, value);
01772     if (sd->desc.proc != NULL) sd->desc.proc((int32)ReadValue(var, sd->save.conv));
01773   }
01774 }
01775 
01779 void SetDefaultCompanySettings(CompanyID cid)
01780 {
01781   Company *c = Company::Get(cid);
01782   const SettingDesc *sd;
01783   for (sd = _company_settings; sd->save.cmd != SL_END; sd++) {
01784     void *var = GetVariableAddress(&c->settings, &sd->save);
01785     Write_ValidateSetting(var, sd, (int32)(size_t)sd->desc.def);
01786   }
01787 }
01788 
01789 #if defined(ENABLE_NETWORK)
01790 
01793 void SyncCompanySettings()
01794 {
01795   const SettingDesc *sd;
01796   uint i = 0;
01797   for (sd = _company_settings; sd->save.cmd != SL_END; sd++, i++) {
01798     const void *old_var = GetVariableAddress(&Company::Get(_current_company)->settings, &sd->save);
01799     const void *new_var = GetVariableAddress(&_settings_client.company, &sd->save);
01800     uint32 old_value = (uint32)ReadValue(old_var, sd->save.conv);
01801     uint32 new_value = (uint32)ReadValue(new_var, sd->save.conv);
01802     if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, NULL, NULL, _local_company);
01803   }
01804 }
01805 #endif /* ENABLE_NETWORK */
01806 
01812 uint GetCompanySettingIndex(const char *name)
01813 {
01814   uint i;
01815   const SettingDesc *sd = GetSettingFromName(name, &i);
01816   assert(sd != NULL && (sd->desc.flags & SGF_PER_COMPANY) != 0);
01817   return i;
01818 }
01819 
01827 bool SetSettingValue(uint index, const char *value, bool force_newgame)
01828 {
01829   const SettingDesc *sd = &_settings[index];
01830   assert(sd->save.conv & SLF_NETWORK_NO);
01831 
01832   if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) {
01833     char **var = (char**)GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
01834     free(*var);
01835     *var = strcmp(value, "(null)") == 0 ? NULL : strdup(value);
01836   } else {
01837     char *var = (char*)GetVariableAddress(NULL, &sd->save);
01838     ttd_strlcpy(var, value, sd->save.length);
01839   }
01840   if (sd->desc.proc != NULL) sd->desc.proc(0);
01841 
01842   return true;
01843 }
01844 
01852 const SettingDesc *GetSettingFromName(const char *name, uint *i)
01853 {
01854   const SettingDesc *sd;
01855 
01856   /* First check all full names */
01857   for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01858     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01859     if (strcmp(sd->desc.name, name) == 0) return sd;
01860   }
01861 
01862   /* Then check the shortcut variant of the name. */
01863   for (*i = 0, sd = _settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01864     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01865     const char *short_name = strchr(sd->desc.name, '.');
01866     if (short_name != NULL) {
01867       short_name++;
01868       if (strcmp(short_name, name) == 0) return sd;
01869     }
01870   }
01871 
01872   if (strncmp(name, "company.", 8) == 0) name += 8;
01873   /* And finally the company-based settings */
01874   for (*i = 0, sd = _company_settings; sd->save.cmd != SL_END; sd++, (*i)++) {
01875     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01876     if (strcmp(sd->desc.name, name) == 0) return sd;
01877   }
01878 
01879   return NULL;
01880 }
01881 
01882 /* Those 2 functions need to be here, else we have to make some stuff non-static
01883  * and besides, it is also better to keep stuff like this at the same place */
01884 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
01885 {
01886   uint index;
01887   const SettingDesc *sd = GetSettingFromName(name, &index);
01888 
01889   if (sd == NULL) {
01890     IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
01891     return;
01892   }
01893 
01894   bool success;
01895   if (sd->desc.cmd == SDT_STRING) {
01896     success = SetSettingValue(index, value, force_newgame);
01897   } else {
01898     uint32 val;
01899     extern bool GetArgumentInteger(uint32 *value, const char *arg);
01900     success = GetArgumentInteger(&val, value);
01901     if (!success) {
01902       IConsolePrintF(CC_ERROR, "'%s' is not an integer.", value);
01903       return;
01904     }
01905 
01906     success = SetSettingValue(index, val, force_newgame);
01907   }
01908 
01909   if (!success) {
01910     if (_network_server) {
01911       IConsoleError("This command/variable is not available during network games.");
01912     } else {
01913       IConsoleError("This command/variable is only available to a network server.");
01914     }
01915   }
01916 }
01917 
01918 void IConsoleSetSetting(const char *name, int value)
01919 {
01920   uint index;
01921   const SettingDesc *sd = GetSettingFromName(name, &index);
01922   assert(sd != NULL);
01923   SetSettingValue(index, value);
01924 }
01925 
01931 void IConsoleGetSetting(const char *name, bool force_newgame)
01932 {
01933   char value[20];
01934   uint index;
01935   const SettingDesc *sd = GetSettingFromName(name, &index);
01936   const void *ptr;
01937 
01938   if (sd == NULL) {
01939     IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name);
01940     return;
01941   }
01942 
01943   ptr = GetVariableAddress((_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game, &sd->save);
01944 
01945   if (sd->desc.cmd == SDT_STRING) {
01946     IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s'", name, (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char **)ptr : (const char *)ptr);
01947   } else {
01948     if (sd->desc.cmd == SDT_BOOLX) {
01949       snprintf(value, sizeof(value), (*(bool*)ptr == 1) ? "on" : "off");
01950     } else {
01951       snprintf(value, sizeof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
01952     }
01953 
01954     IConsolePrintF(CC_WARNING, "Current value for '%s' is: '%s' (min: %s%d, max: %u)",
01955       name, value, (sd->desc.flags & SGF_0ISDISABLED) ? "(0) " : "", sd->desc.min, sd->desc.max);
01956   }
01957 }
01958 
01964 void IConsoleListSettings(const char *prefilter)
01965 {
01966   IConsolePrintF(CC_WARNING, "All settings with their current value:");
01967 
01968   for (const SettingDesc *sd = _settings; sd->save.cmd != SL_END; sd++) {
01969     if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
01970     if (prefilter != NULL && strstr(sd->desc.name, prefilter) == NULL) continue;
01971     char value[80];
01972     const void *ptr = GetVariableAddress(&GetGameSettings(), &sd->save);
01973 
01974     if (sd->desc.cmd == SDT_BOOLX) {
01975       snprintf(value, lengthof(value), (*(bool*)ptr == 1) ? "on" : "off");
01976     } else if (sd->desc.cmd == SDT_STRING) {
01977       snprintf(value, sizeof(value), "%s", (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ) ? *(const char **)ptr : (const char *)ptr);
01978     } else {
01979       snprintf(value, lengthof(value), sd->desc.min < 0 ? "%d" : "%u", (int32)ReadValue(ptr, sd->save.conv));
01980     }
01981     IConsolePrintF(CC_DEFAULT, "%s = %s", sd->desc.name, value);
01982   }
01983 
01984   IConsolePrintF(CC_WARNING, "Use 'setting' command to change a value");
01985 }
01986 
01993 static void LoadSettings(const SettingDesc *osd, void *object)
01994 {
01995   for (; osd->save.cmd != SL_END; osd++) {
01996     const SaveLoad *sld = &osd->save;
01997     void *ptr = GetVariableAddress(object, sld);
01998 
01999     if (!SlObjectMember(ptr, sld)) continue;
02000     if (IsNumericType(sld->conv)) Write_ValidateSetting(ptr, osd, ReadValue(ptr, sld->conv));
02001   }
02002 }
02003 
02010 static void SaveSettings(const SettingDesc *sd, void *object)
02011 {
02012   /* We need to write the CH_RIFF header, but unfortunately can't call
02013    * SlCalcLength() because we have a different format. So do this manually */
02014   const SettingDesc *i;
02015   size_t length = 0;
02016   for (i = sd; i->save.cmd != SL_END; i++) {
02017     length += SlCalcObjMemberLength(object, &i->save);
02018   }
02019   SlSetLength(length);
02020 
02021   for (i = sd; i->save.cmd != SL_END; i++) {
02022     void *ptr = GetVariableAddress(object, &i->save);
02023     SlObjectMember(ptr, &i->save);
02024   }
02025 }
02026 
02027 static void Load_OPTS()
02028 {
02029   /* Copy over default setting since some might not get loaded in
02030    * a networking environment. This ensures for example that the local
02031    * autosave-frequency stays when joining a network-server */
02032   PrepareOldDiffCustom();
02033   LoadSettings(_gameopt_settings, &_settings_game);
02034   HandleOldDiffCustom(true);
02035 }
02036 
02037 static void Load_PATS()
02038 {
02039   /* Copy over default setting since some might not get loaded in
02040    * a networking environment. This ensures for example that the local
02041    * signal_side stays when joining a network-server */
02042   LoadSettings(_settings, &_settings_game);
02043 }
02044 
02045 static void Check_PATS()
02046 {
02047   LoadSettings(_settings, &_load_check_data.settings);
02048 }
02049 
02050 static void Save_PATS()
02051 {
02052   SaveSettings(_settings, &_settings_game);
02053 }
02054 
02055 void CheckConfig()
02056 {
02057   /*
02058    * Increase old default values for pf_maxdepth and pf_maxlength
02059    * to support big networks.
02060    */
02061   if (_settings_newgame.pf.opf.pf_maxdepth == 16 && _settings_newgame.pf.opf.pf_maxlength == 512) {
02062     _settings_newgame.pf.opf.pf_maxdepth = 48;
02063     _settings_newgame.pf.opf.pf_maxlength = 4096;
02064   }
02065 }
02066 
02067 extern const ChunkHandler _setting_chunk_handlers[] = {
02068   { 'OPTS', NULL,      Load_OPTS, NULL, NULL,       CH_RIFF},
02069   { 'PATS', Save_PATS, Load_PATS, NULL, Check_PATS, CH_RIFF | CH_LAST},
02070 };
02071 
02072 static bool IsSignedVarMemType(VarType vt)
02073 {
02074   switch (GetVarMemType(vt)) {
02075     case SLE_VAR_I8:
02076     case SLE_VAR_I16:
02077     case SLE_VAR_I32:
02078     case SLE_VAR_I64:
02079       return true;
02080   }
02081   return false;
02082 }