newgrf_config.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 
00012 #include "stdafx.h"
00013 #include "debug.h"
00014 #include "3rdparty/md5/md5.h"
00015 #include "newgrf.h"
00016 #include "network/network_func.h"
00017 #include "gfx_func.h"
00018 #include "newgrf_text.h"
00019 #include "window_func.h"
00020 #include "progress.h"
00021 #include "video/video_driver.hpp"
00022 #include "strings_func.h"
00023 
00024 #include "fileio_func.h"
00025 #include "fios.h"
00026 
00028 GRFTextWrapper::GRFTextWrapper() :
00029   text(NULL)
00030 {
00031 }
00032 
00034 GRFTextWrapper::~GRFTextWrapper()
00035 {
00036   CleanUpGRFText(this->text);
00037 }
00038 
00044 GRFConfig::GRFConfig(const char *filename) :
00045   name(new GRFTextWrapper()),
00046   info(new GRFTextWrapper()),
00047   url(new GRFTextWrapper()),
00048   num_valid_params(lengthof(param))
00049 {
00050   if (filename != NULL) this->filename = strdup(filename);
00051   this->name->AddRef();
00052   this->info->AddRef();
00053   this->url->AddRef();
00054 }
00055 
00060 GRFConfig::GRFConfig(const GRFConfig &config) :
00061   ZeroedMemoryAllocator(),
00062   ident(config.ident),
00063   name(config.name),
00064   info(config.info),
00065   url(config.url),
00066   version(config.version),
00067   min_loadable_version(config.min_loadable_version),
00068   flags(config.flags & ~(1 << GCF_COPY)),
00069   status(config.status),
00070   grf_bugs(config.grf_bugs),
00071   num_params(config.num_params),
00072   num_valid_params(config.num_valid_params),
00073   palette(config.palette),
00074   has_param_defaults(config.has_param_defaults)
00075 {
00076   MemCpyT<uint8>(this->original_md5sum, config.original_md5sum, lengthof(this->original_md5sum));
00077   MemCpyT<uint32>(this->param, config.param, lengthof(this->param));
00078   if (config.filename != NULL) this->filename = strdup(config.filename);
00079   this->name->AddRef();
00080   this->info->AddRef();
00081   this->url->AddRef();
00082   if (config.error    != NULL) this->error    = new GRFError(*config.error);
00083   for (uint i = 0; i < config.param_info.Length(); i++) {
00084     if (config.param_info[i] == NULL) {
00085       *this->param_info.Append() = NULL;
00086     } else {
00087       *this->param_info.Append() = new GRFParameterInfo(*config.param_info[i]);
00088     }
00089   }
00090 }
00091 
00093 GRFConfig::~GRFConfig()
00094 {
00095   /* GCF_COPY as in NOT strdupped/alloced the filename */
00096   if (!HasBit(this->flags, GCF_COPY)) {
00097     free(this->filename);
00098     delete this->error;
00099   }
00100   this->name->Release();
00101   this->info->Release();
00102   this->url->Release();
00103 
00104   for (uint i = 0; i < this->param_info.Length(); i++) delete this->param_info[i];
00105 }
00106 
00112 const char *GRFConfig::GetName() const
00113 {
00114   const char *name = GetGRFStringFromGRFText(this->name->text);
00115   return StrEmpty(name) ? this->filename : name;
00116 }
00117 
00122 const char *GRFConfig::GetDescription() const
00123 {
00124   return GetGRFStringFromGRFText(this->info->text);
00125 }
00126 
00131 const char *GRFConfig::GetURL() const
00132 {
00133   return GetGRFStringFromGRFText(this->url->text);
00134 }
00135 
00137 void GRFConfig::SetParameterDefaults()
00138 {
00139   this->num_params = 0;
00140   MemSetT<uint32>(this->param, 0, lengthof(this->param));
00141 
00142   if (!this->has_param_defaults) return;
00143 
00144   for (uint i = 0; i < this->param_info.Length(); i++) {
00145     if (this->param_info[i] == NULL) continue;
00146     this->param_info[i]->SetValue(this, this->param_info[i]->def_value);
00147   }
00148 }
00149 
00155 void GRFConfig::SetSuitablePalette()
00156 {
00157   PaletteType pal;
00158   switch (this->palette & GRFP_GRF_MASK) {
00159     case GRFP_GRF_DOS:     pal = PAL_DOS;      break;
00160     case GRFP_GRF_WINDOWS: pal = PAL_WINDOWS;  break;
00161     default:               pal = _settings_client.gui.newgrf_default_palette == 1 ? PAL_WINDOWS : PAL_DOS; break;
00162   }
00163   SB(this->palette, GRFP_USE_BIT, 1, pal == PAL_WINDOWS ? GRFP_USE_WINDOWS : GRFP_USE_DOS);
00164 }
00165 
00166 GRFConfig *_all_grfs;
00167 GRFConfig *_grfconfig;
00168 GRFConfig *_grfconfig_newgame;
00169 GRFConfig *_grfconfig_static;
00170 
00176 GRFError::GRFError(StringID severity, StringID message) :
00177   message(message),
00178   severity(severity)
00179 {
00180 }
00181 
00186 GRFError::GRFError(const GRFError &error) :
00187   ZeroedMemoryAllocator(),
00188   custom_message(error.custom_message),
00189   data(error.data),
00190   message(error.message),
00191   severity(error.severity)
00192 {
00193   if (error.custom_message != NULL) this->custom_message = strdup(error.custom_message);
00194   if (error.data           != NULL) this->data           = strdup(error.data);
00195   memcpy(this->param_value, error.param_value, sizeof(this->param_value));
00196 }
00197 
00198 GRFError::~GRFError()
00199 {
00200   free(this->custom_message);
00201   free(this->data);
00202 }
00203 
00208 GRFParameterInfo::GRFParameterInfo(uint nr) :
00209   name(NULL),
00210   desc(NULL),
00211   type(PTYPE_UINT_ENUM),
00212   min_value(0),
00213   max_value(UINT32_MAX),
00214   def_value(0),
00215   param_nr(nr),
00216   first_bit(0),
00217   num_bit(32)
00218 {}
00219 
00225 GRFParameterInfo::GRFParameterInfo(GRFParameterInfo &info) :
00226   name(DuplicateGRFText(info.name)),
00227   desc(DuplicateGRFText(info.desc)),
00228   type(info.type),
00229   min_value(info.min_value),
00230   max_value(info.max_value),
00231   def_value(info.def_value),
00232   param_nr(info.param_nr),
00233   first_bit(info.first_bit),
00234   num_bit(info.num_bit)
00235 {
00236   for (uint i = 0; i < info.value_names.Length(); i++) {
00237     SmallPair<uint32, GRFText *> *data = info.value_names.Get(i);
00238     this->value_names.Insert(data->first, DuplicateGRFText(data->second));
00239   }
00240 }
00241 
00243 GRFParameterInfo::~GRFParameterInfo()
00244 {
00245   CleanUpGRFText(this->name);
00246   CleanUpGRFText(this->desc);
00247   for (uint i = 0; i < this->value_names.Length(); i++) {
00248     SmallPair<uint32, GRFText *> *data = this->value_names.Get(i);
00249     CleanUpGRFText(data->second);
00250   }
00251 }
00252 
00258 uint32 GRFParameterInfo::GetValue(struct GRFConfig *config) const
00259 {
00260   /* GB doesn't work correctly with nbits == 32, so handle that case here. */
00261   if (this->num_bit == 32) return config->param[this->param_nr];
00262   return GB(config->param[this->param_nr], this->first_bit, this->num_bit);
00263 }
00264 
00270 void GRFParameterInfo::SetValue(struct GRFConfig *config, uint32 value)
00271 {
00272   /* SB doesn't work correctly with nbits == 32, so handle that case here. */
00273   if (this->num_bit == 32) {
00274     config->param[this->param_nr] = value;
00275   } else {
00276     SB(config->param[this->param_nr], this->first_bit, this->num_bit, value);
00277   }
00278   config->num_params = max<uint>(config->num_params, this->param_nr + 1);
00279   SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
00280 }
00281 
00288 bool UpdateNewGRFConfigPalette(int32 p1)
00289 {
00290   for (GRFConfig *c = _grfconfig_newgame; c != NULL; c = c->next) c->SetSuitablePalette();
00291   for (GRFConfig *c = _grfconfig_static;  c != NULL; c = c->next) c->SetSuitablePalette();
00292   for (GRFConfig *c = _all_grfs;          c != NULL; c = c->next) c->SetSuitablePalette();
00293   return true;
00294 }
00295 
00301 size_t GRFGetSizeOfDataSection(FILE *f)
00302 {
00303   extern const byte _grf_cont_v2_sig[];
00304   static const uint header_len = 14;
00305 
00306   byte data[header_len];
00307   if (fread(data, 1, header_len, f) == header_len) {
00308     if (data[0] == 0 && data[1] == 0 && MemCmpT(data + 2, _grf_cont_v2_sig, 8) == 0) {
00309       /* Valid container version 2, get data section size. */
00310       size_t offset = (data[13] << 24) | (data[12] << 16) | (data[11] << 8) | data[10];
00311       return header_len + offset;
00312     }
00313   }
00314 
00315   return SIZE_MAX;
00316 }
00317 
00324 static bool CalcGRFMD5Sum(GRFConfig *config, Subdirectory subdir)
00325 {
00326   FILE *f;
00327   Md5 checksum;
00328   uint8 buffer[1024];
00329   size_t len, size;
00330 
00331   /* open the file */
00332   f = FioFOpenFile(config->filename, "rb", subdir, &size);
00333   if (f == NULL) return false;
00334 
00335   size_t start = ftell(f);
00336   size = min(size, GRFGetSizeOfDataSection(f));
00337   fseek(f, start, SEEK_SET);
00338 
00339   /* calculate md5sum */
00340   while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
00341     size -= len;
00342     checksum.Append(buffer, len);
00343   }
00344   checksum.Finish(config->ident.md5sum);
00345 
00346   FioFCloseFile(f);
00347 
00348   return true;
00349 }
00350 
00351 
00359 bool FillGRFDetails(GRFConfig *config, bool is_static, Subdirectory subdir)
00360 {
00361   if (!FioCheckFileExists(config->filename, subdir)) {
00362     config->status = GCS_NOT_FOUND;
00363     return false;
00364   }
00365 
00366   /* Find and load the Action 8 information */
00367   LoadNewGRFFile(config, CONFIG_SLOT, GLS_FILESCAN, subdir);
00368   config->SetSuitablePalette();
00369 
00370   /* Skip if the grfid is 0 (not read) or 0xFFFFFFFF (ttdp system grf) */
00371   if (config->ident.grfid == 0 || config->ident.grfid == 0xFFFFFFFF || config->IsOpenTTDBaseGRF()) return false;
00372 
00373   if (is_static) {
00374     /* Perform a 'safety scan' for static GRFs */
00375     LoadNewGRFFile(config, 62, GLS_SAFETYSCAN, subdir);
00376 
00377     /* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
00378     if (HasBit(config->flags, GCF_UNSAFE)) return false;
00379   }
00380 
00381   return CalcGRFMD5Sum(config, subdir);
00382 }
00383 
00384 
00390 void ClearGRFConfigList(GRFConfig **config)
00391 {
00392   GRFConfig *c, *next;
00393   for (c = *config; c != NULL; c = next) {
00394     next = c->next;
00395     delete c;
00396   }
00397   *config = NULL;
00398 }
00399 
00400 
00408 GRFConfig **CopyGRFConfigList(GRFConfig **dst, const GRFConfig *src, bool init_only)
00409 {
00410   /* Clear destination as it will be overwritten */
00411   ClearGRFConfigList(dst);
00412   for (; src != NULL; src = src->next) {
00413     GRFConfig *c = new GRFConfig(*src);
00414 
00415     ClrBit(c->flags, GCF_INIT_ONLY);
00416     if (init_only) SetBit(c->flags, GCF_INIT_ONLY);
00417 
00418     *dst = c;
00419     dst = &c->next;
00420   }
00421 
00422   return dst;
00423 }
00424 
00438 static void RemoveDuplicatesFromGRFConfigList(GRFConfig *list)
00439 {
00440   GRFConfig *prev;
00441   GRFConfig *cur;
00442 
00443   if (list == NULL) return;
00444 
00445   for (prev = list, cur = list->next; cur != NULL; prev = cur, cur = cur->next) {
00446     if (cur->ident.grfid != list->ident.grfid) continue;
00447 
00448     prev->next = cur->next;
00449     delete cur;
00450     cur = prev; // Just go back one so it continues as normal later on
00451   }
00452 
00453   RemoveDuplicatesFromGRFConfigList(list->next);
00454 }
00455 
00460 void AppendStaticGRFConfigs(GRFConfig **dst)
00461 {
00462   GRFConfig **tail = dst;
00463   while (*tail != NULL) tail = &(*tail)->next;
00464 
00465   CopyGRFConfigList(tail, _grfconfig_static, false);
00466   RemoveDuplicatesFromGRFConfigList(*dst);
00467 }
00468 
00474 void AppendToGRFConfigList(GRFConfig **dst, GRFConfig *el)
00475 {
00476   GRFConfig **tail = dst;
00477   while (*tail != NULL) tail = &(*tail)->next;
00478   *tail = el;
00479 
00480   RemoveDuplicatesFromGRFConfigList(*dst);
00481 }
00482 
00483 
00485 void ResetGRFConfig(bool defaults)
00486 {
00487   CopyGRFConfigList(&_grfconfig, _grfconfig_newgame, !defaults);
00488   AppendStaticGRFConfigs(&_grfconfig);
00489 }
00490 
00491 
00503 GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
00504 {
00505   GRFListCompatibility res = GLC_ALL_GOOD;
00506 
00507   for (GRFConfig *c = grfconfig; c != NULL; c = c->next) {
00508     const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
00509     if (f == NULL || HasBit(f->flags, GCF_INVALID)) {
00510       char buf[256];
00511 
00512       /* If we have not found the exactly matching GRF try to find one with the
00513        * same grfid, as it most likely is compatible */
00514       f = FindGRFConfig(c->ident.grfid, FGCM_COMPATIBLE, NULL, c->version);
00515       if (f != NULL) {
00516         md5sumToString(buf, lastof(buf), c->ident.md5sum);
00517         DEBUG(grf, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c->ident.grfid), c->filename, buf);
00518         if (!HasBit(c->flags, GCF_COMPATIBLE)) {
00519           /* Preserve original_md5sum after it has been assigned */
00520           SetBit(c->flags, GCF_COMPATIBLE);
00521           memcpy(c->original_md5sum, c->ident.md5sum, sizeof(c->original_md5sum));
00522         }
00523 
00524         /* Non-found has precedence over compatibility load */
00525         if (res != GLC_NOT_FOUND) res = GLC_COMPATIBLE;
00526         goto compatible_grf;
00527       }
00528 
00529       /* No compatible grf was found, mark it as disabled */
00530       md5sumToString(buf, lastof(buf), c->ident.md5sum);
00531       DEBUG(grf, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c->ident.grfid), c->filename, buf);
00532 
00533       c->status = GCS_NOT_FOUND;
00534       res = GLC_NOT_FOUND;
00535     } else {
00536 compatible_grf:
00537       DEBUG(grf, 1, "Loading GRF %08X from %s", BSWAP32(f->ident.grfid), f->filename);
00538       /* The filename could be the filename as in the savegame. As we need
00539        * to load the GRF here, we need the correct filename, so overwrite that
00540        * in any case and set the name and info when it is not set already.
00541        * When the GCF_COPY flag is set, it is certain that the filename is
00542        * already a local one, so there is no need to replace it. */
00543       if (!HasBit(c->flags, GCF_COPY)) {
00544         free(c->filename);
00545         c->filename = strdup(f->filename);
00546         memcpy(c->ident.md5sum, f->ident.md5sum, sizeof(c->ident.md5sum));
00547         c->name->Release();
00548         c->name = f->name;
00549         c->name->AddRef();
00550         c->info->Release();
00551         c->info = f->name;
00552         c->info->AddRef();
00553         c->error = NULL;
00554         c->version = f->version;
00555         c->min_loadable_version = f->min_loadable_version;
00556         c->num_valid_params = f->num_valid_params;
00557         c->has_param_defaults = f->has_param_defaults;
00558         for (uint i = 0; i < f->param_info.Length(); i++) {
00559           if (f->param_info[i] == NULL) {
00560             *c->param_info.Append() = NULL;
00561           } else {
00562             *c->param_info.Append() = new GRFParameterInfo(*f->param_info[i]);
00563           }
00564         }
00565       }
00566     }
00567   }
00568 
00569   return res;
00570 }
00571 
00573 class GRFFileScanner : FileScanner {
00574   uint next_update; 
00575   uint num_scanned; 
00576 
00577 public:
00578   GRFFileScanner() : next_update(_realtime_tick), num_scanned(0)
00579   {
00580   }
00581 
00582   /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename);
00583 
00585   static uint DoScan()
00586   {
00587     GRFFileScanner fs;
00588     int ret = fs.Scan(".grf", NEWGRF_DIR);
00589     /* The number scanned and the number returned may not be the same;
00590      * duplicate NewGRFs and base sets are ignored in the return value. */
00591     _settings_client.gui.last_newgrf_count = fs.num_scanned;
00592     return ret;
00593   }
00594 };
00595 
00596 bool GRFFileScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
00597 {
00598   GRFConfig *c = new GRFConfig(filename + basepath_length);
00599 
00600   bool added = true;
00601   if (FillGRFDetails(c, false)) {
00602     if (_all_grfs == NULL) {
00603       _all_grfs = c;
00604     } else {
00605       /* Insert file into list at a position determined by its
00606        * name, so the list is sorted as we go along */
00607       GRFConfig **pd, *d;
00608       bool stop = false;
00609       for (pd = &_all_grfs; (d = *pd) != NULL; pd = &d->next) {
00610         if (c->ident.grfid == d->ident.grfid && memcmp(c->ident.md5sum, d->ident.md5sum, sizeof(c->ident.md5sum)) == 0) added = false;
00611         /* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
00612          *  before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
00613          *  just after the first with the same name. Avoids doubles in the list. */
00614         if (strcasecmp(c->GetName(), d->GetName()) <= 0) {
00615           stop = true;
00616         } else if (stop) {
00617           break;
00618         }
00619       }
00620       if (added) {
00621         c->next = d;
00622         *pd = c;
00623       }
00624     }
00625   } else {
00626     added = false;
00627   }
00628 
00629   this->num_scanned++;
00630   if (this->next_update <= _realtime_tick) {
00631     _modal_progress_work_mutex->EndCritical();
00632     _modal_progress_paint_mutex->BeginCritical();
00633 
00634     const char *name = NULL;
00635     if (c->name != NULL) name = GetGRFStringFromGRFText(c->name->text);
00636     if (name == NULL) name = c->filename;
00637     UpdateNewGRFScanStatus(this->num_scanned, name);
00638 
00639     _modal_progress_work_mutex->BeginCritical();
00640     _modal_progress_paint_mutex->EndCritical();
00641 
00642     this->next_update = _realtime_tick + 200;
00643   }
00644 
00645   if (!added) {
00646     /* File couldn't be opened, or is either not a NewGRF or is a
00647      * 'system' NewGRF or it's already known, so forget about it. */
00648     delete c;
00649   }
00650 
00651   return added;
00652 }
00653 
00660 static int CDECL GRFSorter(GRFConfig * const *p1, GRFConfig * const *p2)
00661 {
00662   const GRFConfig *c1 = *p1;
00663   const GRFConfig *c2 = *p2;
00664 
00665   return strcasecmp(c1->GetName(), c2->GetName());
00666 }
00667 
00672 void DoScanNewGRFFiles(void *callback)
00673 {
00674   _modal_progress_work_mutex->BeginCritical();
00675 
00676   ClearGRFConfigList(&_all_grfs);
00677   TarScanner::DoScan(TarScanner::NEWGRF);
00678 
00679   DEBUG(grf, 1, "Scanning for NewGRFs");
00680   uint num = GRFFileScanner::DoScan();
00681 
00682   DEBUG(grf, 1, "Scan complete, found %d files", num);
00683   if (num != 0 && _all_grfs != NULL) {
00684     /* Sort the linked list using quicksort.
00685     * For that we first have to make an array, then sort and
00686     * then remake the linked list. */
00687     GRFConfig **to_sort = MallocT<GRFConfig*>(num);
00688 
00689     uint i = 0;
00690     for (GRFConfig *p = _all_grfs; p != NULL; p = p->next, i++) {
00691       to_sort[i] = p;
00692     }
00693     /* Number of files is not necessarily right */
00694     num = i;
00695 
00696     QSortT(to_sort, num, &GRFSorter);
00697 
00698     for (i = 1; i < num; i++) {
00699       to_sort[i - 1]->next = to_sort[i];
00700     }
00701     to_sort[num - 1]->next = NULL;
00702     _all_grfs = to_sort[0];
00703 
00704     free(to_sort);
00705 
00706 #ifdef ENABLE_NETWORK
00707     NetworkAfterNewGRFScan();
00708 #endif
00709   }
00710 
00711   _modal_progress_work_mutex->EndCritical();
00712   _modal_progress_paint_mutex->BeginCritical();
00713 
00714   /* Yes... these are the NewGRF windows */
00715   InvalidateWindowClassesData(WC_SAVELOAD, 0, true);
00716   InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE, GOID_NEWGRF_RESCANNED, true);
00717   if (callback != NULL) ((NewGRFScanCallback*)callback)->OnNewGRFsScanned();
00718 
00719   DeleteWindowByClass(WC_MODAL_PROGRESS);
00720   SetModalProgress(false);
00721   MarkWholeScreenDirty();
00722   _modal_progress_paint_mutex->EndCritical();
00723 }
00724 
00729 void ScanNewGRFFiles(NewGRFScanCallback *callback)
00730 {
00731   /* First set the modal progress. This ensures that it will eventually let go of the paint mutex. */
00732   SetModalProgress(true);
00733   /* Only then can we really start, especially by marking the whole screen dirty. Get those other windows hidden!. */
00734   MarkWholeScreenDirty();
00735 
00736   if (!_video_driver->HasGUI() || !ThreadObject::New(&DoScanNewGRFFiles, callback, NULL)) {
00737     _modal_progress_work_mutex->EndCritical();
00738     _modal_progress_paint_mutex->EndCritical();
00739     DoScanNewGRFFiles(callback);
00740     _modal_progress_paint_mutex->BeginCritical();
00741     _modal_progress_work_mutex->BeginCritical();
00742   } else {
00743     UpdateNewGRFScanStatus(0, NULL);
00744   }
00745 }
00746 
00755 const GRFConfig *FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
00756 {
00757   assert((mode == FGCM_EXACT) != (md5sum == NULL));
00758   const GRFConfig *best = NULL;
00759   for (const GRFConfig *c = _all_grfs; c != NULL; c = c->next) {
00760     /* if md5sum is set, we look for an exact match and continue if not found */
00761     if (!c->ident.HasGrfIdentifier(grfid, md5sum)) continue;
00762     /* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
00763     if (md5sum != NULL || mode == FGCM_ANY) return c;
00764     /* Skip incompatible stuff, unless explicitly allowed */
00765     if (mode != FGCM_NEWEST && HasBit(c->flags, GCF_INVALID)) continue;
00766     /* check version compatibility */
00767     if (mode == FGCM_COMPATIBLE && (c->version < desired_version || c->min_loadable_version > desired_version)) continue;
00768     /* remember the newest one as "the best" */
00769     if (best == NULL || c->version > best->version) best = c;
00770   }
00771 
00772   return best;
00773 }
00774 
00775 #ifdef ENABLE_NETWORK
00776 
00778 struct UnknownGRF : public GRFIdentifier {
00779   UnknownGRF *next;     
00780   GRFTextWrapper *name; 
00781 };
00782 
00800 GRFTextWrapper *FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
00801 {
00802   UnknownGRF *grf;
00803   static UnknownGRF *unknown_grfs = NULL;
00804 
00805   for (grf = unknown_grfs; grf != NULL; grf = grf->next) {
00806     if (grf->grfid == grfid) {
00807       if (memcmp(md5sum, grf->md5sum, sizeof(grf->md5sum)) == 0) return grf->name;
00808     }
00809   }
00810 
00811   if (!create) return NULL;
00812 
00813   grf = CallocT<UnknownGRF>(1);
00814   grf->grfid = grfid;
00815   grf->next  = unknown_grfs;
00816   grf->name = new GRFTextWrapper();
00817   grf->name->AddRef();
00818 
00819   AddGRFTextToList(&grf->name->text, UNKNOWN_GRF_NAME_PLACEHOLDER);
00820   memcpy(grf->md5sum, md5sum, sizeof(grf->md5sum));
00821 
00822   unknown_grfs = grf;
00823   return grf->name;
00824 }
00825 
00826 #endif /* ENABLE_NETWORK */
00827 
00828 
00835 GRFConfig *GetGRFConfig(uint32 grfid, uint32 mask)
00836 {
00837   GRFConfig *c;
00838 
00839   for (c = _grfconfig; c != NULL; c = c->next) {
00840     if ((c->ident.grfid & mask) == (grfid & mask)) return c;
00841   }
00842 
00843   return NULL;
00844 }
00845 
00846 
00848 char *GRFBuildParamList(char *dst, const GRFConfig *c, const char *last)
00849 {
00850   uint i;
00851 
00852   /* Return an empty string if there are no parameters */
00853   if (c->num_params == 0) return strecpy(dst, "", last);
00854 
00855   for (i = 0; i < c->num_params; i++) {
00856     if (i > 0) dst = strecpy(dst, " ", last);
00857     dst += seprintf(dst, last, "%d", c->param[i]);
00858   }
00859   return dst;
00860 }
00861 
00863 static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
00864 
00869 bool GRFConfig::IsOpenTTDBaseGRF() const
00870 {
00871   return (this->ident.grfid & 0x00FFFFFF) == OPENTTD_GRAPHICS_BASE_GRF_ID;
00872 }
00873 
00879 const char *GRFConfig::GetTextfile(TextfileType type) const
00880 {
00881   static const char * const prefixes[] = {
00882     "readme",
00883     "changelog",
00884     "license",
00885   };
00886   assert_compile(lengthof(prefixes) == TFT_END);
00887 
00888   const char *prefix = prefixes[type];
00889 
00890   if (this->filename == NULL) return NULL;
00891 
00892   static char file_path[MAX_PATH];
00893   strecpy(file_path, this->filename, lastof(file_path));
00894 
00895   char *slash = strrchr(file_path, PATHSEPCHAR);
00896   if (slash == NULL) return NULL;
00897 
00898   seprintf(slash + 1, lastof(file_path), "%s_%s.txt", prefix, GetCurrentLanguageIsoCode());
00899   if (FioCheckFileExists(file_path, NEWGRF_DIR)) return file_path;
00900 
00901   seprintf(slash + 1, lastof(file_path), "%s_%.2s.txt", prefix, GetCurrentLanguageIsoCode());
00902   if (FioCheckFileExists(file_path, NEWGRF_DIR)) return file_path;
00903 
00904   seprintf(slash + 1, lastof(file_path), "%s.txt", prefix);
00905   return FioCheckFileExists(file_path, NEWGRF_DIR) ? file_path : NULL;
00906 }