2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file newgrf_config.cpp Finding NewGRFs and configuring them. */
12 #include "3rdparty/md5/md5.h"
14 #include "network/network_func.h"
16 #include "newgrf_text.h"
17 #include "window_func.h"
19 #include "video/video_driver.hpp"
20 #include "strings_func.h"
21 #include "textfile_gui.h"
23 #include "newgrf_config.h"
25 #include "fileio_func.h"
28 #include "safeguards.h"
30 /** Create a new GRFTextWrapper. */
31 GRFTextWrapper::GRFTextWrapper() :
36 /** Cleanup a GRFTextWrapper object. */
37 GRFTextWrapper::~GRFTextWrapper()
39 CleanUpGRFText(this->text
);
43 * Create a new GRFConfig.
44 * @param filename Set the filename of this GRFConfig to filename. The argument
45 * is copied so the original string isn't needed after the constructor.
47 GRFConfig::GRFConfig(const char *filename
) :
48 name(new GRFTextWrapper()),
49 info(new GRFTextWrapper()),
50 url(new GRFTextWrapper()),
51 num_valid_params(lengthof(param
))
53 if (filename
!= nullptr) this->filename
= stredup(filename
);
60 * Create a new GRFConfig that is a deep copy of an existing config.
61 * @param config The GRFConfig object to make a copy of.
63 GRFConfig::GRFConfig(const GRFConfig
&config
) :
64 ZeroedMemoryAllocator(),
69 version(config
.version
),
70 min_loadable_version(config
.min_loadable_version
),
71 flags(config
.flags
& ~(1 << GCF_COPY
)),
72 status(config
.status
),
73 grf_bugs(config
.grf_bugs
),
74 num_params(config
.num_params
),
75 num_valid_params(config
.num_valid_params
),
76 palette(config
.palette
),
77 has_param_defaults(config
.has_param_defaults
)
79 MemCpyT
<uint8
>(this->original_md5sum
, config
.original_md5sum
, lengthof(this->original_md5sum
));
80 MemCpyT
<uint32
>(this->param
, config
.param
, lengthof(this->param
));
81 if (config
.filename
!= nullptr) this->filename
= stredup(config
.filename
);
85 if (config
.error
!= nullptr) this->error
= new GRFError(*config
.error
);
86 for (uint i
= 0; i
< config
.param_info
.size(); i
++) {
87 if (config
.param_info
[i
] == nullptr) {
88 this->param_info
.push_back(nullptr);
90 this->param_info
.push_back(new GRFParameterInfo(*config
.param_info
[i
]));
95 /** Cleanup a GRFConfig object. */
96 GRFConfig::~GRFConfig()
98 /* GCF_COPY as in NOT stredupped/alloced the filename */
99 if (!HasBit(this->flags
, GCF_COPY
)) {
100 free(this->filename
);
103 this->name
->Release();
104 this->info
->Release();
105 this->url
->Release();
107 for (uint i
= 0; i
< this->param_info
.size(); i
++) delete this->param_info
[i
];
111 * Copy the parameter information from the \a src config.
112 * @param src Source config.
114 void GRFConfig::CopyParams(const GRFConfig
&src
)
116 this->num_params
= src
.num_params
;
117 this->num_valid_params
= src
.num_valid_params
;
118 MemCpyT
<uint32
>(this->param
, src
.param
, lengthof(this->param
));
122 * Get the name of this grf. In case the name isn't known
123 * the filename is returned.
124 * @return The name of filename of this grf.
126 const char *GRFConfig::GetName() const
128 const char *name
= GetGRFStringFromGRFText(this->name
->text
);
129 return StrEmpty(name
) ? this->filename
: name
;
134 * @return A string with a description of this grf.
136 const char *GRFConfig::GetDescription() const
138 return GetGRFStringFromGRFText(this->info
->text
);
143 * @return A string with an url of this grf.
145 const char *GRFConfig::GetURL() const
147 return GetGRFStringFromGRFText(this->url
->text
);
150 /** Set the default value for all parameters as specified by action14. */
151 void GRFConfig::SetParameterDefaults()
153 this->num_params
= 0;
154 MemSetT
<uint32
>(this->param
, 0, lengthof(this->param
));
156 if (!this->has_param_defaults
) return;
158 for (uint i
= 0; i
< this->param_info
.size(); i
++) {
159 if (this->param_info
[i
] == nullptr) continue;
160 this->param_info
[i
]->SetValue(this, this->param_info
[i
]->def_value
);
165 * Set the palette of this GRFConfig to something suitable.
166 * That is either the setting coming from the NewGRF or
167 * the globally used palette.
169 void GRFConfig::SetSuitablePalette()
172 switch (this->palette
& GRFP_GRF_MASK
) {
173 case GRFP_GRF_DOS
: pal
= PAL_DOS
; break;
174 case GRFP_GRF_WINDOWS
: pal
= PAL_WINDOWS
; break;
175 default: pal
= _settings_client
.gui
.newgrf_default_palette
== 1 ? PAL_WINDOWS
: PAL_DOS
; break;
177 SB(this->palette
, GRFP_USE_BIT
, 1, pal
== PAL_WINDOWS
? GRFP_USE_WINDOWS
: GRFP_USE_DOS
);
181 * Finalize Action 14 info after file scan is finished.
183 void GRFConfig::FinalizeParameterInfo()
185 for (GRFParameterInfo
*info
: this->param_info
) {
186 if (info
== nullptr) continue;
191 GRFConfig
*_all_grfs
;
192 GRFConfig
*_grfconfig
;
193 GRFConfig
*_grfconfig_newgame
;
194 GRFConfig
*_grfconfig_static
;
195 uint _missing_extra_graphics
= 0;
198 * Construct a new GRFError.
199 * @param severity The severity of this error.
200 * @param message The actual error-string.
202 GRFError::GRFError(StringID severity
, StringID message
) :
209 * Create a new GRFError that is a deep copy of an existing error message.
210 * @param error The GRFError object to make a copy of.
212 GRFError::GRFError(const GRFError
&error
) :
213 ZeroedMemoryAllocator(),
214 custom_message(error
.custom_message
),
216 message(error
.message
),
217 severity(error
.severity
)
219 if (error
.custom_message
!= nullptr) this->custom_message
= stredup(error
.custom_message
);
220 if (error
.data
!= nullptr) this->data
= stredup(error
.data
);
221 memcpy(this->param_value
, error
.param_value
, sizeof(this->param_value
));
224 GRFError::~GRFError()
226 free(this->custom_message
);
231 * Create a new empty GRFParameterInfo object.
232 * @param nr The newgrf parameter that is changed.
234 GRFParameterInfo::GRFParameterInfo(uint nr
) :
237 type(PTYPE_UINT_ENUM
),
239 max_value(UINT32_MAX
),
244 complete_labels(false)
248 * Create a new GRFParameterInfo object that is a deep copy of an existing
249 * parameter info object.
250 * @param info The GRFParameterInfo object to make a copy of.
252 GRFParameterInfo::GRFParameterInfo(GRFParameterInfo
&info
) :
253 name(DuplicateGRFText(info
.name
)),
254 desc(DuplicateGRFText(info
.desc
)),
256 min_value(info
.min_value
),
257 max_value(info
.max_value
),
258 def_value(info
.def_value
),
259 param_nr(info
.param_nr
),
260 first_bit(info
.first_bit
),
261 num_bit(info
.num_bit
),
262 complete_labels(info
.complete_labels
)
264 for (uint i
= 0; i
< info
.value_names
.size(); i
++) {
265 SmallPair
<uint32
, GRFText
*> *data
= info
.value_names
.data() + i
;
266 this->value_names
.Insert(data
->first
, DuplicateGRFText(data
->second
));
270 /** Cleanup all parameter info. */
271 GRFParameterInfo::~GRFParameterInfo()
273 CleanUpGRFText(this->name
);
274 CleanUpGRFText(this->desc
);
275 for (uint i
= 0; i
< this->value_names
.size(); i
++) {
276 SmallPair
<uint32
, GRFText
*> *data
= this->value_names
.data() + i
;
277 CleanUpGRFText(data
->second
);
282 * Get the value of this user-changeable parameter from the given config.
283 * @param config The GRFConfig to get the value from.
284 * @return The value of this parameter.
286 uint32
GRFParameterInfo::GetValue(struct GRFConfig
*config
) const
288 /* GB doesn't work correctly with nbits == 32, so handle that case here. */
289 if (this->num_bit
== 32) return config
->param
[this->param_nr
];
290 return GB(config
->param
[this->param_nr
], this->first_bit
, this->num_bit
);
294 * Set the value of this user-changeable parameter in the given config.
295 * @param config The GRFConfig to set the value in.
296 * @param value The new value.
298 void GRFParameterInfo::SetValue(struct GRFConfig
*config
, uint32 value
)
300 /* SB doesn't work correctly with nbits == 32, so handle that case here. */
301 if (this->num_bit
== 32) {
302 config
->param
[this->param_nr
] = value
;
304 SB(config
->param
[this->param_nr
], this->first_bit
, this->num_bit
, value
);
306 config
->num_params
= max
<uint
>(config
->num_params
, this->param_nr
+ 1);
307 SetWindowDirty(WC_GAME_OPTIONS
, WN_GAME_OPTIONS_NEWGRF_STATE
);
311 * Finalize Action 14 info after file scan is finished.
313 void GRFParameterInfo::Finalize()
315 this->complete_labels
= true;
316 for (uint32 value
= this->min_value
; value
<= this->max_value
; value
++) {
317 if (!this->value_names
.Contains(value
)) {
318 this->complete_labels
= false;
325 * Update the palettes of the graphics from the config file.
326 * Called when changing the default palette in advanced settings.
328 * @return Always true.
330 bool UpdateNewGRFConfigPalette(int32 p1
)
332 for (GRFConfig
*c
= _grfconfig_newgame
; c
!= nullptr; c
= c
->next
) c
->SetSuitablePalette();
333 for (GRFConfig
*c
= _grfconfig_static
; c
!= nullptr; c
= c
->next
) c
->SetSuitablePalette();
334 for (GRFConfig
*c
= _all_grfs
; c
!= nullptr; c
= c
->next
) c
->SetSuitablePalette();
339 * Get the data section size of a GRF.
341 * @return Size of the data section or SIZE_MAX if the file has no separate data section.
343 size_t GRFGetSizeOfDataSection(FILE *f
)
345 extern const byte _grf_cont_v2_sig
[];
346 static const uint header_len
= 14;
348 byte data
[header_len
];
349 if (fread(data
, 1, header_len
, f
) == header_len
) {
350 if (data
[0] == 0 && data
[1] == 0 && MemCmpT(data
+ 2, _grf_cont_v2_sig
, 8) == 0) {
351 /* Valid container version 2, get data section size. */
352 size_t offset
= ((size_t)data
[13] << 24) | ((size_t)data
[12] << 16) | ((size_t)data
[11] << 8) | (size_t)data
[10];
353 if (offset
>= 1 * 1024 * 1024 * 1024) {
354 DEBUG(grf
, 0, "Unexpectedly large offset for NewGRF");
355 /* Having more than 1 GiB of data is very implausible. Mostly because then
356 * all pools in OpenTTD are flooded already. Or it's just Action C all over.
357 * In any case, the offsets to graphics will likely not work either. */
360 return header_len
+ offset
;
368 * Calculate the MD5 sum for a GRF, and store it in the config.
369 * @param config GRF to compute.
370 * @param subdir The subdirectory to look in.
371 * @return MD5 sum was successfully computed
373 static bool CalcGRFMD5Sum(GRFConfig
*config
, Subdirectory subdir
)
381 f
= FioFOpenFile(config
->filename
, "rb", subdir
, &size
);
382 if (f
== nullptr) return false;
384 long start
= ftell(f
);
385 size
= min(size
, GRFGetSizeOfDataSection(f
));
387 if (start
< 0 || fseek(f
, start
, SEEK_SET
) < 0) {
392 /* calculate md5sum */
393 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, f
)) != 0 && size
!= 0) {
395 checksum
.Append(buffer
, len
);
397 checksum
.Finish(config
->ident
.md5sum
);
406 * Find the GRFID of a given grf, and calculate its md5sum.
407 * @param config grf to fill.
408 * @param is_static grf is static.
409 * @param subdir the subdirectory to search in.
410 * @return Operation was successfully completed.
412 bool FillGRFDetails(GRFConfig
*config
, bool is_static
, Subdirectory subdir
)
414 if (!FioCheckFileExists(config
->filename
, subdir
)) {
415 config
->status
= GCS_NOT_FOUND
;
419 /* Find and load the Action 8 information */
420 LoadNewGRFFile(config
, CONFIG_SLOT
, GLS_FILESCAN
, subdir
);
421 config
->SetSuitablePalette();
422 config
->FinalizeParameterInfo();
424 /* Skip if the grfid is 0 (not read) or if it is an internal GRF */
425 if (config
->ident
.grfid
== 0 || HasBit(config
->flags
, GCF_SYSTEM
)) return false;
428 /* Perform a 'safety scan' for static GRFs */
429 LoadNewGRFFile(config
, CONFIG_SLOT
, GLS_SAFETYSCAN
, subdir
);
431 /* GCF_UNSAFE is set if GLS_SAFETYSCAN finds unsafe actions */
432 if (HasBit(config
->flags
, GCF_UNSAFE
)) return false;
435 return CalcGRFMD5Sum(config
, subdir
);
440 * Clear a GRF Config list, freeing all nodes.
441 * @param config Start of the list.
442 * @post \a config is set to \c nullptr.
444 void ClearGRFConfigList(GRFConfig
**config
)
447 for (c
= *config
; c
!= nullptr; c
= next
) {
456 * Copy a GRF Config list
457 * @param dst pointer to destination list
458 * @param src pointer to source list values
459 * @param init_only the copied GRF will be processed up to GLS_INIT
460 * @return pointer to the last value added to the destination list
462 GRFConfig
**CopyGRFConfigList(GRFConfig
**dst
, const GRFConfig
*src
, bool init_only
)
464 /* Clear destination as it will be overwritten */
465 ClearGRFConfigList(dst
);
466 for (; src
!= nullptr; src
= src
->next
) {
467 GRFConfig
*c
= new GRFConfig(*src
);
469 ClrBit(c
->flags
, GCF_INIT_ONLY
);
470 if (init_only
) SetBit(c
->flags
, GCF_INIT_ONLY
);
480 * Removes duplicates from lists of GRFConfigs. These duplicates
481 * are introduced when the _grfconfig_static GRFs are appended
482 * to the _grfconfig on a newgame or savegame. As the parameters
483 * of the static GRFs could be different that the parameters of
484 * the ones used non-statically. This can result in desyncs in
485 * multiplayers, so the duplicate static GRFs have to be removed.
487 * This function _assumes_ that all static GRFs are placed after
488 * the non-static GRFs.
490 * @param list the list to remove the duplicates from
492 static void RemoveDuplicatesFromGRFConfigList(GRFConfig
*list
)
497 if (list
== nullptr) return;
499 for (prev
= list
, cur
= list
->next
; cur
!= nullptr; prev
= cur
, cur
= cur
->next
) {
500 if (cur
->ident
.grfid
!= list
->ident
.grfid
) continue;
502 prev
->next
= cur
->next
;
504 cur
= prev
; // Just go back one so it continues as normal later on
507 RemoveDuplicatesFromGRFConfigList(list
->next
);
511 * Appends the static GRFs to a list of GRFs
512 * @param dst the head of the list to add to
514 void AppendStaticGRFConfigs(GRFConfig
**dst
)
516 GRFConfig
**tail
= dst
;
517 while (*tail
!= nullptr) tail
= &(*tail
)->next
;
519 CopyGRFConfigList(tail
, _grfconfig_static
, false);
520 RemoveDuplicatesFromGRFConfigList(*dst
);
524 * Appends an element to a list of GRFs
525 * @param dst the head of the list to add to
526 * @param el the new tail to be
528 void AppendToGRFConfigList(GRFConfig
**dst
, GRFConfig
*el
)
530 GRFConfig
**tail
= dst
;
531 while (*tail
!= nullptr) tail
= &(*tail
)->next
;
534 RemoveDuplicatesFromGRFConfigList(*dst
);
538 /** Reset the current GRF Config to either blank or newgame settings. */
539 void ResetGRFConfig(bool defaults
)
541 CopyGRFConfigList(&_grfconfig
, _grfconfig_newgame
, !defaults
);
542 AppendStaticGRFConfigs(&_grfconfig
);
547 * Check if all GRFs in the GRF config from a savegame can be loaded.
548 * @param grfconfig GrfConfig to check
549 * @return will return any of the following 3 values:<br>
551 * <li> GLC_ALL_GOOD: No problems occurred, all GRF files were found and loaded
552 * <li> GLC_COMPATIBLE: For one or more GRF's no exact match was found, but a
553 * compatible GRF with the same grfid was found and used instead
554 * <li> GLC_NOT_FOUND: For one or more GRF's no match was found at all
557 GRFListCompatibility
IsGoodGRFConfigList(GRFConfig
*grfconfig
)
559 GRFListCompatibility res
= GLC_ALL_GOOD
;
561 for (GRFConfig
*c
= grfconfig
; c
!= nullptr; c
= c
->next
) {
562 const GRFConfig
*f
= FindGRFConfig(c
->ident
.grfid
, FGCM_EXACT
, c
->ident
.md5sum
);
563 if (f
== nullptr || HasBit(f
->flags
, GCF_INVALID
)) {
566 /* If we have not found the exactly matching GRF try to find one with the
567 * same grfid, as it most likely is compatible */
568 f
= FindGRFConfig(c
->ident
.grfid
, FGCM_COMPATIBLE
, nullptr, c
->version
);
570 md5sumToString(buf
, lastof(buf
), c
->ident
.md5sum
);
571 DEBUG(grf
, 1, "NewGRF %08X (%s) not found; checksum %s. Compatibility mode on", BSWAP32(c
->ident
.grfid
), c
->filename
, buf
);
572 if (!HasBit(c
->flags
, GCF_COMPATIBLE
)) {
573 /* Preserve original_md5sum after it has been assigned */
574 SetBit(c
->flags
, GCF_COMPATIBLE
);
575 memcpy(c
->original_md5sum
, c
->ident
.md5sum
, sizeof(c
->original_md5sum
));
578 /* Non-found has precedence over compatibility load */
579 if (res
!= GLC_NOT_FOUND
) res
= GLC_COMPATIBLE
;
583 /* No compatible grf was found, mark it as disabled */
584 md5sumToString(buf
, lastof(buf
), c
->ident
.md5sum
);
585 DEBUG(grf
, 0, "NewGRF %08X (%s) not found; checksum %s", BSWAP32(c
->ident
.grfid
), c
->filename
, buf
);
587 c
->status
= GCS_NOT_FOUND
;
591 DEBUG(grf
, 1, "Loading GRF %08X from %s", BSWAP32(f
->ident
.grfid
), f
->filename
);
592 /* The filename could be the filename as in the savegame. As we need
593 * to load the GRF here, we need the correct filename, so overwrite that
594 * in any case and set the name and info when it is not set already.
595 * When the GCF_COPY flag is set, it is certain that the filename is
596 * already a local one, so there is no need to replace it. */
597 if (!HasBit(c
->flags
, GCF_COPY
)) {
599 c
->filename
= stredup(f
->filename
);
600 memcpy(c
->ident
.md5sum
, f
->ident
.md5sum
, sizeof(c
->ident
.md5sum
));
608 c
->version
= f
->version
;
609 c
->min_loadable_version
= f
->min_loadable_version
;
610 c
->num_valid_params
= f
->num_valid_params
;
611 c
->has_param_defaults
= f
->has_param_defaults
;
612 for (uint i
= 0; i
< f
->param_info
.size(); i
++) {
613 if (f
->param_info
[i
] == nullptr) {
614 c
->param_info
.push_back(nullptr);
616 c
->param_info
.push_back(new GRFParameterInfo(*f
->param_info
[i
]));
626 /** Helper for scanning for files with GRF as extension */
627 class GRFFileScanner
: FileScanner
{
628 uint next_update
; ///< The next (realtime tick) we do update the screen.
629 uint num_scanned
; ///< The number of GRFs we have scanned.
632 GRFFileScanner() : next_update(_realtime_tick
), num_scanned(0)
636 bool AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
) override
;
638 /** Do the scan for GRFs. */
642 int ret
= fs
.Scan(".grf", NEWGRF_DIR
);
643 /* The number scanned and the number returned may not be the same;
644 * duplicate NewGRFs and base sets are ignored in the return value. */
645 _settings_client
.gui
.last_newgrf_count
= fs
.num_scanned
;
650 bool GRFFileScanner::AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
)
652 GRFConfig
*c
= new GRFConfig(filename
+ basepath_length
);
655 if (FillGRFDetails(c
, false)) {
656 if (_all_grfs
== nullptr) {
659 /* Insert file into list at a position determined by its
660 * name, so the list is sorted as we go along */
663 for (pd
= &_all_grfs
; (d
= *pd
) != nullptr; pd
= &d
->next
) {
664 if (c
->ident
.grfid
== d
->ident
.grfid
&& memcmp(c
->ident
.md5sum
, d
->ident
.md5sum
, sizeof(c
->ident
.md5sum
)) == 0) added
= false;
665 /* Because there can be multiple grfs with the same name, make sure we checked all grfs with the same name,
666 * before inserting the entry. So insert a new grf at the end of all grfs with the same name, instead of
667 * just after the first with the same name. Avoids doubles in the list. */
668 if (strcasecmp(c
->GetName(), d
->GetName()) <= 0) {
684 if (this->next_update
<= _realtime_tick
) {
685 _modal_progress_work_mutex
.unlock();
686 _modal_progress_paint_mutex
.lock();
688 const char *name
= nullptr;
689 if (c
->name
!= nullptr) name
= GetGRFStringFromGRFText(c
->name
->text
);
690 if (name
== nullptr) name
= c
->filename
;
691 UpdateNewGRFScanStatus(this->num_scanned
, name
);
693 _modal_progress_work_mutex
.lock();
694 _modal_progress_paint_mutex
.unlock();
696 this->next_update
= _realtime_tick
+ MODAL_PROGRESS_REDRAW_TIMEOUT
;
700 /* File couldn't be opened, or is either not a NewGRF or is a
701 * 'system' NewGRF or it's already known, so forget about it. */
709 * Simple sorter for GRFS
710 * @param c1 the first GRFConfig *
711 * @param c2 the second GRFConfig *
712 * @return true if the name of first NewGRF is before the name of the second.
714 static bool GRFSorter(GRFConfig
* const &c1
, GRFConfig
* const &c2
)
716 return strnatcmp(c1
->GetName(), c2
->GetName()) < 0;
720 * Really perform the scan for all NewGRFs.
721 * @param callback The callback to call after the scanning is complete.
723 void DoScanNewGRFFiles(NewGRFScanCallback
*callback
)
725 std::unique_lock
<std::mutex
> lock_work(_modal_progress_work_mutex
);
727 ClearGRFConfigList(&_all_grfs
);
728 TarScanner::DoScan(TarScanner::NEWGRF
);
730 DEBUG(grf
, 1, "Scanning for NewGRFs");
731 uint num
= GRFFileScanner::DoScan();
733 DEBUG(grf
, 1, "Scan complete, found %d files", num
);
734 if (num
!= 0 && _all_grfs
!= nullptr) {
735 /* Sort the linked list using quicksort.
736 * For that we first have to make an array, then sort and
737 * then remake the linked list. */
738 std::vector
<GRFConfig
*> to_sort
;
741 for (GRFConfig
*p
= _all_grfs
; p
!= nullptr; p
= p
->next
, i
++) {
742 to_sort
.push_back(p
);
744 /* Number of files is not necessarily right */
747 std::sort(to_sort
.begin(), to_sort
.end(), GRFSorter
);
749 for (i
= 1; i
< num
; i
++) {
750 to_sort
[i
- 1]->next
= to_sort
[i
];
752 to_sort
[num
- 1]->next
= nullptr;
753 _all_grfs
= to_sort
[0];
755 NetworkAfterNewGRFScan();
759 std::lock_guard
<std::mutex
> lock_paint(_modal_progress_paint_mutex
);
761 /* Yes... these are the NewGRF windows */
762 InvalidateWindowClassesData(WC_SAVELOAD
, 0, true);
763 InvalidateWindowData(WC_GAME_OPTIONS
, WN_GAME_OPTIONS_NEWGRF_STATE
, GOID_NEWGRF_RESCANNED
, true);
764 if (callback
!= nullptr) callback
->OnNewGRFsScanned();
766 DeleteWindowByClass(WC_MODAL_PROGRESS
);
767 SetModalProgress(false);
768 MarkWholeScreenDirty();
772 * Scan for all NewGRFs.
773 * @param callback The callback to call after the scanning is complete.
775 void ScanNewGRFFiles(NewGRFScanCallback
*callback
)
777 /* First set the modal progress. This ensures that it will eventually let go of the paint mutex. */
778 SetModalProgress(true);
779 /* Only then can we really start, especially by marking the whole screen dirty. Get those other windows hidden!. */
780 MarkWholeScreenDirty();
782 if (!UseThreadedModelProgress() || !VideoDriver::GetInstance()->HasGUI() || !StartNewThread(nullptr, "ottd:newgrf-scan", &DoScanNewGRFFiles
, (NewGRFScanCallback
*)callback
)) { // Without the seemingly superfluous cast, strange compiler errors ensue.
783 _modal_progress_work_mutex
.unlock();
784 _modal_progress_paint_mutex
.unlock();
785 DoScanNewGRFFiles(callback
);
786 _modal_progress_paint_mutex
.lock();
787 _modal_progress_work_mutex
.lock();
789 UpdateNewGRFScanStatus(0, nullptr);
794 * Find a NewGRF in the scanned list.
795 * @param grfid GRFID to look for,
796 * @param mode Restrictions for matching grfs
797 * @param md5sum Expected MD5 sum
798 * @param desired_version Requested version
799 * @return The matching grf, if it exists in #_all_grfs, else \c nullptr.
801 const GRFConfig
*FindGRFConfig(uint32 grfid
, FindGRFConfigMode mode
, const uint8
*md5sum
, uint32 desired_version
)
803 assert((mode
== FGCM_EXACT
) != (md5sum
== nullptr));
804 const GRFConfig
*best
= nullptr;
805 for (const GRFConfig
*c
= _all_grfs
; c
!= nullptr; c
= c
->next
) {
806 /* if md5sum is set, we look for an exact match and continue if not found */
807 if (!c
->ident
.HasGrfIdentifier(grfid
, md5sum
)) continue;
808 /* return it, if the exact same newgrf is found, or if we do not care about finding "the best" */
809 if (md5sum
!= nullptr || mode
== FGCM_ANY
) return c
;
810 /* Skip incompatible stuff, unless explicitly allowed */
811 if (mode
!= FGCM_NEWEST
&& HasBit(c
->flags
, GCF_INVALID
)) continue;
812 /* check version compatibility */
813 if (mode
== FGCM_COMPATIBLE
&& (c
->version
< desired_version
|| c
->min_loadable_version
> desired_version
)) continue;
814 /* remember the newest one as "the best" */
815 if (best
== nullptr || c
->version
> best
->version
) best
= c
;
821 /** Structure for UnknownGRFs; this is a lightweight variant of GRFConfig */
822 struct UnknownGRF
: public GRFIdentifier
{
823 UnknownGRF
*next
; ///< The next unknown GRF.
824 GRFTextWrapper
*name
; ///< Name of the GRF.
828 * Finds the name of a NewGRF in the list of names for unknown GRFs. An
829 * unknown GRF is a GRF where the .grf is not found during scanning.
831 * The names are resolved via UDP calls to servers that should know the name,
832 * though the replies may not come. This leaves "<Unknown>" as name, though
833 * that shouldn't matter _very_ much as they need GRF crawler or so to look
834 * up the GRF anyway and that works better with the GRF ID.
836 * @param grfid the GRF ID part of the 'unique' GRF identifier
837 * @param md5sum the MD5 checksum part of the 'unique' GRF identifier
838 * @param create whether to create a new GRFConfig if the GRFConfig did not
839 * exist in the fake list of GRFConfigs.
840 * @return The GRFTextWrapper of the name of the GRFConfig with the given GRF ID
841 * and MD5 checksum or nullptr when it does not exist and create is false.
842 * This value must NEVER be freed by the caller.
844 GRFTextWrapper
*FindUnknownGRFName(uint32 grfid
, uint8
*md5sum
, bool create
)
847 static UnknownGRF
*unknown_grfs
= nullptr;
849 for (grf
= unknown_grfs
; grf
!= nullptr; grf
= grf
->next
) {
850 if (grf
->grfid
== grfid
) {
851 if (memcmp(md5sum
, grf
->md5sum
, sizeof(grf
->md5sum
)) == 0) return grf
->name
;
855 if (!create
) return nullptr;
857 grf
= CallocT
<UnknownGRF
>(1);
859 grf
->next
= unknown_grfs
;
860 grf
->name
= new GRFTextWrapper();
863 AddGRFTextToList(&grf
->name
->text
, UNKNOWN_GRF_NAME_PLACEHOLDER
);
864 memcpy(grf
->md5sum
, md5sum
, sizeof(grf
->md5sum
));
871 * Retrieve a NewGRF from the current config by its grfid.
872 * @param grfid grf to look for.
873 * @param mask GRFID mask to allow for partial matching.
874 * @return The grf config, if it exists, else \c nullptr.
876 GRFConfig
*GetGRFConfig(uint32 grfid
, uint32 mask
)
880 for (c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
881 if ((c
->ident
.grfid
& mask
) == (grfid
& mask
)) return c
;
888 /** Build a string containing space separated parameter values, and terminate */
889 char *GRFBuildParamList(char *dst
, const GRFConfig
*c
, const char *last
)
893 /* Return an empty string if there are no parameters */
894 if (c
->num_params
== 0) return strecpy(dst
, "", last
);
896 for (i
= 0; i
< c
->num_params
; i
++) {
897 if (i
> 0) dst
= strecpy(dst
, " ", last
);
898 dst
+= seprintf(dst
, last
, "%d", c
->param
[i
]);
903 /** Base GRF ID for OpenTTD's base graphics GRFs. */
904 static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID
= BSWAP32(0xFF4F5400);
907 * Search a textfile file next to this NewGRF.
908 * @param type The type of the textfile to search for.
909 * @return The filename for the textfile, \c nullptr otherwise.
911 const char *GRFConfig::GetTextfile(TextfileType type
) const
913 return ::GetTextfile(type
, NEWGRF_DIR
, this->filename
);