Add: Overlay cargo icon in vehicle/depot list when holding shift+ctrl. (#12938)
[openttd-github.git] / src / newgrf.cpp
blob019e50cf2c86fd8e6f086f715078a91422c22ad4
1 /*
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/>.
6 */
8 /** @file newgrf.cpp Base of all NewGRF support. */
10 #include "stdafx.h"
12 #include "core/backup_type.hpp"
13 #include "core/container_func.hpp"
14 #include "debug.h"
15 #include "fileio_func.h"
16 #include "engine_func.h"
17 #include "engine_base.h"
18 #include "bridge.h"
19 #include "town.h"
20 #include "newgrf_engine.h"
21 #include "newgrf_text.h"
22 #include "fontcache.h"
23 #include "currency.h"
24 #include "landscape.h"
25 #include "newgrf_cargo.h"
26 #include "newgrf_house.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_station.h"
29 #include "industrytype.h"
30 #include "industry_map.h"
31 #include "newgrf_act5.h"
32 #include "newgrf_canal.h"
33 #include "newgrf_townname.h"
34 #include "newgrf_industries.h"
35 #include "newgrf_airporttiles.h"
36 #include "newgrf_airport.h"
37 #include "newgrf_object.h"
38 #include "rev.h"
39 #include "fios.h"
40 #include "strings_func.h"
41 #include "timer/timer_game_tick.h"
42 #include "timer/timer_game_calendar.h"
43 #include "string_func.h"
44 #include "network/core/config.h"
45 #include "smallmap_gui.h"
46 #include "genworld.h"
47 #include "error.h"
48 #include "error_func.h"
49 #include "vehicle_func.h"
50 #include "language.h"
51 #include "vehicle_base.h"
52 #include "road.h"
53 #include "newgrf_roadstop.h"
55 #include "table/strings.h"
56 #include "table/build_industry.h"
58 #include "safeguards.h"
60 /* TTDPatch extended GRF format codec
61 * (c) Petr Baudis 2004 (GPL'd)
62 * Changes by Florian octo Forster are (c) by the OpenTTD development team.
64 * Contains portions of documentation by TTDPatch team.
65 * Thanks especially to Josef Drexler for the documentation as well as a lot
66 * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
67 * served as subject to the initial testing of this codec. */
69 /** List of all loaded GRF files */
70 static std::vector<GRFFile *> _grf_files;
72 const std::vector<GRFFile *> &GetAllGRFFiles()
74 return _grf_files;
77 /** Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E */
78 uint8_t _misc_grf_features = 0;
80 /** 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */
81 static uint32_t _ttdpatch_flags[8];
83 /** Indicates which are the newgrf features currently loaded ingame */
84 GRFLoadedFeatures _loaded_newgrf_features;
86 static const uint MAX_SPRITEGROUP = UINT8_MAX; ///< Maximum GRF-local ID for a spritegroup.
88 /** Temporary data during loading of GRFs */
89 struct GrfProcessingState {
90 private:
91 /** Definition of a single Action1 spriteset */
92 struct SpriteSet {
93 SpriteID sprite; ///< SpriteID of the first sprite of the set.
94 uint num_sprites; ///< Number of sprites in the set.
97 /** Currently referenceable spritesets */
98 std::map<uint, SpriteSet> spritesets[GSF_END];
100 public:
101 /* Global state */
102 GrfLoadingStage stage; ///< Current loading stage
103 SpriteID spriteid; ///< First available SpriteID for loading realsprites.
105 /* Local state in the file */
106 SpriteFile *file; ///< File of currently processed GRF file.
107 GRFFile *grffile; ///< Currently processed GRF file.
108 GRFConfig *grfconfig; ///< Config of the currently processed GRF file.
109 uint32_t nfo_line; ///< Currently processed pseudo sprite number in the GRF.
111 /* Kind of return values when processing certain actions */
112 int skip_sprites; ///< Number of pseudo sprites to skip before processing the next one. (-1 to skip to end of file)
114 /* Currently referenceable spritegroups */
115 const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
117 /** Clear temporary data before processing the next file in the current loading stage */
118 void ClearDataForNextFile()
120 this->nfo_line = 0;
121 this->skip_sprites = 0;
123 for (uint i = 0; i < GSF_END; i++) {
124 this->spritesets[i].clear();
127 memset(this->spritegroups, 0, sizeof(this->spritegroups));
131 * Records new spritesets.
132 * @param feature GrfSpecFeature the set is defined for.
133 * @param first_sprite SpriteID of the first sprite in the set.
134 * @param first_set First spriteset to define.
135 * @param numsets Number of sets to define.
136 * @param numents Number of sprites per set to define.
138 void AddSpriteSets(uint8_t feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
140 assert(feature < GSF_END);
141 for (uint i = 0; i < numsets; i++) {
142 SpriteSet &set = this->spritesets[feature][first_set + i];
143 set.sprite = first_sprite + i * numents;
144 set.num_sprites = numents;
149 * Check whether there are any valid spritesets for a feature.
150 * @param feature GrfSpecFeature to check.
151 * @return true if there are any valid sets.
152 * @note Spritesets with zero sprites are valid to allow callback-failures.
154 bool HasValidSpriteSets(uint8_t feature) const
156 assert(feature < GSF_END);
157 return !this->spritesets[feature].empty();
161 * Check whether a specific set is defined.
162 * @param feature GrfSpecFeature to check.
163 * @param set Set to check.
164 * @return true if the set is valid.
165 * @note Spritesets with zero sprites are valid to allow callback-failures.
167 bool IsValidSpriteSet(uint8_t feature, uint set) const
169 assert(feature < GSF_END);
170 return this->spritesets[feature].find(set) != this->spritesets[feature].end();
174 * Returns the first sprite of a spriteset.
175 * @param feature GrfSpecFeature to query.
176 * @param set Set to query.
177 * @return First sprite of the set.
179 SpriteID GetSprite(uint8_t feature, uint set) const
181 assert(IsValidSpriteSet(feature, set));
182 return this->spritesets[feature].find(set)->second.sprite;
186 * Returns the number of sprites in a spriteset
187 * @param feature GrfSpecFeature to query.
188 * @param set Set to query.
189 * @return Number of sprites in the set.
191 uint GetNumEnts(uint8_t feature, uint set) const
193 assert(IsValidSpriteSet(feature, set));
194 return this->spritesets[feature].find(set)->second.num_sprites;
198 static GrfProcessingState _cur;
202 * Helper to check whether an image index is valid for a particular NewGRF vehicle.
203 * @tparam T The type of vehicle.
204 * @param image_index The image index to check.
205 * @return True iff the image index is valid, or 0xFD (use new graphics).
207 template <VehicleType T>
208 static inline bool IsValidNewGRFImageIndex(uint8_t image_index)
210 return image_index == 0xFD || IsValidImageIndex<T>(image_index);
213 class OTTDByteReaderSignal { };
215 /** Class to read from a NewGRF file */
216 class ByteReader {
217 protected:
218 uint8_t *data;
219 uint8_t *end;
221 public:
222 ByteReader(uint8_t *data, uint8_t *end) : data(data), end(end) { }
224 inline uint8_t *ReadBytes(size_t size)
226 if (data + size >= end) {
227 /* Put data at the end, as would happen if every byte had been individually read. */
228 data = end;
229 throw OTTDByteReaderSignal();
232 uint8_t *ret = data;
233 data += size;
234 return ret;
237 inline uint8_t ReadByte()
239 if (data < end) return *(data)++;
240 throw OTTDByteReaderSignal();
243 uint16_t ReadWord()
245 uint16_t val = ReadByte();
246 return val | (ReadByte() << 8);
249 uint16_t ReadExtendedByte()
251 uint16_t val = ReadByte();
252 return val == 0xFF ? ReadWord() : val;
255 uint32_t ReadDWord()
257 uint32_t val = ReadWord();
258 return val | (ReadWord() << 16);
261 uint32_t PeekDWord()
263 AutoRestoreBackup backup(this->data, this->data);
264 return this->ReadDWord();
267 uint32_t ReadVarSize(uint8_t size)
269 switch (size) {
270 case 1: return ReadByte();
271 case 2: return ReadWord();
272 case 4: return ReadDWord();
273 default:
274 NOT_REACHED();
275 return 0;
279 std::string_view ReadString()
281 char *string = reinterpret_cast<char *>(data);
282 size_t string_length = ttd_strnlen(string, Remaining());
284 /* Skip past the terminating NUL byte if it is present, but not more than remaining. */
285 Skip(std::min(string_length + 1, Remaining()));
287 return std::string_view(string, string_length);
290 inline size_t Remaining() const
292 return end - data;
295 inline bool HasData(size_t count = 1) const
297 return data + count <= end;
300 inline void Skip(size_t len)
302 data += len;
303 /* It is valid to move the buffer to exactly the end of the data,
304 * as there may not be any more data read. */
305 if (data > end) throw OTTDByteReaderSignal();
309 typedef void (*SpecialSpriteHandler)(ByteReader &buf);
311 /** The maximum amount of stations a single GRF is allowed to add */
312 static const uint NUM_STATIONS_PER_GRF = UINT16_MAX - 1;
314 /** Temporary engine data used when loading only */
315 struct GRFTempEngineData {
316 /** Summary state of refittability properties */
317 enum Refittability {
318 UNSET = 0, ///< No properties assigned. Default refit masks shall be activated.
319 EMPTY, ///< GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
320 NONEMPTY, ///< GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not available), disable the vehicle.
323 CargoClasses cargo_allowed;
324 CargoClasses cargo_disallowed;
325 RailTypeLabel railtypelabel;
326 uint8_t roadtramtype;
327 const GRFFile *defaultcargo_grf; ///< GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
328 Refittability refittability; ///< Did the newgrf set any refittability property? If not, default refittability will be applied.
329 uint8_t rv_max_speed; ///< Temporary storage of RV prop 15, maximum speed in mph/0.8
330 CargoTypes ctt_include_mask; ///< Cargo types always included in the refit mask.
331 CargoTypes ctt_exclude_mask; ///< Cargo types always excluded from the refit mask.
334 * Update the summary refittability on setting a refittability property.
335 * @param non_empty true if the GRF sets the vehicle to be refittable.
337 void UpdateRefittability(bool non_empty)
339 if (non_empty) {
340 this->refittability = NONEMPTY;
341 } else if (this->refittability == UNSET) {
342 this->refittability = EMPTY;
347 static std::vector<GRFTempEngineData> _gted; ///< Temporary engine data used during NewGRF loading
350 * Contains the GRF ID of the owner of a vehicle if it has been reserved.
351 * GRM for vehicles is only used if dynamic engine allocation is disabled,
352 * so 256 is the number of original engines. */
353 static uint32_t _grm_engines[256];
355 /** Contains the GRF ID of the owner of a cargo if it has been reserved */
356 static uint32_t _grm_cargoes[NUM_CARGO * 2];
358 struct GRFLocation {
359 uint32_t grfid;
360 uint32_t nfoline;
362 GRFLocation(uint32_t grfid, uint32_t nfoline) : grfid(grfid), nfoline(nfoline) { }
364 bool operator<(const GRFLocation &other) const
366 return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
369 bool operator == (const GRFLocation &other) const
371 return this->grfid == other.grfid && this->nfoline == other.nfoline;
375 static std::map<GRFLocation, std::pair<SpriteID, uint16_t>> _grm_sprites;
376 typedef std::map<GRFLocation, std::vector<uint8_t>> GRFLineToSpriteOverride;
377 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
380 * Debug() function dedicated to newGRF debugging messages
381 * Function is essentially the same as Debug(grf, severity, ...) with the
382 * addition of file:line information when parsing grf files.
383 * NOTE: for the above reason(s) GrfMsg() should ONLY be used for
384 * loading/parsing grf files, not for runtime debug messages as there
385 * is no file information available during that time.
386 * @param severity debugging severity level, see debug.h
387 * @param msg the message
389 void GrfMsgI(int severity, const std::string &msg)
391 Debug(grf, severity, "[{}:{}] {}", _cur.grfconfig->filename, _cur.nfo_line, msg);
395 * Obtain a NewGRF file by its grfID
396 * @param grfid The grfID to obtain the file for
397 * @return The file.
399 static GRFFile *GetFileByGRFID(uint32_t grfid)
401 for (GRFFile * const file : _grf_files) {
402 if (file->grfid == grfid) return file;
404 return nullptr;
408 * Obtain a NewGRF file by its filename
409 * @param filename The filename to obtain the file for.
410 * @return The file.
412 static GRFFile *GetFileByFilename(const std::string &filename)
414 for (GRFFile * const file : _grf_files) {
415 if (file->filename == filename) return file;
417 return nullptr;
420 /** Reset all NewGRFData that was used only while processing data */
421 static void ClearTemporaryNewGRFData(GRFFile *gf)
423 gf->labels.clear();
427 * Disable a GRF
428 * @param message Error message or STR_NULL.
429 * @param config GRFConfig to disable, nullptr for current.
430 * @return Error message of the GRF for further customisation.
432 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
434 GRFFile *file;
435 if (config != nullptr) {
436 file = GetFileByGRFID(config->ident.grfid);
437 } else {
438 config = _cur.grfconfig;
439 file = _cur.grffile;
442 config->status = GCS_DISABLED;
443 if (file != nullptr) ClearTemporaryNewGRFData(file);
444 if (config == _cur.grfconfig) _cur.skip_sprites = -1;
446 if (message == STR_NULL) return nullptr;
448 config->error = {STR_NEWGRF_ERROR_MSG_FATAL, message};
449 if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
450 return &config->error.value();
454 * Information for mapping static StringIDs.
456 struct StringIDMapping {
457 uint32_t grfid; ///< Source NewGRF.
458 StringID source; ///< Source StringID (GRF local).
459 std::function<void(StringID)> func; ///< Function for mapping result.
461 StringIDMapping(uint32_t grfid, StringID source, std::function<void(StringID)> &&func) : grfid(grfid), source(source), func(std::move(func)) { }
464 /** Strings to be mapped during load. */
465 static std::vector<StringIDMapping> _string_to_grf_mapping;
468 * Record a static StringID for getting translated later.
469 * @param source Source StringID (GRF local).
470 * @param func Function to call to set the mapping result.
472 static void AddStringForMapping(StringID source, std::function<void(StringID)> &&func)
474 func(STR_UNDEFINED);
475 _string_to_grf_mapping.emplace_back(_cur.grffile->grfid, source, std::move(func));
479 * Record a static StringID for getting translated later.
480 * @param source Source StringID (GRF local).
481 * @param target Destination for the mapping result.
483 static void AddStringForMapping(StringID source, StringID *target)
485 AddStringForMapping(source, [target](StringID str) { *target = str; });
489 * Perform a mapping from TTDPatch's string IDs to OpenTTD's
490 * string IDs, but only for the ones we are aware off; the rest
491 * like likely unused and will show a warning.
492 * @param str the string ID to convert
493 * @return the converted string ID
495 static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
497 /* StringID table for TextIDs 0x4E->0x6D */
498 static const StringID units_volume[] = {
499 STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
500 STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
501 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
502 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
503 STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
504 STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
505 STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
506 STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
509 /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
510 assert(!IsInsideMM(str, 0xD000, 0xD7FF));
512 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
513 static_assert(stringend - stringid == end - begin); \
514 if (str >= begin && str <= end) return str + (stringid - begin)
516 /* We have some changes in our cargo strings, resulting in some missing. */
517 TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
518 TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
519 if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
520 TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
521 TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
522 TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
524 /* Map building names according to our lang file changes. There are several
525 * ranges of house ids, all of which need to be remapped to allow newgrfs
526 * to use original house names. */
527 TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
528 TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
529 TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
531 /* Same thing for industries */
532 TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
533 TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
534 TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
535 TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
536 TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
538 switch (str) {
539 case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
540 case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
541 case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
543 #undef TEXTID_TO_STRINGID
545 if (str == STR_NULL) return STR_EMPTY;
547 Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
549 return STR_EMPTY;
553 * Used when setting an object's property to map to the GRF's strings
554 * while taking in consideration the "drift" between TTDPatch string system and OpenTTD's one
555 * @param grfid Id of the grf file.
556 * @param str StringID that we want to have the equivalent in OoenTTD.
557 * @return The properly adjusted StringID.
559 StringID MapGRFStringID(uint32_t grfid, StringID str)
561 if (IsInsideMM(str, 0xD800, 0x10000)) {
562 /* General text provided by NewGRF.
563 * In the specs this is called the 0xDCxx range (misc persistent texts),
564 * but we meanwhile extended the range to 0xD800-0xFFFF.
565 * Note: We are not involved in the "persistent" business, since we do not store
566 * any NewGRF strings in savegames. */
567 return GetGRFStringID(grfid, str);
568 } else if (IsInsideMM(str, 0xD000, 0xD800)) {
569 /* Callback text provided by NewGRF.
570 * In the specs this is called the 0xD0xx range (misc graphics texts).
571 * These texts can be returned by various callbacks.
573 * Due to how TTDP implements the GRF-local- to global-textid translation
574 * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
575 * We do not care about that difference and just mask out the 0x400 bit.
577 str &= ~0x400;
578 return GetGRFStringID(grfid, str);
579 } else {
580 /* The NewGRF wants to include/reference an original TTD string.
581 * Try our best to find an equivalent one. */
582 return TTDPStringIDToOTTDStringIDMapping(str);
586 static std::map<uint32_t, uint32_t> _grf_id_overrides;
589 * Set the override for a NewGRF
590 * @param source_grfid The grfID which wants to override another NewGRF.
591 * @param target_grfid The grfID which is being overridden.
593 static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
595 if (target_grfid == 0) {
596 _grf_id_overrides.erase(source_grfid);
597 GrfMsg(5, "SetNewGRFOverride: Removed override of 0x{:X}", BSWAP32(source_grfid));
598 } else {
599 _grf_id_overrides[source_grfid] = target_grfid;
600 GrfMsg(5, "SetNewGRFOverride: Added override of 0x{:X} to 0x{:X}", BSWAP32(source_grfid), BSWAP32(target_grfid));
605 * Returns the engine associated to a certain internal_id, resp. allocates it.
606 * @param file NewGRF that wants to change the engine.
607 * @param type Vehicle type.
608 * @param internal_id Engine ID inside the NewGRF.
609 * @param static_access If the engine is not present, return nullptr instead of allocating a new engine. (Used for static Action 0x04).
610 * @return The requested engine.
612 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access = false)
614 /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
615 * them use the same engine slots. */
616 uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
617 if (_settings_game.vehicle.dynamic_engines) {
618 /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
619 scope_grfid = file->grfid;
620 if (auto it = _grf_id_overrides.find(file->grfid); it != std::end(_grf_id_overrides)) {
621 scope_grfid = it->second;
622 const GRFFile *grf_match = GetFileByGRFID(scope_grfid);
623 if (grf_match == nullptr) {
624 GrfMsg(5, "Tried mapping from GRFID {:x} to {:x} but target is not loaded", BSWAP32(file->grfid), BSWAP32(scope_grfid));
625 } else {
626 GrfMsg(5, "Mapping from GRFID {:x} to {:x}", BSWAP32(file->grfid), BSWAP32(scope_grfid));
630 /* Check if the engine is registered in the override manager */
631 EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
632 if (engine != INVALID_ENGINE) {
633 Engine *e = Engine::Get(engine);
634 if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
635 return e;
639 /* Check if there is an unreserved slot */
640 EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
641 if (engine != INVALID_ENGINE) {
642 Engine *e = Engine::Get(engine);
644 if (e->grf_prop.grffile == nullptr) {
645 e->grf_prop.grffile = file;
646 GrfMsg(5, "Replaced engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
649 /* Reserve the engine slot */
650 if (!static_access) {
651 EngineIDMapping *eid = _engine_mngr.data() + engine;
652 eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
655 return e;
658 if (static_access) return nullptr;
660 if (!Engine::CanAllocateItem()) {
661 GrfMsg(0, "Can't allocate any more engines");
662 return nullptr;
665 size_t engine_pool_size = Engine::GetPoolSize();
667 /* ... it's not, so create a new one based off an existing engine */
668 Engine *e = new Engine(type, internal_id);
669 e->grf_prop.grffile = file;
671 /* Reserve the engine slot */
672 assert(_engine_mngr.size() == e->index);
673 _engine_mngr.push_back({
674 scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
675 internal_id,
676 type,
677 std::min<uint8_t>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
680 if (engine_pool_size != Engine::GetPoolSize()) {
681 /* Resize temporary engine data ... */
682 _gted.resize(Engine::GetPoolSize());
684 if (type == VEH_TRAIN) {
685 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
688 GrfMsg(5, "Created new engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
690 return e;
694 * Return the ID of a new engine
695 * @param file The NewGRF file providing the engine.
696 * @param type The Vehicle type.
697 * @param internal_id NewGRF-internal ID of the engine.
698 * @return The new EngineID.
699 * @note depending on the dynamic_engine setting and a possible override
700 * property the grfID may be unique or overwriting or partially re-defining
701 * properties of an existing engine.
703 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
705 uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
706 if (_settings_game.vehicle.dynamic_engines) {
707 scope_grfid = file->grfid;
708 if (auto it = _grf_id_overrides.find(file->grfid); it != std::end(_grf_id_overrides)) {
709 scope_grfid = it->second;
713 return _engine_mngr.GetID(type, internal_id, scope_grfid);
717 * Map the colour modifiers of TTDPatch to those that Open is using.
718 * @param grf_sprite Pointer to the structure been modified.
720 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
722 if (HasBit(grf_sprite->pal, 14)) {
723 ClrBit(grf_sprite->pal, 14);
724 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
727 if (HasBit(grf_sprite->sprite, 14)) {
728 ClrBit(grf_sprite->sprite, 14);
729 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
732 if (HasBit(grf_sprite->sprite, 15)) {
733 ClrBit(grf_sprite->sprite, 15);
734 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
739 * Read a sprite and a palette from the GRF and convert them into a format
740 * suitable to OpenTTD.
741 * @param buf Input stream.
742 * @param read_flags Whether to read TileLayoutFlags.
743 * @param invert_action1_flag Set to true, if palette bit 15 means 'not from action 1'.
744 * @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
745 * @param feature GrfSpecFeature to use spritesets from.
746 * @param[out] grf_sprite Read sprite and palette.
747 * @param[out] max_sprite_offset Optionally returns the number of sprites in the spriteset of the sprite. (0 if no spritset)
748 * @param[out] max_palette_offset Optionally returns the number of sprites in the spriteset of the palette. (0 if no spritset)
749 * @return Read TileLayoutFlags.
751 static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader &buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16_t *max_sprite_offset = nullptr, uint16_t *max_palette_offset = nullptr)
753 grf_sprite->sprite = buf.ReadWord();
754 grf_sprite->pal = buf.ReadWord();
755 TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf.ReadWord() : TLF_NOTHING;
757 MapSpriteMappingRecolour(grf_sprite);
759 bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
760 ClrBit(grf_sprite->pal, 15);
761 if (custom_sprite) {
762 /* Use sprite from Action 1 */
763 uint index = GB(grf_sprite->sprite, 0, 14);
764 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
765 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {}", index);
766 grf_sprite->sprite = SPR_IMG_QUERY;
767 grf_sprite->pal = PAL_NONE;
768 } else {
769 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
770 if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
771 SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
772 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
774 } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
775 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
776 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
777 return flags;
780 if (flags & TLF_CUSTOM_PALETTE) {
781 /* Use palette from Action 1 */
782 uint index = GB(grf_sprite->pal, 0, 14);
783 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
784 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {} for 'palette'", index);
785 grf_sprite->pal = PAL_NONE;
786 } else {
787 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
788 if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
789 SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
790 SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
792 } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
793 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
794 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
795 return flags;
798 return flags;
802 * Preprocess the TileLayoutFlags and read register modifiers from the GRF.
803 * @param buf Input stream.
804 * @param flags TileLayoutFlags to process.
805 * @param is_parent Whether the sprite is a parentsprite with a bounding box.
806 * @param dts Sprite layout to insert data into.
807 * @param index Sprite index to process; 0 for ground sprite.
809 static void ReadSpriteLayoutRegisters(ByteReader &buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
811 if (!(flags & TLF_DRAWING_FLAGS)) return;
813 if (dts->registers == nullptr) dts->AllocateRegisters();
814 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
815 regs.flags = flags & TLF_DRAWING_FLAGS;
817 if (flags & TLF_DODRAW) regs.dodraw = buf.ReadByte();
818 if (flags & TLF_SPRITE) regs.sprite = buf.ReadByte();
819 if (flags & TLF_PALETTE) regs.palette = buf.ReadByte();
821 if (is_parent) {
822 if (flags & TLF_BB_XY_OFFSET) {
823 regs.delta.parent[0] = buf.ReadByte();
824 regs.delta.parent[1] = buf.ReadByte();
826 if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf.ReadByte();
827 } else {
828 if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf.ReadByte();
829 if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf.ReadByte();
832 if (flags & TLF_SPRITE_VAR10) {
833 regs.sprite_var10 = buf.ReadByte();
834 if (regs.sprite_var10 > TLR_MAX_VAR10) {
835 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.sprite_var10, TLR_MAX_VAR10);
836 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
837 return;
841 if (flags & TLF_PALETTE_VAR10) {
842 regs.palette_var10 = buf.ReadByte();
843 if (regs.palette_var10 > TLR_MAX_VAR10) {
844 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.palette_var10, TLR_MAX_VAR10);
845 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
846 return;
852 * Read a spritelayout from the GRF.
853 * @param buf Input
854 * @param num_building_sprites Number of building sprites to read
855 * @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
856 * @param feature GrfSpecFeature to use spritesets from.
857 * @param allow_var10 Whether the spritelayout may specify var10 values for resolving multiple action-1-2-3 chains
858 * @param no_z_position Whether bounding boxes have no Z offset
859 * @param dts Layout container to output into
860 * @return True on error (GRF was disabled).
862 static bool ReadSpriteLayout(ByteReader &buf, uint num_building_sprites, bool use_cur_spritesets, uint8_t feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
864 bool has_flags = HasBit(num_building_sprites, 6);
865 ClrBit(num_building_sprites, 6);
866 TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
867 if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
868 dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
870 std::vector<uint16_t> max_sprite_offset(num_building_sprites + 1, 0);
871 std::vector<uint16_t> max_palette_offset(num_building_sprites + 1, 0);
873 /* Groundsprite */
874 TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset.data(), max_palette_offset.data());
875 if (_cur.skip_sprites < 0) return true;
877 if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
878 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x{:X} for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
879 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
880 return true;
883 ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
884 if (_cur.skip_sprites < 0) return true;
886 for (uint i = 0; i < num_building_sprites; i++) {
887 DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
889 flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset.data() + i + 1, max_palette_offset.data() + i + 1);
890 if (_cur.skip_sprites < 0) return true;
892 if (flags & ~valid_flags) {
893 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x{:X}", flags & ~valid_flags);
894 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
895 return true;
898 seq->delta_x = buf.ReadByte();
899 seq->delta_y = buf.ReadByte();
901 if (!no_z_position) seq->delta_z = buf.ReadByte();
903 if (seq->IsParentSprite()) {
904 seq->size_x = buf.ReadByte();
905 seq->size_y = buf.ReadByte();
906 seq->size_z = buf.ReadByte();
909 ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
910 if (_cur.skip_sprites < 0) return true;
913 /* Check if the number of sprites per spriteset is consistent */
914 bool is_consistent = true;
915 dts->consistent_max_offset = 0;
916 for (uint i = 0; i < num_building_sprites + 1; i++) {
917 if (max_sprite_offset[i] > 0) {
918 if (dts->consistent_max_offset == 0) {
919 dts->consistent_max_offset = max_sprite_offset[i];
920 } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
921 is_consistent = false;
922 break;
925 if (max_palette_offset[i] > 0) {
926 if (dts->consistent_max_offset == 0) {
927 dts->consistent_max_offset = max_palette_offset[i];
928 } else if (dts->consistent_max_offset != max_palette_offset[i]) {
929 is_consistent = false;
930 break;
935 /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
936 assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
938 if (!is_consistent || dts->registers != nullptr) {
939 dts->consistent_max_offset = 0;
940 if (dts->registers == nullptr) dts->AllocateRegisters();
942 for (uint i = 0; i < num_building_sprites + 1; i++) {
943 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
944 regs.max_sprite_offset = max_sprite_offset[i];
945 regs.max_palette_offset = max_palette_offset[i];
949 return false;
953 * Translate the refit mask. refit_mask is uint32_t as it has not been mapped to CargoTypes.
955 static CargoTypes TranslateRefitMask(uint32_t refit_mask)
957 CargoTypes result = 0;
958 for (uint8_t bit : SetBitIterator(refit_mask)) {
959 CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
960 if (IsValidCargoID(cargo)) SetBit(result, cargo);
962 return result;
966 * Converts TTD(P) Base Price pointers into the enum used by OTTD
967 * See http://wiki.ttdpatch.net/tiki-index.php?page=BaseCosts
968 * @param base_pointer TTD(P) Base Price Pointer
969 * @param error_location Function name for grf error messages
970 * @param[out] index If \a base_pointer is valid, \a index is assigned to the matching price; else it is left unchanged
972 static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
974 /* Special value for 'none' */
975 if (base_pointer == 0) {
976 *index = INVALID_PRICE;
977 return;
980 static const uint32_t start = 0x4B34; ///< Position of first base price
981 static const uint32_t size = 6; ///< Size of each base price record
983 if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
984 GrfMsg(1, "{}: Unsupported running cost base 0x{:04X}, ignoring", error_location, base_pointer);
985 return;
988 *index = (Price)((base_pointer - start) / size);
991 /** Possible return values for the FeatureChangeInfo functions */
992 enum ChangeInfoResult {
993 CIR_SUCCESS, ///< Variable was parsed and read
994 CIR_DISABLED, ///< GRF was disabled due to error
995 CIR_UNHANDLED, ///< Variable was parsed but unread
996 CIR_UNKNOWN, ///< Variable is unknown
997 CIR_INVALID_ID, ///< Attempt to modify an invalid ID
1000 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader &buf);
1003 * Define properties common to all vehicles
1004 * @param ei Engine info.
1005 * @param prop The property to change.
1006 * @param buf The property value.
1007 * @return ChangeInfoResult.
1009 static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader &buf)
1011 switch (prop) {
1012 case 0x00: // Introduction date
1013 ei->base_intro = buf.ReadWord() + CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1014 break;
1016 case 0x02: // Decay speed
1017 ei->decay_speed = buf.ReadByte();
1018 break;
1020 case 0x03: // Vehicle life
1021 ei->lifelength = buf.ReadByte();
1022 break;
1024 case 0x04: // Model life
1025 ei->base_life = buf.ReadByte();
1026 break;
1028 case 0x06: // Climates available
1029 ei->climates = buf.ReadByte();
1030 break;
1032 case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1033 /* Amount of cargo loaded during a vehicle's "loading tick" */
1034 ei->load_amount = buf.ReadByte();
1035 break;
1037 default:
1038 return CIR_UNKNOWN;
1041 return CIR_SUCCESS;
1045 * Define properties for rail vehicles
1046 * @param engine :ocal ID of the first vehicle.
1047 * @param numinfo Number of subsequent IDs to change the property for.
1048 * @param prop The property to change.
1049 * @param buf The property value.
1050 * @return ChangeInfoResult.
1052 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1054 ChangeInfoResult ret = CIR_SUCCESS;
1056 for (int i = 0; i < numinfo; i++) {
1057 Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1058 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1060 EngineInfo *ei = &e->info;
1061 RailVehicleInfo *rvi = &e->u.rail;
1063 switch (prop) {
1064 case 0x05: { // Track type
1065 uint8_t tracktype = buf.ReadByte();
1067 if (tracktype < _cur.grffile->railtype_list.size()) {
1068 _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1069 break;
1072 switch (tracktype) {
1073 case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_LABEL_ELECTRIC : RAILTYPE_LABEL_RAIL; break;
1074 case 1: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MONO; break;
1075 case 2: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MAGLEV; break;
1076 default:
1077 GrfMsg(1, "RailVehicleChangeInfo: Invalid track type {} specified, ignoring", tracktype);
1078 break;
1080 break;
1083 case 0x08: // AI passenger service
1084 /* Tells the AI that this engine is designed for
1085 * passenger services and shouldn't be used for freight. */
1086 rvi->ai_passenger_only = buf.ReadByte();
1087 break;
1089 case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1090 uint16_t speed = buf.ReadWord();
1091 if (speed == 0xFFFF) speed = 0;
1093 rvi->max_speed = speed;
1094 break;
1097 case PROP_TRAIN_POWER: // 0x0B Power
1098 rvi->power = buf.ReadWord();
1100 /* Set engine / wagon state based on power */
1101 if (rvi->power != 0) {
1102 if (rvi->railveh_type == RAILVEH_WAGON) {
1103 rvi->railveh_type = RAILVEH_SINGLEHEAD;
1105 } else {
1106 rvi->railveh_type = RAILVEH_WAGON;
1108 break;
1110 case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1111 rvi->running_cost = buf.ReadByte();
1112 break;
1114 case 0x0E: // Running cost base
1115 ConvertTTDBasePrice(buf.ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1116 break;
1118 case 0x12: { // Sprite ID
1119 uint8_t spriteid = buf.ReadByte();
1120 uint8_t orig_spriteid = spriteid;
1122 /* TTD sprite IDs point to a location in a 16bit array, but we use it
1123 * as an array index, so we need it to be half the original value. */
1124 if (spriteid < 0xFD) spriteid >>= 1;
1126 if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1127 rvi->image_index = spriteid;
1128 } else {
1129 GrfMsg(1, "RailVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1130 rvi->image_index = 0;
1132 break;
1135 case 0x13: { // Dual-headed
1136 uint8_t dual = buf.ReadByte();
1138 if (dual != 0) {
1139 rvi->railveh_type = RAILVEH_MULTIHEAD;
1140 } else {
1141 rvi->railveh_type = rvi->power == 0 ?
1142 RAILVEH_WAGON : RAILVEH_SINGLEHEAD;
1144 break;
1147 case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1148 rvi->capacity = buf.ReadByte();
1149 break;
1151 case 0x15: { // Cargo type
1152 _gted[e->index].defaultcargo_grf = _cur.grffile;
1153 uint8_t ctype = buf.ReadByte();
1155 if (ctype == 0xFF) {
1156 /* 0xFF is specified as 'use first refittable' */
1157 ei->cargo_type = INVALID_CARGO;
1158 } else if (_cur.grffile->grf_version >= 8) {
1159 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1160 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1161 } else if (ctype < NUM_CARGO) {
1162 /* Use untranslated cargo. */
1163 ei->cargo_type = ctype;
1164 } else {
1165 ei->cargo_type = INVALID_CARGO;
1166 GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1168 ei->cargo_label = CT_INVALID;
1169 break;
1172 case PROP_TRAIN_WEIGHT: // 0x16 Weight
1173 SB(rvi->weight, 0, 8, buf.ReadByte());
1174 break;
1176 case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1177 rvi->cost_factor = buf.ReadByte();
1178 break;
1180 case 0x18: // AI rank
1181 GrfMsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1182 buf.ReadByte();
1183 break;
1185 case 0x19: { // Engine traction type
1186 /* What do the individual numbers mean?
1187 * 0x00 .. 0x07: Steam
1188 * 0x08 .. 0x27: Diesel
1189 * 0x28 .. 0x31: Electric
1190 * 0x32 .. 0x37: Monorail
1191 * 0x38 .. 0x41: Maglev
1193 uint8_t traction = buf.ReadByte();
1194 EngineClass engclass;
1196 if (traction <= 0x07) {
1197 engclass = EC_STEAM;
1198 } else if (traction <= 0x27) {
1199 engclass = EC_DIESEL;
1200 } else if (traction <= 0x31) {
1201 engclass = EC_ELECTRIC;
1202 } else if (traction <= 0x37) {
1203 engclass = EC_MONORAIL;
1204 } else if (traction <= 0x41) {
1205 engclass = EC_MAGLEV;
1206 } else {
1207 break;
1210 if (_cur.grffile->railtype_list.empty()) {
1211 /* Use traction type to select between normal and electrified
1212 * rail only when no translation list is in place. */
1213 if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_RAIL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_ELECTRIC;
1214 if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_ELECTRIC && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_RAIL;
1217 rvi->engclass = engclass;
1218 break;
1221 case 0x1A: // Alter purchase list sort order
1222 AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1223 break;
1225 case 0x1B: // Powered wagons power bonus
1226 rvi->pow_wag_power = buf.ReadWord();
1227 break;
1229 case 0x1C: // Refit cost
1230 ei->refit_cost = buf.ReadByte();
1231 break;
1233 case 0x1D: { // Refit cargo
1234 uint32_t mask = buf.ReadDWord();
1235 _gted[e->index].UpdateRefittability(mask != 0);
1236 ei->refit_mask = TranslateRefitMask(mask);
1237 _gted[e->index].defaultcargo_grf = _cur.grffile;
1238 break;
1241 case 0x1E: // Callback
1242 SB(ei->callback_mask, 0, 8, buf.ReadByte());
1243 break;
1245 case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1246 rvi->tractive_effort = buf.ReadByte();
1247 break;
1249 case 0x20: // Air drag
1250 rvi->air_drag = buf.ReadByte();
1251 break;
1253 case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1254 rvi->shorten_factor = buf.ReadByte();
1255 break;
1257 case 0x22: // Visual effect
1258 rvi->visual_effect = buf.ReadByte();
1259 /* Avoid accidentally setting visual_effect to the default value
1260 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1261 if (rvi->visual_effect == VE_DEFAULT) {
1262 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1263 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1265 break;
1267 case 0x23: // Powered wagons weight bonus
1268 rvi->pow_wag_weight = buf.ReadByte();
1269 break;
1271 case 0x24: { // High byte of vehicle weight
1272 uint8_t weight = buf.ReadByte();
1274 if (weight > 4) {
1275 GrfMsg(2, "RailVehicleChangeInfo: Nonsensical weight of {} tons, ignoring", weight << 8);
1276 } else {
1277 SB(rvi->weight, 8, 8, weight);
1279 break;
1282 case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1283 rvi->user_def_data = buf.ReadByte();
1284 break;
1286 case 0x26: // Retire vehicle early
1287 ei->retire_early = buf.ReadByte();
1288 break;
1290 case 0x27: // Miscellaneous flags
1291 ei->misc_flags = buf.ReadByte();
1292 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1293 break;
1295 case 0x28: // Cargo classes allowed
1296 _gted[e->index].cargo_allowed = buf.ReadWord();
1297 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1298 _gted[e->index].defaultcargo_grf = _cur.grffile;
1299 break;
1301 case 0x29: // Cargo classes disallowed
1302 _gted[e->index].cargo_disallowed = buf.ReadWord();
1303 _gted[e->index].UpdateRefittability(false);
1304 break;
1306 case 0x2A: // Long format introduction date (days since year 0)
1307 ei->base_intro = buf.ReadDWord();
1308 break;
1310 case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1311 ei->cargo_age_period = buf.ReadWord();
1312 break;
1314 case 0x2C: // CTT refit include list
1315 case 0x2D: { // CTT refit exclude list
1316 uint8_t count = buf.ReadByte();
1317 _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1318 if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1319 CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1320 ctt = 0;
1321 while (count--) {
1322 CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1323 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1325 break;
1328 case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1329 rvi->curve_speed_mod = buf.ReadWord();
1330 break;
1332 case 0x2F: // Engine variant
1333 ei->variant_id = buf.ReadWord();
1334 break;
1336 case 0x30: // Extra miscellaneous flags
1337 ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1338 break;
1340 case 0x31: // Callback additional mask
1341 SB(ei->callback_mask, 8, 8, buf.ReadByte());
1342 break;
1344 default:
1345 ret = CommonVehicleChangeInfo(ei, prop, buf);
1346 break;
1350 return ret;
1354 * Define properties for road vehicles
1355 * @param engine Local ID of the first vehicle.
1356 * @param numinfo Number of subsequent IDs to change the property for.
1357 * @param prop The property to change.
1358 * @param buf The property value.
1359 * @return ChangeInfoResult.
1361 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1363 ChangeInfoResult ret = CIR_SUCCESS;
1365 for (int i = 0; i < numinfo; i++) {
1366 Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1367 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1369 EngineInfo *ei = &e->info;
1370 RoadVehicleInfo *rvi = &e->u.road;
1372 switch (prop) {
1373 case 0x05: // Road/tram type
1374 /* RoadTypeLabel is looked up later after the engine's road/tram
1375 * flag is set, however 0 means the value has not been set. */
1376 _gted[e->index].roadtramtype = buf.ReadByte() + 1;
1377 break;
1379 case 0x08: // Speed (1 unit is 0.5 kmh)
1380 rvi->max_speed = buf.ReadByte();
1381 break;
1383 case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1384 rvi->running_cost = buf.ReadByte();
1385 break;
1387 case 0x0A: // Running cost base
1388 ConvertTTDBasePrice(buf.ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1389 break;
1391 case 0x0E: { // Sprite ID
1392 uint8_t spriteid = buf.ReadByte();
1393 uint8_t orig_spriteid = spriteid;
1395 /* cars have different custom id in the GRF file */
1396 if (spriteid == 0xFF) spriteid = 0xFD;
1398 if (spriteid < 0xFD) spriteid >>= 1;
1400 if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1401 rvi->image_index = spriteid;
1402 } else {
1403 GrfMsg(1, "RoadVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1404 rvi->image_index = 0;
1406 break;
1409 case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1410 rvi->capacity = buf.ReadByte();
1411 break;
1413 case 0x10: { // Cargo type
1414 _gted[e->index].defaultcargo_grf = _cur.grffile;
1415 uint8_t ctype = buf.ReadByte();
1417 if (ctype == 0xFF) {
1418 /* 0xFF is specified as 'use first refittable' */
1419 ei->cargo_type = INVALID_CARGO;
1420 } else if (_cur.grffile->grf_version >= 8) {
1421 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1422 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1423 } else if (ctype < NUM_CARGO) {
1424 /* Use untranslated cargo. */
1425 ei->cargo_type = ctype;
1426 } else {
1427 ei->cargo_type = INVALID_CARGO;
1428 GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1430 ei->cargo_label = CT_INVALID;
1431 break;
1434 case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1435 rvi->cost_factor = buf.ReadByte();
1436 break;
1438 case 0x12: // SFX
1439 rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte());
1440 break;
1442 case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1443 rvi->power = buf.ReadByte();
1444 break;
1446 case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1447 rvi->weight = buf.ReadByte();
1448 break;
1450 case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1451 _gted[e->index].rv_max_speed = buf.ReadByte();
1452 break;
1454 case 0x16: { // Cargoes available for refitting
1455 uint32_t mask = buf.ReadDWord();
1456 _gted[e->index].UpdateRefittability(mask != 0);
1457 ei->refit_mask = TranslateRefitMask(mask);
1458 _gted[e->index].defaultcargo_grf = _cur.grffile;
1459 break;
1462 case 0x17: // Callback mask
1463 SB(ei->callback_mask, 0, 8, buf.ReadByte());
1464 break;
1466 case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1467 rvi->tractive_effort = buf.ReadByte();
1468 break;
1470 case 0x19: // Air drag
1471 rvi->air_drag = buf.ReadByte();
1472 break;
1474 case 0x1A: // Refit cost
1475 ei->refit_cost = buf.ReadByte();
1476 break;
1478 case 0x1B: // Retire vehicle early
1479 ei->retire_early = buf.ReadByte();
1480 break;
1482 case 0x1C: // Miscellaneous flags
1483 ei->misc_flags = buf.ReadByte();
1484 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1485 break;
1487 case 0x1D: // Cargo classes allowed
1488 _gted[e->index].cargo_allowed = buf.ReadWord();
1489 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1490 _gted[e->index].defaultcargo_grf = _cur.grffile;
1491 break;
1493 case 0x1E: // Cargo classes disallowed
1494 _gted[e->index].cargo_disallowed = buf.ReadWord();
1495 _gted[e->index].UpdateRefittability(false);
1496 break;
1498 case 0x1F: // Long format introduction date (days since year 0)
1499 ei->base_intro = buf.ReadDWord();
1500 break;
1502 case 0x20: // Alter purchase list sort order
1503 AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1504 break;
1506 case 0x21: // Visual effect
1507 rvi->visual_effect = buf.ReadByte();
1508 /* Avoid accidentally setting visual_effect to the default value
1509 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1510 if (rvi->visual_effect == VE_DEFAULT) {
1511 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1512 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1514 break;
1516 case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1517 ei->cargo_age_period = buf.ReadWord();
1518 break;
1520 case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1521 rvi->shorten_factor = buf.ReadByte();
1522 break;
1524 case 0x24: // CTT refit include list
1525 case 0x25: { // CTT refit exclude list
1526 uint8_t count = buf.ReadByte();
1527 _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1528 if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1529 CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1530 ctt = 0;
1531 while (count--) {
1532 CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1533 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1535 break;
1538 case 0x26: // Engine variant
1539 ei->variant_id = buf.ReadWord();
1540 break;
1542 case 0x27: // Extra miscellaneous flags
1543 ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1544 break;
1546 case 0x28: // Callback additional mask
1547 SB(ei->callback_mask, 8, 8, buf.ReadByte());
1548 break;
1550 default:
1551 ret = CommonVehicleChangeInfo(ei, prop, buf);
1552 break;
1556 return ret;
1560 * Define properties for ships
1561 * @param engine Local ID of the first vehicle.
1562 * @param numinfo Number of subsequent IDs to change the property for.
1563 * @param prop The property to change.
1564 * @param buf The property value.
1565 * @return ChangeInfoResult.
1567 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1569 ChangeInfoResult ret = CIR_SUCCESS;
1571 for (int i = 0; i < numinfo; i++) {
1572 Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1573 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1575 EngineInfo *ei = &e->info;
1576 ShipVehicleInfo *svi = &e->u.ship;
1578 switch (prop) {
1579 case 0x08: { // Sprite ID
1580 uint8_t spriteid = buf.ReadByte();
1581 uint8_t orig_spriteid = spriteid;
1583 /* ships have different custom id in the GRF file */
1584 if (spriteid == 0xFF) spriteid = 0xFD;
1586 if (spriteid < 0xFD) spriteid >>= 1;
1588 if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1589 svi->image_index = spriteid;
1590 } else {
1591 GrfMsg(1, "ShipVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1592 svi->image_index = 0;
1594 break;
1597 case 0x09: // Refittable
1598 svi->old_refittable = (buf.ReadByte() != 0);
1599 break;
1601 case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1602 svi->cost_factor = buf.ReadByte();
1603 break;
1605 case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h). Use 0x23 to achieve higher speeds.
1606 svi->max_speed = buf.ReadByte();
1607 break;
1609 case 0x0C: { // Cargo type
1610 _gted[e->index].defaultcargo_grf = _cur.grffile;
1611 uint8_t ctype = buf.ReadByte();
1613 if (ctype == 0xFF) {
1614 /* 0xFF is specified as 'use first refittable' */
1615 ei->cargo_type = INVALID_CARGO;
1616 } else if (_cur.grffile->grf_version >= 8) {
1617 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1618 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1619 } else if (ctype < NUM_CARGO) {
1620 /* Use untranslated cargo. */
1621 ei->cargo_type = ctype;
1622 } else {
1623 ei->cargo_type = INVALID_CARGO;
1624 GrfMsg(2, "ShipVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1626 ei->cargo_label = CT_INVALID;
1627 break;
1630 case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1631 svi->capacity = buf.ReadWord();
1632 break;
1634 case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1635 svi->running_cost = buf.ReadByte();
1636 break;
1638 case 0x10: // SFX
1639 svi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte());
1640 break;
1642 case 0x11: { // Cargoes available for refitting
1643 uint32_t mask = buf.ReadDWord();
1644 _gted[e->index].UpdateRefittability(mask != 0);
1645 ei->refit_mask = TranslateRefitMask(mask);
1646 _gted[e->index].defaultcargo_grf = _cur.grffile;
1647 break;
1650 case 0x12: // Callback mask
1651 SB(ei->callback_mask, 0, 8, buf.ReadByte());
1652 break;
1654 case 0x13: // Refit cost
1655 ei->refit_cost = buf.ReadByte();
1656 break;
1658 case 0x14: // Ocean speed fraction
1659 svi->ocean_speed_frac = buf.ReadByte();
1660 break;
1662 case 0x15: // Canal speed fraction
1663 svi->canal_speed_frac = buf.ReadByte();
1664 break;
1666 case 0x16: // Retire vehicle early
1667 ei->retire_early = buf.ReadByte();
1668 break;
1670 case 0x17: // Miscellaneous flags
1671 ei->misc_flags = buf.ReadByte();
1672 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1673 break;
1675 case 0x18: // Cargo classes allowed
1676 _gted[e->index].cargo_allowed = buf.ReadWord();
1677 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1678 _gted[e->index].defaultcargo_grf = _cur.grffile;
1679 break;
1681 case 0x19: // Cargo classes disallowed
1682 _gted[e->index].cargo_disallowed = buf.ReadWord();
1683 _gted[e->index].UpdateRefittability(false);
1684 break;
1686 case 0x1A: // Long format introduction date (days since year 0)
1687 ei->base_intro = buf.ReadDWord();
1688 break;
1690 case 0x1B: // Alter purchase list sort order
1691 AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1692 break;
1694 case 0x1C: // Visual effect
1695 svi->visual_effect = buf.ReadByte();
1696 /* Avoid accidentally setting visual_effect to the default value
1697 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1698 if (svi->visual_effect == VE_DEFAULT) {
1699 assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1700 SB(svi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1702 break;
1704 case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1705 ei->cargo_age_period = buf.ReadWord();
1706 break;
1708 case 0x1E: // CTT refit include list
1709 case 0x1F: { // CTT refit exclude list
1710 uint8_t count = buf.ReadByte();
1711 _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1712 if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1713 CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1714 ctt = 0;
1715 while (count--) {
1716 CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1717 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1719 break;
1722 case 0x20: // Engine variant
1723 ei->variant_id = buf.ReadWord();
1724 break;
1726 case 0x21: // Extra miscellaneous flags
1727 ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1728 break;
1730 case 0x22: // Callback additional mask
1731 SB(ei->callback_mask, 8, 8, buf.ReadByte());
1732 break;
1734 case 0x23: // Speed (1 unit is 0.5 km-ish/h)
1735 svi->max_speed = buf.ReadWord();
1736 break;
1738 case 0x24: // Acceleration (1 unit is 0.5 km-ish/h per tick)
1739 svi->acceleration = std::max<uint8_t>(1, buf.ReadByte());
1740 break;
1742 default:
1743 ret = CommonVehicleChangeInfo(ei, prop, buf);
1744 break;
1748 return ret;
1752 * Define properties for aircraft
1753 * @param engine Local ID of the aircraft.
1754 * @param numinfo Number of subsequent IDs to change the property for.
1755 * @param prop The property to change.
1756 * @param buf The property value.
1757 * @return ChangeInfoResult.
1759 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1761 ChangeInfoResult ret = CIR_SUCCESS;
1763 for (int i = 0; i < numinfo; i++) {
1764 Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1765 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1767 EngineInfo *ei = &e->info;
1768 AircraftVehicleInfo *avi = &e->u.air;
1770 switch (prop) {
1771 case 0x08: { // Sprite ID
1772 uint8_t spriteid = buf.ReadByte();
1773 uint8_t orig_spriteid = spriteid;
1775 /* aircraft have different custom id in the GRF file */
1776 if (spriteid == 0xFF) spriteid = 0xFD;
1778 if (spriteid < 0xFD) spriteid >>= 1;
1780 if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1781 avi->image_index = spriteid;
1782 } else {
1783 GrfMsg(1, "AircraftVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1784 avi->image_index = 0;
1786 break;
1789 case 0x09: // Helicopter
1790 if (buf.ReadByte() == 0) {
1791 avi->subtype = AIR_HELI;
1792 } else {
1793 SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1795 break;
1797 case 0x0A: // Large
1798 AssignBit(avi->subtype, 1, buf.ReadByte() != 0); // AIR_FAST
1799 break;
1801 case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1802 avi->cost_factor = buf.ReadByte();
1803 break;
1805 case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1806 avi->max_speed = (buf.ReadByte() * 128) / 10;
1807 break;
1809 case 0x0D: // Acceleration
1810 avi->acceleration = buf.ReadByte();
1811 break;
1813 case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1814 avi->running_cost = buf.ReadByte();
1815 break;
1817 case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1818 avi->passenger_capacity = buf.ReadWord();
1819 break;
1821 case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1822 avi->mail_capacity = buf.ReadByte();
1823 break;
1825 case 0x12: // SFX
1826 avi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte());
1827 break;
1829 case 0x13: { // Cargoes available for refitting
1830 uint32_t mask = buf.ReadDWord();
1831 _gted[e->index].UpdateRefittability(mask != 0);
1832 ei->refit_mask = TranslateRefitMask(mask);
1833 _gted[e->index].defaultcargo_grf = _cur.grffile;
1834 break;
1837 case 0x14: // Callback mask
1838 SB(ei->callback_mask, 0, 8, buf.ReadByte());
1839 break;
1841 case 0x15: // Refit cost
1842 ei->refit_cost = buf.ReadByte();
1843 break;
1845 case 0x16: // Retire vehicle early
1846 ei->retire_early = buf.ReadByte();
1847 break;
1849 case 0x17: // Miscellaneous flags
1850 ei->misc_flags = buf.ReadByte();
1851 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1852 break;
1854 case 0x18: // Cargo classes allowed
1855 _gted[e->index].cargo_allowed = buf.ReadWord();
1856 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1857 _gted[e->index].defaultcargo_grf = _cur.grffile;
1858 break;
1860 case 0x19: // Cargo classes disallowed
1861 _gted[e->index].cargo_disallowed = buf.ReadWord();
1862 _gted[e->index].UpdateRefittability(false);
1863 break;
1865 case 0x1A: // Long format introduction date (days since year 0)
1866 ei->base_intro = buf.ReadDWord();
1867 break;
1869 case 0x1B: // Alter purchase list sort order
1870 AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1871 break;
1873 case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1874 ei->cargo_age_period = buf.ReadWord();
1875 break;
1877 case 0x1D: // CTT refit include list
1878 case 0x1E: { // CTT refit exclude list
1879 uint8_t count = buf.ReadByte();
1880 _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1881 if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1882 CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1883 ctt = 0;
1884 while (count--) {
1885 CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1886 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1888 break;
1891 case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1892 avi->max_range = buf.ReadWord();
1893 break;
1895 case 0x20: // Engine variant
1896 ei->variant_id = buf.ReadWord();
1897 break;
1899 case 0x21: // Extra miscellaneous flags
1900 ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1901 break;
1903 case 0x22: // Callback additional mask
1904 SB(ei->callback_mask, 8, 8, buf.ReadByte());
1905 break;
1907 default:
1908 ret = CommonVehicleChangeInfo(ei, prop, buf);
1909 break;
1913 return ret;
1917 * Define properties for stations
1918 * @param stid StationID of the first station tile.
1919 * @param numinfo Number of subsequent station tiles to change the property for.
1920 * @param prop The property to change.
1921 * @param buf The property value.
1922 * @return ChangeInfoResult.
1924 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader &buf)
1926 ChangeInfoResult ret = CIR_SUCCESS;
1928 if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1929 GrfMsg(1, "StationChangeInfo: Station {} is invalid, max {}, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1930 return CIR_INVALID_ID;
1933 /* Allocate station specs if necessary */
1934 if (_cur.grffile->stations.size() < stid + numinfo) _cur.grffile->stations.resize(stid + numinfo);
1936 for (int i = 0; i < numinfo; i++) {
1937 auto &statspec = _cur.grffile->stations[stid + i];
1939 /* Check that the station we are modifying is defined. */
1940 if (statspec == nullptr && prop != 0x08) {
1941 GrfMsg(2, "StationChangeInfo: Attempt to modify undefined station {}, ignoring", stid + i);
1942 return CIR_INVALID_ID;
1945 switch (prop) {
1946 case 0x08: { // Class ID
1947 /* Property 0x08 is special; it is where the station is allocated */
1948 if (statspec == nullptr) {
1949 statspec = std::make_unique<StationSpec>();
1952 /* Swap classid because we read it in BE meaning WAYP or DFLT */
1953 uint32_t classid = buf.ReadDWord();
1954 statspec->class_index = StationClass::Allocate(BSWAP32(classid));
1955 break;
1958 case 0x09: { // Define sprite layout
1959 uint16_t tiles = buf.ReadExtendedByte();
1960 statspec->renderdata.clear(); // delete earlier loaded stuff
1961 statspec->renderdata.reserve(tiles);
1963 for (uint t = 0; t < tiles; t++) {
1964 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1965 dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1967 if (buf.HasData(4) && buf.PeekDWord() == 0) {
1968 buf.Skip(4);
1969 extern const DrawTileSprites _station_display_datas_rail[8];
1970 dts->Clone(&_station_display_datas_rail[t % 8]);
1971 continue;
1974 ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1975 /* On error, bail out immediately. Temporary GRF data was already freed */
1976 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1978 static std::vector<DrawTileSeqStruct> tmp_layout;
1979 tmp_layout.clear();
1980 for (;;) {
1981 /* no relative bounding box support */
1982 DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1983 MemSetT(&dtss, 0);
1985 dtss.delta_x = buf.ReadByte();
1986 if (dtss.IsTerminator()) break;
1987 dtss.delta_y = buf.ReadByte();
1988 dtss.delta_z = buf.ReadByte();
1989 dtss.size_x = buf.ReadByte();
1990 dtss.size_y = buf.ReadByte();
1991 dtss.size_z = buf.ReadByte();
1993 ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1994 /* On error, bail out immediately. Temporary GRF data was already freed */
1995 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1997 dts->Clone(tmp_layout.data());
2000 /* Number of layouts must be even, alternating X and Y */
2001 if (statspec->renderdata.size() & 1) {
2002 GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
2003 statspec->renderdata.pop_back();
2005 break;
2008 case 0x0A: { // Copy sprite layout
2009 uint16_t srcid = buf.ReadExtendedByte();
2010 const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
2012 if (srcstatspec == nullptr) {
2013 GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy sprite layout to {}.", srcid, stid + i);
2014 continue;
2017 statspec->renderdata.clear(); // delete earlier loaded stuff
2018 statspec->renderdata.reserve(srcstatspec->renderdata.size());
2020 for (const auto &it : srcstatspec->renderdata) {
2021 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2022 dts->Clone(&it);
2024 break;
2027 case 0x0B: // Callback mask
2028 statspec->callback_mask = buf.ReadByte();
2029 break;
2031 case 0x0C: // Disallowed number of platforms
2032 statspec->disallowed_platforms = buf.ReadByte();
2033 break;
2035 case 0x0D: // Disallowed platform lengths
2036 statspec->disallowed_lengths = buf.ReadByte();
2037 break;
2039 case 0x0E: // Define custom layout
2040 while (buf.HasData()) {
2041 uint8_t length = buf.ReadByte();
2042 uint8_t number = buf.ReadByte();
2044 if (length == 0 || number == 0) break;
2046 const uint8_t *buf_layout = buf.ReadBytes(length * number);
2048 /* Create entry in layouts and assign the layout to it. */
2049 auto &layout = statspec->layouts[GetStationLayoutKey(number, length)];
2050 layout.assign(buf_layout, buf_layout + length * number);
2052 /* Ensure the first bit, axis, is zero. The rest of the value is validated during rendering, as we don't know the range yet. */
2053 for (auto &tile : layout) {
2054 if ((tile & ~1U) != tile) {
2055 GrfMsg(1, "StationChangeInfo: Invalid tile {} in layout {}x{}", tile, length, number);
2056 tile &= ~1U;
2060 break;
2062 case 0x0F: { // Copy custom layout
2063 uint16_t srcid = buf.ReadExtendedByte();
2064 const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
2066 if (srcstatspec == nullptr) {
2067 GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy tile layout to {}.", srcid, stid + i);
2068 continue;
2071 statspec->layouts = srcstatspec->layouts;
2072 break;
2075 case 0x10: // Little/lots cargo threshold
2076 statspec->cargo_threshold = buf.ReadWord();
2077 break;
2079 case 0x11: { // Pylon placement
2080 uint8_t pylons = buf.ReadByte();
2081 if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8);
2082 for (int j = 0; j < 8; ++j) {
2083 if (HasBit(pylons, j)) {
2084 statspec->tileflags[j] |= StationSpec::TileFlags::Pylons;
2085 } else {
2086 statspec->tileflags[j] &= ~StationSpec::TileFlags::Pylons;
2089 break;
2092 case 0x12: // Cargo types for random triggers
2093 if (_cur.grffile->grf_version >= 7) {
2094 statspec->cargo_triggers = TranslateRefitMask(buf.ReadDWord());
2095 } else {
2096 statspec->cargo_triggers = (CargoTypes)buf.ReadDWord();
2098 break;
2100 case 0x13: // General flags
2101 statspec->flags = buf.ReadByte();
2102 break;
2104 case 0x14: { // Overhead wire placement
2105 uint8_t wires = buf.ReadByte();
2106 if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8);
2107 for (int j = 0; j < 8; ++j) {
2108 if (HasBit(wires, j)) {
2109 statspec->tileflags[j] |= StationSpec::TileFlags::NoWires;
2110 } else {
2111 statspec->tileflags[j] &= ~StationSpec::TileFlags::NoWires;
2114 break;
2117 case 0x15: { // Blocked tiles
2118 uint8_t blocked = buf.ReadByte();
2119 if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8);
2120 for (int j = 0; j < 8; ++j) {
2121 if (HasBit(blocked, j)) {
2122 statspec->tileflags[j] |= StationSpec::TileFlags::Blocked;
2123 } else {
2124 statspec->tileflags[j] &= ~StationSpec::TileFlags::Blocked;
2127 break;
2130 case 0x16: // Animation info
2131 statspec->animation.frames = buf.ReadByte();
2132 statspec->animation.status = buf.ReadByte();
2133 break;
2135 case 0x17: // Animation speed
2136 statspec->animation.speed = buf.ReadByte();
2137 break;
2139 case 0x18: // Animation triggers
2140 statspec->animation.triggers = buf.ReadWord();
2141 break;
2143 /* 0x19 road routing (not implemented) */
2145 case 0x1A: { // Advanced sprite layout
2146 uint16_t tiles = buf.ReadExtendedByte();
2147 statspec->renderdata.clear(); // delete earlier loaded stuff
2148 statspec->renderdata.reserve(tiles);
2150 for (uint t = 0; t < tiles; t++) {
2151 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2152 uint num_building_sprites = buf.ReadByte();
2153 /* On error, bail out immediately. Temporary GRF data was already freed */
2154 if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2157 /* Number of layouts must be even, alternating X and Y */
2158 if (statspec->renderdata.size() & 1) {
2159 GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
2160 statspec->renderdata.pop_back();
2162 break;
2165 case 0x1B: // Minimum bridge height (not implemented)
2166 buf.ReadWord();
2167 buf.ReadWord();
2168 buf.ReadWord();
2169 buf.ReadWord();
2170 break;
2172 case 0x1C: // Station Name
2173 AddStringForMapping(buf.ReadWord(), &statspec->name);
2174 break;
2176 case 0x1D: // Station Class name
2177 AddStringForMapping(buf.ReadWord(), [statspec = statspec.get()](StringID str) { StationClass::Get(statspec->class_index)->name = str; });
2178 break;
2180 case 0x1E: { // Extended tile flags (replaces prop 11, 14 and 15)
2181 uint16_t tiles = buf.ReadExtendedByte();
2182 auto flags = reinterpret_cast<const StationSpec::TileFlags *>(buf.ReadBytes(tiles));
2183 statspec->tileflags.assign(flags, flags + tiles);
2184 break;
2187 default:
2188 ret = CIR_UNKNOWN;
2189 break;
2193 return ret;
2197 * Define properties for water features
2198 * @param id Type of the first water feature.
2199 * @param numinfo Number of subsequent water feature ids to change the property for.
2200 * @param prop The property to change.
2201 * @param buf The property value.
2202 * @return ChangeInfoResult.
2204 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
2206 ChangeInfoResult ret = CIR_SUCCESS;
2208 if (id + numinfo > CF_END) {
2209 GrfMsg(1, "CanalChangeInfo: Canal feature 0x{:02X} is invalid, max {}, ignoring", id + numinfo, CF_END);
2210 return CIR_INVALID_ID;
2213 for (int i = 0; i < numinfo; i++) {
2214 CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2216 switch (prop) {
2217 case 0x08:
2218 cp->callback_mask = buf.ReadByte();
2219 break;
2221 case 0x09:
2222 cp->flags = buf.ReadByte();
2223 break;
2225 default:
2226 ret = CIR_UNKNOWN;
2227 break;
2231 return ret;
2235 * Define properties for bridges
2236 * @param brid BridgeID of the bridge.
2237 * @param numinfo Number of subsequent bridgeIDs to change the property for.
2238 * @param prop The property to change.
2239 * @param buf The property value.
2240 * @return ChangeInfoResult.
2242 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader &buf)
2244 ChangeInfoResult ret = CIR_SUCCESS;
2246 if (brid + numinfo > MAX_BRIDGES) {
2247 GrfMsg(1, "BridgeChangeInfo: Bridge {} is invalid, max {}, ignoring", brid + numinfo, MAX_BRIDGES);
2248 return CIR_INVALID_ID;
2251 for (int i = 0; i < numinfo; i++) {
2252 BridgeSpec *bridge = &_bridge[brid + i];
2254 switch (prop) {
2255 case 0x08: { // Year of availability
2256 /* We treat '0' as always available */
2257 uint8_t year = buf.ReadByte();
2258 bridge->avail_year = (year > 0 ? CalendarTime::ORIGINAL_BASE_YEAR + year : 0);
2259 break;
2262 case 0x09: // Minimum length
2263 bridge->min_length = buf.ReadByte();
2264 break;
2266 case 0x0A: // Maximum length
2267 bridge->max_length = buf.ReadByte();
2268 if (bridge->max_length > 16) bridge->max_length = UINT16_MAX;
2269 break;
2271 case 0x0B: // Cost factor
2272 bridge->price = buf.ReadByte();
2273 break;
2275 case 0x0C: // Maximum speed
2276 bridge->speed = buf.ReadWord();
2277 if (bridge->speed == 0) bridge->speed = UINT16_MAX;
2278 break;
2280 case 0x0D: { // Bridge sprite tables
2281 uint8_t tableid = buf.ReadByte();
2282 uint8_t numtables = buf.ReadByte();
2284 if (bridge->sprite_table == nullptr) {
2285 /* Allocate memory for sprite table pointers and zero out */
2286 bridge->sprite_table = CallocT<PalSpriteID*>(7);
2289 for (; numtables-- != 0; tableid++) {
2290 if (tableid >= 7) { // skip invalid data
2291 GrfMsg(1, "BridgeChangeInfo: Table {} >= 7, skipping", tableid);
2292 for (uint8_t sprite = 0; sprite < 32; sprite++) buf.ReadDWord();
2293 continue;
2296 if (bridge->sprite_table[tableid] == nullptr) {
2297 bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2300 for (uint8_t sprite = 0; sprite < 32; sprite++) {
2301 SpriteID image = buf.ReadWord();
2302 PaletteID pal = buf.ReadWord();
2304 bridge->sprite_table[tableid][sprite].sprite = image;
2305 bridge->sprite_table[tableid][sprite].pal = pal;
2307 MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2310 break;
2313 case 0x0E: // Flags; bit 0 - disable far pillars
2314 bridge->flags = buf.ReadByte();
2315 break;
2317 case 0x0F: // Long format year of availability (year since year 0)
2318 bridge->avail_year = Clamp(TimerGameCalendar::Year(buf.ReadDWord()), CalendarTime::MIN_YEAR, CalendarTime::MAX_YEAR);
2319 break;
2321 case 0x10: { // purchase string
2322 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf.ReadWord());
2323 if (newone != STR_UNDEFINED) bridge->material = newone;
2324 break;
2327 case 0x11: // description of bridge with rails or roads
2328 case 0x12: {
2329 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf.ReadWord());
2330 if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2331 break;
2334 case 0x13: // 16 bits cost multiplier
2335 bridge->price = buf.ReadWord();
2336 break;
2338 default:
2339 ret = CIR_UNKNOWN;
2340 break;
2344 return ret;
2348 * Ignore a house property
2349 * @param prop Property to read.
2350 * @param buf Property value.
2351 * @return ChangeInfoResult.
2353 static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader &buf)
2355 ChangeInfoResult ret = CIR_SUCCESS;
2357 switch (prop) {
2358 case 0x09:
2359 case 0x0B:
2360 case 0x0C:
2361 case 0x0D:
2362 case 0x0E:
2363 case 0x0F:
2364 case 0x11:
2365 case 0x14:
2366 case 0x15:
2367 case 0x16:
2368 case 0x18:
2369 case 0x19:
2370 case 0x1A:
2371 case 0x1B:
2372 case 0x1C:
2373 case 0x1D:
2374 case 0x1F:
2375 buf.ReadByte();
2376 break;
2378 case 0x0A:
2379 case 0x10:
2380 case 0x12:
2381 case 0x13:
2382 case 0x21:
2383 case 0x22:
2384 buf.ReadWord();
2385 break;
2387 case 0x1E:
2388 buf.ReadDWord();
2389 break;
2391 case 0x17:
2392 for (uint j = 0; j < 4; j++) buf.ReadByte();
2393 break;
2395 case 0x20: {
2396 uint8_t count = buf.ReadByte();
2397 for (uint8_t j = 0; j < count; j++) buf.ReadByte();
2398 break;
2401 case 0x23:
2402 buf.Skip(buf.ReadByte() * 2);
2403 break;
2405 default:
2406 ret = CIR_UNKNOWN;
2407 break;
2409 return ret;
2413 * Define properties for houses
2414 * @param hid HouseID of the house.
2415 * @param numinfo Number of subsequent houseIDs to change the property for.
2416 * @param prop The property to change.
2417 * @param buf The property value.
2418 * @return ChangeInfoResult.
2420 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader &buf)
2422 ChangeInfoResult ret = CIR_SUCCESS;
2424 if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2425 GrfMsg(1, "TownHouseChangeInfo: Too many houses loaded ({}), max ({}). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2426 return CIR_INVALID_ID;
2429 /* Allocate house specs if they haven't been allocated already. */
2430 if (_cur.grffile->housespec.size() < hid + numinfo) _cur.grffile->housespec.resize(hid + numinfo);
2432 for (int i = 0; i < numinfo; i++) {
2433 auto &housespec = _cur.grffile->housespec[hid + i];
2435 if (prop != 0x08 && housespec == nullptr) {
2436 /* If the house property 08 is not yet set, ignore this property */
2437 ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2438 if (cir > ret) ret = cir;
2439 continue;
2442 switch (prop) {
2443 case 0x08: { // Substitute building type, and definition of a new house
2444 uint8_t subs_id = buf.ReadByte();
2445 if (subs_id == 0xFF) {
2446 /* Instead of defining a new house, a substitute house id
2447 * of 0xFF disables the old house with the current id. */
2448 if (hid + i < NEW_HOUSE_OFFSET) HouseSpec::Get(hid + i)->enabled = false;
2449 continue;
2450 } else if (subs_id >= NEW_HOUSE_OFFSET) {
2451 /* The substitute id must be one of the original houses. */
2452 GrfMsg(2, "TownHouseChangeInfo: Attempt to use new house {} as substitute house for {}. Ignoring.", subs_id, hid + i);
2453 continue;
2456 /* Allocate space for this house. */
2457 if (housespec == nullptr) {
2458 /* Only the first property 08 setting copies properties; if you later change it, properties will stay. */
2459 housespec = std::make_unique<HouseSpec>(*HouseSpec::Get(subs_id));
2461 housespec->enabled = true;
2462 housespec->grf_prop.local_id = hid + i;
2463 housespec->grf_prop.subst_id = subs_id;
2464 housespec->grf_prop.grffile = _cur.grffile;
2465 /* Set default colours for randomization, used if not overridden. */
2466 housespec->random_colour[0] = COLOUR_RED;
2467 housespec->random_colour[1] = COLOUR_BLUE;
2468 housespec->random_colour[2] = COLOUR_ORANGE;
2469 housespec->random_colour[3] = COLOUR_GREEN;
2471 /* House flags 40 and 80 are exceptions; these flags are never set automatically. */
2472 housespec->building_flags &= ~(BUILDING_IS_CHURCH | BUILDING_IS_STADIUM);
2474 /* Make sure that the third cargo type is valid in this
2475 * climate. This can cause problems when copying the properties
2476 * of a house that accepts food, where the new house is valid
2477 * in the temperate climate. */
2478 CargoID cid = housespec->accepts_cargo[2];
2479 if (!IsValidCargoID(cid)) cid = GetCargoIDByLabel(housespec->accepts_cargo_label[2]);
2480 if (!IsValidCargoID(cid)) {
2481 housespec->cargo_acceptance[2] = 0;
2484 break;
2487 case 0x09: // Building flags
2488 housespec->building_flags = (BuildingFlags)buf.ReadByte();
2489 break;
2491 case 0x0A: { // Availability years
2492 uint16_t years = buf.ReadWord();
2493 housespec->min_year = GB(years, 0, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2494 housespec->max_year = GB(years, 8, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2495 break;
2498 case 0x0B: // Population
2499 housespec->population = buf.ReadByte();
2500 break;
2502 case 0x0C: // Mail generation multiplier
2503 housespec->mail_generation = buf.ReadByte();
2504 break;
2506 case 0x0D: // Passenger acceptance
2507 case 0x0E: // Mail acceptance
2508 housespec->cargo_acceptance[prop - 0x0D] = buf.ReadByte();
2509 break;
2511 case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2512 int8_t goods = buf.ReadByte();
2514 /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2515 * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2516 CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_CANDY) : GetCargoIDByLabel(CT_GOODS)) :
2517 ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_FIZZY_DRINKS) : GetCargoIDByLabel(CT_FOOD));
2519 /* Make sure the cargo type is valid in this climate. */
2520 if (!IsValidCargoID(cid)) goods = 0;
2522 housespec->accepts_cargo[2] = cid;
2523 housespec->accepts_cargo_label[2] = CT_INVALID;
2524 housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2525 break;
2528 case 0x10: // Local authority rating decrease on removal
2529 housespec->remove_rating_decrease = buf.ReadWord();
2530 break;
2532 case 0x11: // Removal cost multiplier
2533 housespec->removal_cost = buf.ReadByte();
2534 break;
2536 case 0x12: // Building name ID
2537 AddStringForMapping(buf.ReadWord(), &housespec->building_name);
2538 break;
2540 case 0x13: // Building availability mask
2541 housespec->building_availability = (HouseZones)buf.ReadWord();
2542 break;
2544 case 0x14: // House callback mask
2545 housespec->callback_mask |= buf.ReadByte();
2546 break;
2548 case 0x15: { // House override byte
2549 uint8_t override = buf.ReadByte();
2551 /* The house being overridden must be an original house. */
2552 if (override >= NEW_HOUSE_OFFSET) {
2553 GrfMsg(2, "TownHouseChangeInfo: Attempt to override new house {} with house id {}. Ignoring.", override, hid + i);
2554 continue;
2557 _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2558 break;
2561 case 0x16: // Periodic refresh multiplier
2562 housespec->processing_time = std::min<uint8_t>(buf.ReadByte(), 63u);
2563 break;
2565 case 0x17: // Four random colours to use
2566 for (uint j = 0; j < 4; j++) housespec->random_colour[j] = static_cast<Colours>(GB(buf.ReadByte(), 0, 4));
2567 break;
2569 case 0x18: // Relative probability of appearing
2570 housespec->probability = buf.ReadByte();
2571 break;
2573 case 0x19: // Extra flags
2574 housespec->extra_flags = (HouseExtraFlags)buf.ReadByte();
2575 break;
2577 case 0x1A: // Animation frames
2578 housespec->animation.frames = buf.ReadByte();
2579 housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2580 SB(housespec->animation.frames, 7, 1, 0);
2581 break;
2583 case 0x1B: // Animation speed
2584 housespec->animation.speed = Clamp(buf.ReadByte(), 2, 16);
2585 break;
2587 case 0x1C: // Class of the building type
2588 housespec->class_id = AllocateHouseClassID(buf.ReadByte(), _cur.grffile->grfid);
2589 break;
2591 case 0x1D: // Callback mask part 2
2592 housespec->callback_mask |= (buf.ReadByte() << 8);
2593 break;
2595 case 0x1E: { // Accepted cargo types
2596 uint32_t cargotypes = buf.ReadDWord();
2598 /* Check if the cargo types should not be changed */
2599 if (cargotypes == 0xFFFFFFFF) break;
2601 for (uint j = 0; j < HOUSE_ORIGINAL_NUM_ACCEPTS; j++) {
2602 /* Get the cargo number from the 'list' */
2603 uint8_t cargo_part = GB(cargotypes, 8 * j, 8);
2604 CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2606 if (!IsValidCargoID(cargo)) {
2607 /* Disable acceptance of invalid cargo type */
2608 housespec->cargo_acceptance[j] = 0;
2609 } else {
2610 housespec->accepts_cargo[j] = cargo;
2612 housespec->accepts_cargo_label[j] = CT_INVALID;
2614 break;
2617 case 0x1F: // Minimum life span
2618 housespec->minimum_life = buf.ReadByte();
2619 break;
2621 case 0x20: { // Cargo acceptance watch list
2622 uint8_t count = buf.ReadByte();
2623 for (uint8_t j = 0; j < count; j++) {
2624 CargoID cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
2625 if (IsValidCargoID(cargo)) SetBit(housespec->watched_cargoes, cargo);
2627 break;
2630 case 0x21: // long introduction year
2631 housespec->min_year = buf.ReadWord();
2632 break;
2634 case 0x22: // long maximum year
2635 housespec->max_year = buf.ReadWord();
2636 if (housespec->max_year == UINT16_MAX) housespec->max_year = CalendarTime::MAX_YEAR;
2637 break;
2639 case 0x23: { // variable length cargo types accepted
2640 uint count = buf.ReadByte();
2641 if (count > lengthof(housespec->accepts_cargo)) {
2642 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2643 error->param_value[1] = prop;
2644 return CIR_DISABLED;
2646 /* Always write the full accepts_cargo array, and check each index for being inside the
2647 * provided data. This ensures all values are properly initialized, and also avoids
2648 * any risks of array overrun. */
2649 for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2650 if (i < count) {
2651 housespec->accepts_cargo[i] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
2652 housespec->cargo_acceptance[i] = buf.ReadByte();
2653 } else {
2654 housespec->accepts_cargo[i] = INVALID_CARGO;
2655 housespec->cargo_acceptance[i] = 0;
2657 housespec->accepts_cargo_label[i] = CT_INVALID;
2659 break;
2662 default:
2663 ret = CIR_UNKNOWN;
2664 break;
2668 return ret;
2672 * Get the language map associated with a given NewGRF and language.
2673 * @param grfid The NewGRF to get the map for.
2674 * @param language_id The (NewGRF) language ID to get the map for.
2675 * @return The LanguageMap, or nullptr if it couldn't be found.
2677 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32_t grfid, uint8_t language_id)
2679 /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2680 const GRFFile *grffile = GetFileByGRFID(grfid);
2681 if (grffile == nullptr) return nullptr;
2683 auto it = grffile->language_map.find(language_id);
2684 if (it == std::end(grffile->language_map)) return nullptr;
2686 return &it->second;
2690 * Load a cargo- or railtype-translation table.
2691 * @param gvid ID of the global variable. This is basically only checked for zerones.
2692 * @param numinfo Number of subsequent IDs to change the property for.
2693 * @param buf The property value.
2694 * @param[in,out] translation_table Storage location for the translation table.
2695 * @param name Name of the table for debug output.
2696 * @return ChangeInfoResult.
2698 template <typename T>
2699 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader &buf, std::vector<T> &translation_table, const char *name)
2701 if (gvid != 0) {
2702 GrfMsg(1, "LoadTranslationTable: {} translation table must start at zero", name);
2703 return CIR_INVALID_ID;
2706 translation_table.clear();
2707 translation_table.reserve(numinfo);
2708 for (int i = 0; i < numinfo; i++) {
2709 translation_table.push_back(T(BSWAP32(buf.ReadDWord())));
2712 return CIR_SUCCESS;
2716 * Helper to read a DWord worth of bytes from the reader
2717 * and to return it as a valid string.
2718 * @param reader The source of the DWord.
2719 * @return The read DWord as string.
2721 static std::string ReadDWordAsString(ByteReader &reader)
2723 std::string output;
2724 for (int i = 0; i < 4; i++) output.push_back(reader.ReadByte());
2725 return StrMakeValid(output);
2729 * Define properties for global variables
2730 * @param gvid ID of the global variable.
2731 * @param numinfo Number of subsequent IDs to change the property for.
2732 * @param prop The property to change.
2733 * @param buf The property value.
2734 * @return ChangeInfoResult.
2736 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader &buf)
2738 /* Properties which are handled as a whole */
2739 switch (prop) {
2740 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2741 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2743 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2744 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2746 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2747 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2749 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2750 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2752 default:
2753 break;
2756 /* Properties which are handled per item */
2757 ChangeInfoResult ret = CIR_SUCCESS;
2758 for (int i = 0; i < numinfo; i++) {
2759 switch (prop) {
2760 case 0x08: { // Cost base factor
2761 int factor = buf.ReadByte();
2762 uint price = gvid + i;
2764 if (price < PR_END) {
2765 _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2766 } else {
2767 GrfMsg(1, "GlobalVarChangeInfo: Price {} out of range, ignoring", price);
2769 break;
2772 case 0x0A: { // Currency display names
2773 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2774 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf.ReadWord());
2776 if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2777 _currency_specs[curidx].name = newone;
2778 _currency_specs[curidx].code.clear();
2780 break;
2783 case 0x0B: { // Currency multipliers
2784 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2785 uint32_t rate = buf.ReadDWord();
2787 if (curidx < CURRENCY_END) {
2788 /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2789 * which OTTD does not. For this reason, divide grf value by 1000,
2790 * to be compatible */
2791 _currency_specs[curidx].rate = rate / 1000;
2792 } else {
2793 GrfMsg(1, "GlobalVarChangeInfo: Currency multipliers {} out of range, ignoring", curidx);
2795 break;
2798 case 0x0C: { // Currency options
2799 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2800 uint16_t options = buf.ReadWord();
2802 if (curidx < CURRENCY_END) {
2803 _currency_specs[curidx].separator.clear();
2804 _currency_specs[curidx].separator.push_back(GB(options, 0, 8));
2805 /* By specifying only one bit, we prevent errors,
2806 * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2807 _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2808 } else {
2809 GrfMsg(1, "GlobalVarChangeInfo: Currency option {} out of range, ignoring", curidx);
2811 break;
2814 case 0x0D: { // Currency prefix symbol
2815 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2816 std::string prefix = ReadDWordAsString(buf);
2818 if (curidx < CURRENCY_END) {
2819 _currency_specs[curidx].prefix = prefix;
2820 } else {
2821 GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2823 break;
2826 case 0x0E: { // Currency suffix symbol
2827 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2828 std::string suffix = ReadDWordAsString(buf);
2830 if (curidx < CURRENCY_END) {
2831 _currency_specs[curidx].suffix = suffix;
2832 } else {
2833 GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2835 break;
2838 case 0x0F: { // Euro introduction dates
2839 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2840 TimerGameCalendar::Year year_euro = buf.ReadWord();
2842 if (curidx < CURRENCY_END) {
2843 _currency_specs[curidx].to_euro = year_euro;
2844 } else {
2845 GrfMsg(1, "GlobalVarChangeInfo: Euro intro date {} out of range, ignoring", curidx);
2847 break;
2850 case 0x10: // Snow line height table
2851 if (numinfo > 1 || IsSnowLineSet()) {
2852 GrfMsg(1, "GlobalVarChangeInfo: The snowline can only be set once ({})", numinfo);
2853 } else if (buf.Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2854 GrfMsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table ({})", buf.Remaining());
2855 } else {
2856 uint8_t table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2858 for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2859 for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2860 table[i][j] = buf.ReadByte();
2861 if (_cur.grffile->grf_version >= 8) {
2862 if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2863 } else {
2864 if (table[i][j] >= 128) {
2865 /* no snow */
2866 table[i][j] = 0xFF;
2867 } else {
2868 table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2873 SetSnowLine(table);
2875 break;
2877 case 0x11: // GRF match for engine allocation
2878 /* This is loaded during the reservation stage, so just skip it here. */
2879 /* Each entry is 8 bytes. */
2880 buf.Skip(8);
2881 break;
2883 case 0x13: // Gender translation table
2884 case 0x14: // Case translation table
2885 case 0x15: { // Plural form translation
2886 uint curidx = gvid + i; // The current index, i.e. language.
2887 const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2888 if (lang == nullptr) {
2889 GrfMsg(1, "GlobalVarChangeInfo: Language {} is not known, ignoring", curidx);
2890 /* Skip over the data. */
2891 if (prop == 0x15) {
2892 buf.ReadByte();
2893 } else {
2894 while (buf.ReadByte() != 0) {
2895 buf.ReadString();
2898 break;
2901 if (prop == 0x15) {
2902 uint plural_form = buf.ReadByte();
2903 if (plural_form >= LANGUAGE_MAX_PLURAL) {
2904 GrfMsg(1, "GlobalVarChanceInfo: Plural form {} is out of range, ignoring", plural_form);
2905 } else {
2906 _cur.grffile->language_map[curidx].plural_form = plural_form;
2908 break;
2911 uint8_t newgrf_id = buf.ReadByte(); // The NewGRF (custom) identifier.
2912 while (newgrf_id != 0) {
2913 std::string_view name = buf.ReadString(); // The name for the OpenTTD identifier.
2915 /* We'll just ignore the UTF8 identifier character. This is (fairly)
2916 * safe as OpenTTD's strings gender/cases are usually in ASCII which
2917 * is just a subset of UTF8, or they need the bigger UTF8 characters
2918 * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2919 char32_t c;
2920 size_t len = Utf8Decode(&c, name.data());
2921 if (c == NFO_UTF8_IDENTIFIER) name = name.substr(len);
2923 LanguageMap::Mapping map;
2924 map.newgrf_id = newgrf_id;
2925 if (prop == 0x13) {
2926 map.openttd_id = lang->GetGenderIndex(name.data());
2927 if (map.openttd_id >= MAX_NUM_GENDERS) {
2928 GrfMsg(1, "GlobalVarChangeInfo: Gender name {} is not known, ignoring", StrMakeValid(name));
2929 } else {
2930 _cur.grffile->language_map[curidx].gender_map.push_back(map);
2932 } else {
2933 map.openttd_id = lang->GetCaseIndex(name.data());
2934 if (map.openttd_id >= MAX_NUM_CASES) {
2935 GrfMsg(1, "GlobalVarChangeInfo: Case name {} is not known, ignoring", StrMakeValid(name));
2936 } else {
2937 _cur.grffile->language_map[curidx].case_map.push_back(map);
2940 newgrf_id = buf.ReadByte();
2942 break;
2945 default:
2946 ret = CIR_UNKNOWN;
2947 break;
2951 return ret;
2954 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader &buf)
2956 /* Properties which are handled as a whole */
2957 switch (prop) {
2958 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2959 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2961 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2962 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2964 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2965 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2967 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2968 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2970 default:
2971 break;
2974 /* Properties which are handled per item */
2975 ChangeInfoResult ret = CIR_SUCCESS;
2976 for (int i = 0; i < numinfo; i++) {
2977 switch (prop) {
2978 case 0x08: // Cost base factor
2979 case 0x15: // Plural form translation
2980 buf.ReadByte();
2981 break;
2983 case 0x0A: // Currency display names
2984 case 0x0C: // Currency options
2985 case 0x0F: // Euro introduction dates
2986 buf.ReadWord();
2987 break;
2989 case 0x0B: // Currency multipliers
2990 case 0x0D: // Currency prefix symbol
2991 case 0x0E: // Currency suffix symbol
2992 buf.ReadDWord();
2993 break;
2995 case 0x10: // Snow line height table
2996 buf.Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2997 break;
2999 case 0x11: { // GRF match for engine allocation
3000 uint32_t s = buf.ReadDWord();
3001 uint32_t t = buf.ReadDWord();
3002 SetNewGRFOverride(s, t);
3003 break;
3006 case 0x13: // Gender translation table
3007 case 0x14: // Case translation table
3008 while (buf.ReadByte() != 0) {
3009 buf.ReadString();
3011 break;
3013 default:
3014 ret = CIR_UNKNOWN;
3015 break;
3019 return ret;
3024 * Define properties for cargoes
3025 * @param cid Local ID of the cargo.
3026 * @param numinfo Number of subsequent IDs to change the property for.
3027 * @param prop The property to change.
3028 * @param buf The property value.
3029 * @return ChangeInfoResult.
3031 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader &buf)
3033 ChangeInfoResult ret = CIR_SUCCESS;
3035 if (cid + numinfo > NUM_CARGO) {
3036 GrfMsg(2, "CargoChangeInfo: Cargo type {} out of range (max {})", cid + numinfo, NUM_CARGO - 1);
3037 return CIR_INVALID_ID;
3040 for (int i = 0; i < numinfo; i++) {
3041 CargoSpec *cs = CargoSpec::Get(cid + i);
3043 switch (prop) {
3044 case 0x08: // Bit number of cargo
3045 cs->bitnum = buf.ReadByte();
3046 if (cs->IsValid()) {
3047 cs->grffile = _cur.grffile;
3048 SetBit(_cargo_mask, cid + i);
3049 } else {
3050 ClrBit(_cargo_mask, cid + i);
3052 BuildCargoLabelMap();
3053 break;
3055 case 0x09: // String ID for cargo type name
3056 AddStringForMapping(buf.ReadWord(), &cs->name);
3057 break;
3059 case 0x0A: // String for 1 unit of cargo
3060 AddStringForMapping(buf.ReadWord(), &cs->name_single);
3061 break;
3063 case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
3064 case 0x1B: // String for cargo units
3065 /* String for units of cargo. This is different in OpenTTD
3066 * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
3067 * Property 1B is used to set OpenTTD's behaviour. */
3068 AddStringForMapping(buf.ReadWord(), &cs->units_volume);
3069 break;
3071 case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
3072 case 0x1C: // String for any amount of cargo
3073 /* Strings for an amount of cargo. This is different in OpenTTD
3074 * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
3075 * Property 1C is used to set OpenTTD's behaviour. */
3076 AddStringForMapping(buf.ReadWord(), &cs->quantifier);
3077 break;
3079 case 0x0D: // String for two letter cargo abbreviation
3080 AddStringForMapping(buf.ReadWord(), &cs->abbrev);
3081 break;
3083 case 0x0E: // Sprite ID for cargo icon
3084 cs->sprite = buf.ReadWord();
3085 break;
3087 case 0x0F: // Weight of one unit of cargo
3088 cs->weight = buf.ReadByte();
3089 break;
3091 case 0x10: // Used for payment calculation
3092 cs->transit_periods[0] = buf.ReadByte();
3093 break;
3095 case 0x11: // Used for payment calculation
3096 cs->transit_periods[1] = buf.ReadByte();
3097 break;
3099 case 0x12: // Base cargo price
3100 cs->initial_payment = buf.ReadDWord();
3101 break;
3103 case 0x13: // Colour for station rating bars
3104 cs->rating_colour = buf.ReadByte();
3105 break;
3107 case 0x14: // Colour for cargo graph
3108 cs->legend_colour = buf.ReadByte();
3109 break;
3111 case 0x15: // Freight status
3112 cs->is_freight = (buf.ReadByte() != 0);
3113 break;
3115 case 0x16: // Cargo classes
3116 cs->classes = buf.ReadWord();
3117 break;
3119 case 0x17: // Cargo label
3120 cs->label = CargoLabel{BSWAP32(buf.ReadDWord())};
3121 BuildCargoLabelMap();
3122 break;
3124 case 0x18: { // Town growth substitute type
3125 uint8_t substitute_type = buf.ReadByte();
3127 switch (substitute_type) {
3128 case 0x00: cs->town_acceptance_effect = TAE_PASSENGERS; break;
3129 case 0x02: cs->town_acceptance_effect = TAE_MAIL; break;
3130 case 0x05: cs->town_acceptance_effect = TAE_GOODS; break;
3131 case 0x09: cs->town_acceptance_effect = TAE_WATER; break;
3132 case 0x0B: cs->town_acceptance_effect = TAE_FOOD; break;
3133 default:
3134 GrfMsg(1, "CargoChangeInfo: Unknown town growth substitute value {}, setting to none.", substitute_type);
3135 [[fallthrough]];
3136 case 0xFF: cs->town_acceptance_effect = TAE_NONE; break;
3138 break;
3141 case 0x19: // Town growth coefficient
3142 buf.ReadWord();
3143 break;
3145 case 0x1A: // Bitmask of callbacks to use
3146 cs->callback_mask = buf.ReadByte();
3147 break;
3149 case 0x1D: // Vehicle capacity muliplier
3150 cs->multiplier = std::max<uint16_t>(1u, buf.ReadWord());
3151 break;
3153 case 0x1E: { // Town production substitute type
3154 uint8_t substitute_type = buf.ReadByte();
3156 switch (substitute_type) {
3157 case 0x00: cs->town_production_effect = TPE_PASSENGERS; break;
3158 case 0x02: cs->town_production_effect = TPE_MAIL; break;
3159 default:
3160 GrfMsg(1, "CargoChangeInfo: Unknown town production substitute value {}, setting to none.", substitute_type);
3161 [[fallthrough]];
3162 case 0xFF: cs->town_production_effect = TPE_NONE; break;
3164 break;
3167 case 0x1F: // Town production multiplier
3168 cs->town_production_multiplier = std::max<uint16_t>(1U, buf.ReadWord());
3169 break;
3171 default:
3172 ret = CIR_UNKNOWN;
3173 break;
3177 return ret;
3182 * Define properties for sound effects
3183 * @param sid Local ID of the sound.
3184 * @param numinfo Number of subsequent IDs to change the property for.
3185 * @param prop The property to change.
3186 * @param buf The property value.
3187 * @return ChangeInfoResult.
3189 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader &buf)
3191 ChangeInfoResult ret = CIR_SUCCESS;
3193 if (_cur.grffile->sound_offset == 0) {
3194 GrfMsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3195 return CIR_INVALID_ID;
3198 if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3199 GrfMsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect ({}), max ({}). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3200 return CIR_INVALID_ID;
3203 for (int i = 0; i < numinfo; i++) {
3204 SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3206 switch (prop) {
3207 case 0x08: // Relative volume
3208 sound->volume = Clamp(buf.ReadByte(), 0, SOUND_EFFECT_MAX_VOLUME);
3209 break;
3211 case 0x09: // Priority
3212 sound->priority = buf.ReadByte();
3213 break;
3215 case 0x0A: { // Override old sound
3216 SoundID orig_sound = buf.ReadByte();
3218 if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3219 GrfMsg(1, "SoundEffectChangeInfo: Original sound {} not defined (max {})", orig_sound, ORIGINAL_SAMPLE_COUNT);
3220 } else {
3221 SoundEntry *old_sound = GetSound(orig_sound);
3223 /* Literally copy the data of the new sound over the original */
3224 *old_sound = *sound;
3226 break;
3229 default:
3230 ret = CIR_UNKNOWN;
3231 break;
3235 return ret;
3239 * Ignore an industry tile property
3240 * @param prop The property to ignore.
3241 * @param buf The property value.
3242 * @return ChangeInfoResult.
3244 static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader &buf)
3246 ChangeInfoResult ret = CIR_SUCCESS;
3248 switch (prop) {
3249 case 0x09:
3250 case 0x0D:
3251 case 0x0E:
3252 case 0x10:
3253 case 0x11:
3254 case 0x12:
3255 buf.ReadByte();
3256 break;
3258 case 0x0A:
3259 case 0x0B:
3260 case 0x0C:
3261 case 0x0F:
3262 buf.ReadWord();
3263 break;
3265 case 0x13:
3266 buf.Skip(buf.ReadByte() * 2);
3267 break;
3269 default:
3270 ret = CIR_UNKNOWN;
3271 break;
3273 return ret;
3277 * Define properties for industry tiles
3278 * @param indtid Local ID of the industry tile.
3279 * @param numinfo Number of subsequent industry tile IDs to change the property for.
3280 * @param prop The property to change.
3281 * @param buf The property value.
3282 * @return ChangeInfoResult.
3284 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader &buf)
3286 ChangeInfoResult ret = CIR_SUCCESS;
3288 if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3289 GrfMsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded ({}), max ({}). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3290 return CIR_INVALID_ID;
3293 /* Allocate industry tile specs if they haven't been allocated already. */
3294 if (_cur.grffile->indtspec.size() < indtid + numinfo) _cur.grffile->indtspec.resize(indtid + numinfo);
3296 for (int i = 0; i < numinfo; i++) {
3297 auto &tsp = _cur.grffile->indtspec[indtid + i];
3299 if (prop != 0x08 && tsp == nullptr) {
3300 ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf);
3301 if (cir > ret) ret = cir;
3302 continue;
3305 switch (prop) {
3306 case 0x08: { // Substitute industry tile type
3307 uint8_t subs_id = buf.ReadByte();
3308 if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3309 /* The substitute id must be one of the original industry tile. */
3310 GrfMsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile {} as substitute industry tile for {}. Ignoring.", subs_id, indtid + i);
3311 continue;
3314 /* Allocate space for this industry. */
3315 if (tsp == nullptr) {
3316 tsp = std::make_unique<IndustryTileSpec>(_industry_tile_specs[subs_id]);
3318 tsp->enabled = true;
3320 /* A copied tile should not have the animation infos copied too.
3321 * The anim_state should be left untouched, though
3322 * It is up to the author to animate them */
3323 tsp->anim_production = INDUSTRYTILE_NOANIM;
3324 tsp->anim_next = INDUSTRYTILE_NOANIM;
3326 tsp->grf_prop.local_id = indtid + i;
3327 tsp->grf_prop.subst_id = subs_id;
3328 tsp->grf_prop.grffile = _cur.grffile;
3329 _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3331 break;
3334 case 0x09: { // Industry tile override
3335 uint8_t ovrid = buf.ReadByte();
3337 /* The industry being overridden must be an original industry. */
3338 if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3339 GrfMsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile {} with industry tile id {}. Ignoring.", ovrid, indtid + i);
3340 continue;
3343 _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3344 break;
3347 case 0x0A: // Tile acceptance
3348 case 0x0B:
3349 case 0x0C: {
3350 uint16_t acctp = buf.ReadWord();
3351 tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3352 tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3353 tsp->accepts_cargo_label[prop - 0x0A] = CT_INVALID;
3354 break;
3357 case 0x0D: // Land shape flags
3358 tsp->slopes_refused = (Slope)buf.ReadByte();
3359 break;
3361 case 0x0E: // Callback mask
3362 tsp->callback_mask = buf.ReadByte();
3363 break;
3365 case 0x0F: // Animation information
3366 tsp->animation.frames = buf.ReadByte();
3367 tsp->animation.status = buf.ReadByte();
3368 break;
3370 case 0x10: // Animation speed
3371 tsp->animation.speed = buf.ReadByte();
3372 break;
3374 case 0x11: // Triggers for callback 25
3375 tsp->animation.triggers = buf.ReadByte();
3376 break;
3378 case 0x12: // Special flags
3379 tsp->special_flags = (IndustryTileSpecialFlags)buf.ReadByte();
3380 break;
3382 case 0x13: { // variable length cargo acceptance
3383 uint8_t num_cargoes = buf.ReadByte();
3384 if (num_cargoes > std::size(tsp->acceptance)) {
3385 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3386 error->param_value[1] = prop;
3387 return CIR_DISABLED;
3389 for (uint i = 0; i < std::size(tsp->acceptance); i++) {
3390 if (i < num_cargoes) {
3391 tsp->accepts_cargo[i] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3392 /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3393 tsp->acceptance[i] = (int8_t)buf.ReadByte();
3394 } else {
3395 tsp->accepts_cargo[i] = INVALID_CARGO;
3396 tsp->acceptance[i] = 0;
3398 tsp->accepts_cargo_label[i] = CT_INVALID;
3400 break;
3403 default:
3404 ret = CIR_UNKNOWN;
3405 break;
3409 return ret;
3413 * Ignore an industry property
3414 * @param prop The property to ignore.
3415 * @param buf The property value.
3416 * @return ChangeInfoResult.
3418 static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader &buf)
3420 ChangeInfoResult ret = CIR_SUCCESS;
3422 switch (prop) {
3423 case 0x09:
3424 case 0x0B:
3425 case 0x0F:
3426 case 0x12:
3427 case 0x13:
3428 case 0x14:
3429 case 0x17:
3430 case 0x18:
3431 case 0x19:
3432 case 0x21:
3433 case 0x22:
3434 buf.ReadByte();
3435 break;
3437 case 0x0C:
3438 case 0x0D:
3439 case 0x0E:
3440 case 0x10: // INDUSTRY_ORIGINAL_NUM_OUTPUTS bytes
3441 case 0x1B:
3442 case 0x1F:
3443 case 0x24:
3444 buf.ReadWord();
3445 break;
3447 case 0x11: // INDUSTRY_ORIGINAL_NUM_INPUTS bytes + 1
3448 case 0x1A:
3449 case 0x1C:
3450 case 0x1D:
3451 case 0x1E:
3452 case 0x20:
3453 case 0x23:
3454 buf.ReadDWord();
3455 break;
3457 case 0x0A: {
3458 uint8_t num_table = buf.ReadByte();
3459 for (uint8_t j = 0; j < num_table; j++) {
3460 for (uint k = 0;; k++) {
3461 uint8_t x = buf.ReadByte();
3462 if (x == 0xFE && k == 0) {
3463 buf.ReadByte();
3464 buf.ReadByte();
3465 break;
3468 uint8_t y = buf.ReadByte();
3469 if (x == 0 && y == 0x80) break;
3471 uint8_t gfx = buf.ReadByte();
3472 if (gfx == 0xFE) buf.ReadWord();
3475 break;
3478 case 0x16:
3479 for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_INPUTS; j++) buf.ReadByte();
3480 break;
3482 case 0x15:
3483 case 0x25:
3484 case 0x26:
3485 case 0x27:
3486 buf.Skip(buf.ReadByte());
3487 break;
3489 case 0x28: {
3490 int num_inputs = buf.ReadByte();
3491 int num_outputs = buf.ReadByte();
3492 buf.Skip(num_inputs * num_outputs * 2);
3493 break;
3496 default:
3497 ret = CIR_UNKNOWN;
3498 break;
3500 return ret;
3504 * Validate the industry layout; e.g. to prevent duplicate tiles.
3505 * @param layout The layout to check.
3506 * @return True if the layout is deemed valid.
3508 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3510 const size_t size = layout.size();
3511 if (size == 0) return false;
3513 for (size_t i = 0; i < size - 1; i++) {
3514 for (size_t j = i + 1; j < size; j++) {
3515 if (layout[i].ti.x == layout[j].ti.x &&
3516 layout[i].ti.y == layout[j].ti.y) {
3517 return false;
3522 bool have_regular_tile = false;
3523 for (const auto &tilelayout : layout) {
3524 if (tilelayout.gfx != GFX_WATERTILE_SPECIALCHECK) {
3525 have_regular_tile = true;
3526 break;
3530 return have_regular_tile;
3534 * Define properties for industries
3535 * @param indid Local ID of the industry.
3536 * @param numinfo Number of subsequent industry IDs to change the property for.
3537 * @param prop The property to change.
3538 * @param buf The property value.
3539 * @return ChangeInfoResult.
3541 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader &buf)
3543 ChangeInfoResult ret = CIR_SUCCESS;
3545 if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3546 GrfMsg(1, "IndustriesChangeInfo: Too many industries loaded ({}), max ({}). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3547 return CIR_INVALID_ID;
3550 /* Allocate industry specs if they haven't been allocated already. */
3551 if (_cur.grffile->industryspec.size() < indid + numinfo) _cur.grffile->industryspec.resize(indid + numinfo);
3553 for (int i = 0; i < numinfo; i++) {
3554 auto &indsp = _cur.grffile->industryspec[indid + i];
3556 if (prop != 0x08 && indsp == nullptr) {
3557 ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3558 if (cir > ret) ret = cir;
3559 continue;
3562 switch (prop) {
3563 case 0x08: { // Substitute industry type
3564 uint8_t subs_id = buf.ReadByte();
3565 if (subs_id == 0xFF) {
3566 /* Instead of defining a new industry, a substitute industry id
3567 * of 0xFF disables the old industry with the current id. */
3568 _industry_specs[indid + i].enabled = false;
3569 continue;
3570 } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3571 /* The substitute id must be one of the original industry. */
3572 GrfMsg(2, "_industry_specs: Attempt to use new industry {} as substitute industry for {}. Ignoring.", subs_id, indid + i);
3573 continue;
3576 /* Allocate space for this industry.
3577 * Only need to do it once. If ever it is called again, it should not
3578 * do anything */
3579 if (indsp == nullptr) {
3580 indsp = std::make_unique<IndustrySpec>(_origin_industry_specs[subs_id]);
3582 indsp->enabled = true;
3583 indsp->grf_prop.local_id = indid + i;
3584 indsp->grf_prop.subst_id = subs_id;
3585 indsp->grf_prop.grffile = _cur.grffile;
3586 /* If the grf industry needs to check its surrounding upon creation, it should
3587 * rely on callbacks, not on the original placement functions */
3588 indsp->check_proc = CHECK_NOTHING;
3590 break;
3593 case 0x09: { // Industry type override
3594 uint8_t ovrid = buf.ReadByte();
3596 /* The industry being overridden must be an original industry. */
3597 if (ovrid >= NEW_INDUSTRYOFFSET) {
3598 GrfMsg(2, "IndustriesChangeInfo: Attempt to override new industry {} with industry id {}. Ignoring.", ovrid, indid + i);
3599 continue;
3601 indsp->grf_prop.override = ovrid;
3602 _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3603 break;
3606 case 0x0A: { // Set industry layout(s)
3607 uint8_t new_num_layouts = buf.ReadByte();
3608 uint32_t definition_size = buf.ReadDWord();
3609 uint32_t bytes_read = 0;
3610 std::vector<IndustryTileLayout> new_layouts;
3611 IndustryTileLayout layout;
3613 for (uint8_t j = 0; j < new_num_layouts; j++) {
3614 layout.clear();
3615 layout.reserve(new_num_layouts);
3617 for (uint k = 0;; k++) {
3618 if (bytes_read >= definition_size) {
3619 GrfMsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry {}.", indid);
3620 /* Avoid warning twice */
3621 definition_size = UINT32_MAX;
3624 layout.push_back(IndustryTileLayoutTile{});
3625 IndustryTileLayoutTile &it = layout.back();
3627 it.ti.x = buf.ReadByte(); // Offsets from northermost tile
3628 ++bytes_read;
3630 if (it.ti.x == 0xFE && k == 0) {
3631 /* This means we have to borrow the layout from an old industry */
3632 IndustryType type = buf.ReadByte();
3633 uint8_t laynbr = buf.ReadByte();
3634 bytes_read += 2;
3636 if (type >= lengthof(_origin_industry_specs)) {
3637 GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", indid);
3638 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3639 return CIR_DISABLED;
3641 if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3642 GrfMsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry {}", indid);
3643 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3644 return CIR_DISABLED;
3646 layout = _origin_industry_specs[type].layouts[laynbr];
3647 break;
3650 it.ti.y = buf.ReadByte(); // Or table definition finalisation
3651 ++bytes_read;
3653 if (it.ti.x == 0 && it.ti.y == 0x80) {
3654 /* Terminator, remove and finish up */
3655 layout.pop_back();
3656 break;
3659 it.gfx = buf.ReadByte();
3660 ++bytes_read;
3662 if (it.gfx == 0xFE) {
3663 /* Use a new tile from this GRF */
3664 int local_tile_id = buf.ReadWord();
3665 bytes_read += 2;
3667 /* Read the ID from the _industile_mngr. */
3668 int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3670 if (tempid == INVALID_INDUSTRYTILE) {
3671 GrfMsg(2, "IndustriesChangeInfo: Attempt to use industry tile {} with industry id {}, not yet defined. Ignoring.", local_tile_id, indid);
3672 } else {
3673 /* Declared as been valid, can be used */
3674 it.gfx = tempid;
3676 } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
3677 it.ti.x = (int8_t)GB(it.ti.x, 0, 8);
3678 it.ti.y = (int8_t)GB(it.ti.y, 0, 8);
3680 /* When there were only 256x256 maps, TileIndex was a uint16_t and
3681 * it.ti was just a TileIndexDiff that was added to it.
3682 * As such negative "x" values were shifted into the "y" position.
3683 * x = -1, y = 1 -> x = 255, y = 0
3684 * Since GRF version 8 the position is interpreted as pair of independent int8.
3685 * For GRF version < 8 we need to emulate the old shifting behaviour.
3687 if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3691 if (!ValidateIndustryLayout(layout)) {
3692 /* The industry layout was not valid, so skip this one. */
3693 GrfMsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id {}. Ignoring", indid);
3694 new_num_layouts--;
3695 j--;
3696 } else {
3697 new_layouts.push_back(layout);
3701 /* Install final layout construction in the industry spec */
3702 indsp->layouts = new_layouts;
3703 break;
3706 case 0x0B: // Industry production flags
3707 indsp->life_type = (IndustryLifeType)buf.ReadByte();
3708 break;
3710 case 0x0C: // Industry closure message
3711 AddStringForMapping(buf.ReadWord(), &indsp->closure_text);
3712 break;
3714 case 0x0D: // Production increase message
3715 AddStringForMapping(buf.ReadWord(), &indsp->production_up_text);
3716 break;
3718 case 0x0E: // Production decrease message
3719 AddStringForMapping(buf.ReadWord(), &indsp->production_down_text);
3720 break;
3722 case 0x0F: // Fund cost multiplier
3723 indsp->cost_multiplier = buf.ReadByte();
3724 break;
3726 case 0x10: // Production cargo types
3727 for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_OUTPUTS; j++) {
3728 indsp->produced_cargo[j] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3729 indsp->produced_cargo_label[j] = CT_INVALID;
3731 break;
3733 case 0x11: // Acceptance cargo types
3734 for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_INPUTS; j++) {
3735 indsp->accepts_cargo[j] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3736 indsp->accepts_cargo_label[j] = CT_INVALID;
3738 buf.ReadByte(); // Unnused, eat it up
3739 break;
3741 case 0x12: // Production multipliers
3742 case 0x13:
3743 indsp->production_rate[prop - 0x12] = buf.ReadByte();
3744 break;
3746 case 0x14: // Minimal amount of cargo distributed
3747 indsp->minimal_cargo = buf.ReadByte();
3748 break;
3750 case 0x15: { // Random sound effects
3751 uint8_t num_sounds = buf.ReadByte();
3753 std::vector<uint8_t> sounds;
3754 sounds.reserve(num_sounds);
3755 for (uint8_t j = 0; j < num_sounds; ++j) {
3756 sounds.push_back(buf.ReadByte());
3759 indsp->random_sounds = std::move(sounds);
3760 break;
3763 case 0x16: // Conflicting industry types
3764 for (uint8_t j = 0; j < 3; j++) indsp->conflicting[j] = buf.ReadByte();
3765 break;
3767 case 0x17: // Probability in random game
3768 indsp->appear_creation[_settings_game.game_creation.landscape] = buf.ReadByte();
3769 break;
3771 case 0x18: // Probability during gameplay
3772 indsp->appear_ingame[_settings_game.game_creation.landscape] = buf.ReadByte();
3773 break;
3775 case 0x19: // Map colour
3776 indsp->map_colour = buf.ReadByte();
3777 break;
3779 case 0x1A: // Special industry flags to define special behavior
3780 indsp->behaviour = (IndustryBehaviour)buf.ReadDWord();
3781 break;
3783 case 0x1B: // New industry text ID
3784 AddStringForMapping(buf.ReadWord(), &indsp->new_industry_text);
3785 break;
3787 case 0x1C: // Input cargo multipliers for the three input cargo types
3788 case 0x1D:
3789 case 0x1E: {
3790 uint32_t multiples = buf.ReadDWord();
3791 indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3792 indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3793 break;
3796 case 0x1F: // Industry name
3797 AddStringForMapping(buf.ReadWord(), &indsp->name);
3798 break;
3800 case 0x20: // Prospecting success chance
3801 indsp->prospecting_chance = buf.ReadDWord();
3802 break;
3804 case 0x21: // Callback mask
3805 case 0x22: { // Callback additional mask
3806 uint8_t aflag = buf.ReadByte();
3807 SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3808 break;
3811 case 0x23: // removal cost multiplier
3812 indsp->removal_cost_multiplier = buf.ReadDWord();
3813 break;
3815 case 0x24: { // name for nearby station
3816 uint16_t str = buf.ReadWord();
3817 if (str == 0) {
3818 indsp->station_name = STR_NULL;
3819 } else {
3820 AddStringForMapping(str, &indsp->station_name);
3822 break;
3825 case 0x25: { // variable length produced cargoes
3826 uint8_t num_cargoes = buf.ReadByte();
3827 if (num_cargoes > std::size(indsp->produced_cargo)) {
3828 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3829 error->param_value[1] = prop;
3830 return CIR_DISABLED;
3832 for (size_t i = 0; i < std::size(indsp->produced_cargo); i++) {
3833 if (i < num_cargoes) {
3834 CargoID cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3835 indsp->produced_cargo[i] = cargo;
3836 } else {
3837 indsp->produced_cargo[i] = INVALID_CARGO;
3839 indsp->produced_cargo_label[i] = CT_INVALID;
3841 break;
3844 case 0x26: { // variable length accepted cargoes
3845 uint8_t num_cargoes = buf.ReadByte();
3846 if (num_cargoes > std::size(indsp->accepts_cargo)) {
3847 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3848 error->param_value[1] = prop;
3849 return CIR_DISABLED;
3851 for (size_t i = 0; i < std::size(indsp->accepts_cargo); i++) {
3852 if (i < num_cargoes) {
3853 CargoID cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3854 indsp->accepts_cargo[i] = cargo;
3855 } else {
3856 indsp->accepts_cargo[i] = INVALID_CARGO;
3858 indsp->accepts_cargo_label[i] = CT_INVALID;
3860 break;
3863 case 0x27: { // variable length production rates
3864 uint8_t num_cargoes = buf.ReadByte();
3865 if (num_cargoes > lengthof(indsp->production_rate)) {
3866 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3867 error->param_value[1] = prop;
3868 return CIR_DISABLED;
3870 for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3871 if (i < num_cargoes) {
3872 indsp->production_rate[i] = buf.ReadByte();
3873 } else {
3874 indsp->production_rate[i] = 0;
3877 break;
3880 case 0x28: { // variable size input/output production multiplier table
3881 uint8_t num_inputs = buf.ReadByte();
3882 uint8_t num_outputs = buf.ReadByte();
3883 if (num_inputs > std::size(indsp->accepts_cargo) || num_outputs > std::size(indsp->produced_cargo)) {
3884 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3885 error->param_value[1] = prop;
3886 return CIR_DISABLED;
3888 for (size_t i = 0; i < std::size(indsp->accepts_cargo); i++) {
3889 for (size_t j = 0; j < std::size(indsp->produced_cargo); j++) {
3890 uint16_t mult = 0;
3891 if (i < num_inputs && j < num_outputs) mult = buf.ReadWord();
3892 indsp->input_cargo_multiplier[i][j] = mult;
3895 break;
3898 default:
3899 ret = CIR_UNKNOWN;
3900 break;
3904 return ret;
3908 * Define properties for airports
3909 * @param airport Local ID of the airport.
3910 * @param numinfo Number of subsequent airport IDs to change the property for.
3911 * @param prop The property to change.
3912 * @param buf The property value.
3913 * @return ChangeInfoResult.
3915 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader &buf)
3917 ChangeInfoResult ret = CIR_SUCCESS;
3919 if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3920 GrfMsg(1, "AirportChangeInfo: Too many airports, trying id ({}), max ({}). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3921 return CIR_INVALID_ID;
3924 /* Allocate industry specs if they haven't been allocated already. */
3925 if (_cur.grffile->airportspec.size() < airport + numinfo) _cur.grffile->airportspec.resize(airport + numinfo);
3927 for (int i = 0; i < numinfo; i++) {
3928 auto &as = _cur.grffile->airportspec[airport + i];
3930 if (as == nullptr && prop != 0x08 && prop != 0x09) {
3931 GrfMsg(2, "AirportChangeInfo: Attempt to modify undefined airport {}, ignoring", airport + i);
3932 return CIR_INVALID_ID;
3935 switch (prop) {
3936 case 0x08: { // Modify original airport
3937 uint8_t subs_id = buf.ReadByte();
3938 if (subs_id == 0xFF) {
3939 /* Instead of defining a new airport, an airport id
3940 * of 0xFF disables the old airport with the current id. */
3941 AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3942 continue;
3943 } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3944 /* The substitute id must be one of the original airports. */
3945 GrfMsg(2, "AirportChangeInfo: Attempt to use new airport {} as substitute airport for {}. Ignoring.", subs_id, airport + i);
3946 continue;
3949 /* Allocate space for this airport.
3950 * Only need to do it once. If ever it is called again, it should not
3951 * do anything */
3952 if (as == nullptr) {
3953 as = std::make_unique<AirportSpec>(*AirportSpec::GetWithoutOverride(subs_id));
3955 as->enabled = true;
3956 as->grf_prop.local_id = airport + i;
3957 as->grf_prop.subst_id = subs_id;
3958 as->grf_prop.grffile = _cur.grffile;
3959 /* override the default airport */
3960 _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3962 break;
3965 case 0x0A: { // Set airport layout
3966 uint8_t num_layouts = buf.ReadByte();
3967 buf.ReadDWord(); // Total size of definition, unneeded.
3968 uint8_t size_x = 0;
3969 uint8_t size_y = 0;
3971 std::vector<AirportTileLayout> layouts;
3972 layouts.reserve(num_layouts);
3974 for (uint8_t j = 0; j != num_layouts; ++j) {
3975 auto &layout = layouts.emplace_back();
3976 layout.rotation = static_cast<Direction>(buf.ReadByte() & 6); // Rotation can only be DIR_NORTH, DIR_EAST, DIR_SOUTH or DIR_WEST.
3978 for (;;) {
3979 auto &tile = layout.tiles.emplace_back();
3980 tile.ti.x = buf.ReadByte();
3981 tile.ti.y = buf.ReadByte();
3982 if (tile.ti.x == 0 && tile.ti.y == 0x80) {
3983 /* Convert terminator to our own. */
3984 tile.ti.x = -0x80;
3985 tile.ti.y = 0;
3986 tile.gfx = 0;
3987 break;
3990 tile.gfx = buf.ReadByte();
3992 if (tile.gfx == 0xFE) {
3993 /* Use a new tile from this GRF */
3994 int local_tile_id = buf.ReadWord();
3996 /* Read the ID from the _airporttile_mngr. */
3997 uint16_t tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3999 if (tempid == INVALID_AIRPORTTILE) {
4000 GrfMsg(2, "AirportChangeInfo: Attempt to use airport tile {} with airport id {}, not yet defined. Ignoring.", local_tile_id, airport + i);
4001 } else {
4002 /* Declared as been valid, can be used */
4003 tile.gfx = tempid;
4005 } else if (tile.gfx == 0xFF) {
4006 tile.ti.x = static_cast<int8_t>(GB(tile.ti.x, 0, 8));
4007 tile.ti.y = static_cast<int8_t>(GB(tile.ti.y, 0, 8));
4010 /* Determine largest size. */
4011 if (layout.rotation == DIR_E || layout.rotation == DIR_W) {
4012 size_x = std::max<uint8_t>(size_x, tile.ti.y + 1);
4013 size_y = std::max<uint8_t>(size_y, tile.ti.x + 1);
4014 } else {
4015 size_x = std::max<uint8_t>(size_x, tile.ti.x + 1);
4016 size_y = std::max<uint8_t>(size_y, tile.ti.y + 1);
4020 as->layouts = std::move(layouts);
4021 as->size_x = size_x;
4022 as->size_y = size_y;
4023 break;
4026 case 0x0C:
4027 as->min_year = buf.ReadWord();
4028 as->max_year = buf.ReadWord();
4029 if (as->max_year == 0xFFFF) as->max_year = CalendarTime::MAX_YEAR;
4030 break;
4032 case 0x0D:
4033 as->ttd_airport_type = (TTDPAirportType)buf.ReadByte();
4034 break;
4036 case 0x0E:
4037 as->catchment = Clamp(buf.ReadByte(), 1, MAX_CATCHMENT);
4038 break;
4040 case 0x0F:
4041 as->noise_level = buf.ReadByte();
4042 break;
4044 case 0x10:
4045 AddStringForMapping(buf.ReadWord(), &as->name);
4046 break;
4048 case 0x11: // Maintenance cost factor
4049 as->maintenance_cost = buf.ReadWord();
4050 break;
4052 default:
4053 ret = CIR_UNKNOWN;
4054 break;
4058 return ret;
4062 * Ignore properties for objects
4063 * @param prop The property to ignore.
4064 * @param buf The property value.
4065 * @return ChangeInfoResult.
4067 static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader &buf)
4069 ChangeInfoResult ret = CIR_SUCCESS;
4071 switch (prop) {
4072 case 0x0B:
4073 case 0x0C:
4074 case 0x0D:
4075 case 0x12:
4076 case 0x14:
4077 case 0x16:
4078 case 0x17:
4079 case 0x18:
4080 buf.ReadByte();
4081 break;
4083 case 0x09:
4084 case 0x0A:
4085 case 0x10:
4086 case 0x11:
4087 case 0x13:
4088 case 0x15:
4089 buf.ReadWord();
4090 break;
4092 case 0x08:
4093 case 0x0E:
4094 case 0x0F:
4095 buf.ReadDWord();
4096 break;
4098 default:
4099 ret = CIR_UNKNOWN;
4100 break;
4103 return ret;
4107 * Define properties for objects
4108 * @param id Local ID of the object.
4109 * @param numinfo Number of subsequent objectIDs to change the property for.
4110 * @param prop The property to change.
4111 * @param buf The property value.
4112 * @return ChangeInfoResult.
4114 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4116 ChangeInfoResult ret = CIR_SUCCESS;
4118 if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4119 GrfMsg(1, "ObjectChangeInfo: Too many objects loaded ({}), max ({}). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4120 return CIR_INVALID_ID;
4123 /* Allocate object specs if they haven't been allocated already. */
4124 if (_cur.grffile->objectspec.size() < id + numinfo) _cur.grffile->objectspec.resize(id + numinfo);
4126 for (int i = 0; i < numinfo; i++) {
4127 auto &spec = _cur.grffile->objectspec[id + i];
4129 if (prop != 0x08 && spec == nullptr) {
4130 /* If the object property 08 is not yet set, ignore this property */
4131 ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4132 if (cir > ret) ret = cir;
4133 continue;
4136 switch (prop) {
4137 case 0x08: { // Class ID
4138 /* Allocate space for this object. */
4139 if (spec == nullptr) {
4140 spec = std::make_unique<ObjectSpec>();
4141 spec->views = 1; // Default for NewGRFs that don't set it.
4142 spec->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
4145 /* Swap classid because we read it in BE. */
4146 uint32_t classid = buf.ReadDWord();
4147 spec->class_index = ObjectClass::Allocate(BSWAP32(classid));
4148 break;
4151 case 0x09: { // Class name
4152 AddStringForMapping(buf.ReadWord(), [spec = spec.get()](StringID str) { ObjectClass::Get(spec->class_index)->name = str; });
4153 break;
4156 case 0x0A: // Object name
4157 AddStringForMapping(buf.ReadWord(), &spec->name);
4158 break;
4160 case 0x0B: // Climate mask
4161 spec->climate = buf.ReadByte();
4162 break;
4164 case 0x0C: // Size
4165 spec->size = buf.ReadByte();
4166 if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4167 GrfMsg(0, "ObjectChangeInfo: Invalid object size requested (0x{:X}) for object id {}. Ignoring.", spec->size, id + i);
4168 spec->size = OBJECT_SIZE_1X1;
4170 break;
4172 case 0x0D: // Build cost multipler
4173 spec->build_cost_multiplier = buf.ReadByte();
4174 spec->clear_cost_multiplier = spec->build_cost_multiplier;
4175 break;
4177 case 0x0E: // Introduction date
4178 spec->introduction_date = buf.ReadDWord();
4179 break;
4181 case 0x0F: // End of life
4182 spec->end_of_life_date = buf.ReadDWord();
4183 break;
4185 case 0x10: // Flags
4186 spec->flags = (ObjectFlags)buf.ReadWord();
4187 _loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
4188 break;
4190 case 0x11: // Animation info
4191 spec->animation.frames = buf.ReadByte();
4192 spec->animation.status = buf.ReadByte();
4193 break;
4195 case 0x12: // Animation speed
4196 spec->animation.speed = buf.ReadByte();
4197 break;
4199 case 0x13: // Animation triggers
4200 spec->animation.triggers = buf.ReadWord();
4201 break;
4203 case 0x14: // Removal cost multiplier
4204 spec->clear_cost_multiplier = buf.ReadByte();
4205 break;
4207 case 0x15: // Callback mask
4208 spec->callback_mask = buf.ReadWord();
4209 break;
4211 case 0x16: // Building height
4212 spec->height = buf.ReadByte();
4213 break;
4215 case 0x17: // Views
4216 spec->views = buf.ReadByte();
4217 if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4218 GrfMsg(2, "ObjectChangeInfo: Invalid number of views ({}) for object id {}. Ignoring.", spec->views, id + i);
4219 spec->views = 1;
4221 break;
4223 case 0x18: // Amount placed on 256^2 map on map creation
4224 spec->generate_amount = buf.ReadByte();
4225 break;
4227 default:
4228 ret = CIR_UNKNOWN;
4229 break;
4233 return ret;
4237 * Define properties for railtypes
4238 * @param id ID of the railtype.
4239 * @param numinfo Number of subsequent IDs to change the property for.
4240 * @param prop The property to change.
4241 * @param buf The property value.
4242 * @return ChangeInfoResult.
4244 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4246 ChangeInfoResult ret = CIR_SUCCESS;
4248 extern RailTypeInfo _railtypes[RAILTYPE_END];
4250 if (id + numinfo > RAILTYPE_END) {
4251 GrfMsg(1, "RailTypeChangeInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4252 return CIR_INVALID_ID;
4255 for (int i = 0; i < numinfo; i++) {
4256 RailType rt = _cur.grffile->railtype_map[id + i];
4257 if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4259 RailTypeInfo *rti = &_railtypes[rt];
4261 switch (prop) {
4262 case 0x08: // Label of rail type
4263 /* Skipped here as this is loaded during reservation stage. */
4264 buf.ReadDWord();
4265 break;
4267 case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4268 uint16_t str = buf.ReadWord();
4269 AddStringForMapping(str, &rti->strings.toolbar_caption);
4270 if (_cur.grffile->grf_version < 8) {
4271 AddStringForMapping(str, &rti->strings.name);
4273 break;
4276 case 0x0A: // Menu text of railtype
4277 AddStringForMapping(buf.ReadWord(), &rti->strings.menu_text);
4278 break;
4280 case 0x0B: // Build window caption
4281 AddStringForMapping(buf.ReadWord(), &rti->strings.build_caption);
4282 break;
4284 case 0x0C: // Autoreplace text
4285 AddStringForMapping(buf.ReadWord(), &rti->strings.replace_text);
4286 break;
4288 case 0x0D: // New locomotive text
4289 AddStringForMapping(buf.ReadWord(), &rti->strings.new_loco);
4290 break;
4292 case 0x0E: // Compatible railtype list
4293 case 0x0F: // Powered railtype list
4294 case 0x18: // Railtype list required for date introduction
4295 case 0x19: // Introduced railtype list
4297 /* Rail type compatibility bits are added to the existing bits
4298 * to allow multiple GRFs to modify compatibility with the
4299 * default rail types. */
4300 int n = buf.ReadByte();
4301 for (int j = 0; j != n; j++) {
4302 RailTypeLabel label = buf.ReadDWord();
4303 RailType resolved_rt = GetRailTypeByLabel(BSWAP32(label), false);
4304 if (resolved_rt != INVALID_RAILTYPE) {
4305 switch (prop) {
4306 case 0x0F: SetBit(rti->powered_railtypes, resolved_rt); [[fallthrough]]; // Powered implies compatible.
4307 case 0x0E: SetBit(rti->compatible_railtypes, resolved_rt); break;
4308 case 0x18: SetBit(rti->introduction_required_railtypes, resolved_rt); break;
4309 case 0x19: SetBit(rti->introduces_railtypes, resolved_rt); break;
4313 break;
4316 case 0x10: // Rail Type flags
4317 rti->flags = (RailTypeFlags)buf.ReadByte();
4318 break;
4320 case 0x11: // Curve speed advantage
4321 rti->curve_speed = buf.ReadByte();
4322 break;
4324 case 0x12: // Station graphic
4325 rti->fallback_railtype = Clamp(buf.ReadByte(), 0, 2);
4326 break;
4328 case 0x13: // Construction cost factor
4329 rti->cost_multiplier = buf.ReadWord();
4330 break;
4332 case 0x14: // Speed limit
4333 rti->max_speed = buf.ReadWord();
4334 break;
4336 case 0x15: // Acceleration model
4337 rti->acceleration_type = Clamp(buf.ReadByte(), 0, 2);
4338 break;
4340 case 0x16: // Map colour
4341 rti->map_colour = buf.ReadByte();
4342 break;
4344 case 0x17: // Introduction date
4345 rti->introduction_date = buf.ReadDWord();
4346 break;
4348 case 0x1A: // Sort order
4349 rti->sorting_order = buf.ReadByte();
4350 break;
4352 case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4353 AddStringForMapping(buf.ReadWord(), &rti->strings.name);
4354 break;
4356 case 0x1C: // Maintenance cost factor
4357 rti->maintenance_multiplier = buf.ReadWord();
4358 break;
4360 case 0x1D: // Alternate rail type label list
4361 /* Skipped here as this is loaded during reservation stage. */
4362 for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4363 break;
4365 default:
4366 ret = CIR_UNKNOWN;
4367 break;
4371 return ret;
4374 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf)
4376 ChangeInfoResult ret = CIR_SUCCESS;
4378 extern RailTypeInfo _railtypes[RAILTYPE_END];
4380 if (id + numinfo > RAILTYPE_END) {
4381 GrfMsg(1, "RailTypeReserveInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4382 return CIR_INVALID_ID;
4385 for (int i = 0; i < numinfo; i++) {
4386 switch (prop) {
4387 case 0x08: // Label of rail type
4389 RailTypeLabel rtl = buf.ReadDWord();
4390 rtl = BSWAP32(rtl);
4392 RailType rt = GetRailTypeByLabel(rtl, false);
4393 if (rt == INVALID_RAILTYPE) {
4394 /* Set up new rail type */
4395 rt = AllocateRailType(rtl);
4398 _cur.grffile->railtype_map[id + i] = rt;
4399 break;
4402 case 0x09: // Toolbar caption of railtype
4403 case 0x0A: // Menu text
4404 case 0x0B: // Build window caption
4405 case 0x0C: // Autoreplace text
4406 case 0x0D: // New loco
4407 case 0x13: // Construction cost
4408 case 0x14: // Speed limit
4409 case 0x1B: // Name of railtype
4410 case 0x1C: // Maintenance cost factor
4411 buf.ReadWord();
4412 break;
4414 case 0x1D: // Alternate rail type label list
4415 if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4416 int n = buf.ReadByte();
4417 for (int j = 0; j != n; j++) {
4418 _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf.ReadDWord()));
4420 break;
4422 GrfMsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type {} because no label was set", id + i);
4423 [[fallthrough]];
4425 case 0x0E: // Compatible railtype list
4426 case 0x0F: // Powered railtype list
4427 case 0x18: // Railtype list required for date introduction
4428 case 0x19: // Introduced railtype list
4429 for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4430 break;
4432 case 0x10: // Rail Type flags
4433 case 0x11: // Curve speed advantage
4434 case 0x12: // Station graphic
4435 case 0x15: // Acceleration model
4436 case 0x16: // Map colour
4437 case 0x1A: // Sort order
4438 buf.ReadByte();
4439 break;
4441 case 0x17: // Introduction date
4442 buf.ReadDWord();
4443 break;
4445 default:
4446 ret = CIR_UNKNOWN;
4447 break;
4451 return ret;
4455 * Define properties for roadtypes
4456 * @param id ID of the roadtype.
4457 * @param numinfo Number of subsequent IDs to change the property for.
4458 * @param prop The property to change.
4459 * @param buf The property value.
4460 * @return ChangeInfoResult.
4462 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf, RoadTramType rtt)
4464 ChangeInfoResult ret = CIR_SUCCESS;
4466 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4467 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4469 if (id + numinfo > ROADTYPE_END) {
4470 GrfMsg(1, "RoadTypeChangeInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4471 return CIR_INVALID_ID;
4474 for (int i = 0; i < numinfo; i++) {
4475 RoadType rt = type_map[id + i];
4476 if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4478 RoadTypeInfo *rti = &_roadtypes[rt];
4480 switch (prop) {
4481 case 0x08: // Label of road type
4482 /* Skipped here as this is loaded during reservation stage. */
4483 buf.ReadDWord();
4484 break;
4486 case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4487 uint16_t str = buf.ReadWord();
4488 AddStringForMapping(str, &rti->strings.toolbar_caption);
4489 break;
4492 case 0x0A: // Menu text of roadtype
4493 AddStringForMapping(buf.ReadWord(), &rti->strings.menu_text);
4494 break;
4496 case 0x0B: // Build window caption
4497 AddStringForMapping(buf.ReadWord(), &rti->strings.build_caption);
4498 break;
4500 case 0x0C: // Autoreplace text
4501 AddStringForMapping(buf.ReadWord(), &rti->strings.replace_text);
4502 break;
4504 case 0x0D: // New engine text
4505 AddStringForMapping(buf.ReadWord(), &rti->strings.new_engine);
4506 break;
4508 case 0x0F: // Powered roadtype list
4509 case 0x18: // Roadtype list required for date introduction
4510 case 0x19: { // Introduced roadtype list
4511 /* Road type compatibility bits are added to the existing bits
4512 * to allow multiple GRFs to modify compatibility with the
4513 * default road types. */
4514 int n = buf.ReadByte();
4515 for (int j = 0; j != n; j++) {
4516 RoadTypeLabel label = buf.ReadDWord();
4517 RoadType resolved_rt = GetRoadTypeByLabel(BSWAP32(label), false);
4518 if (resolved_rt != INVALID_ROADTYPE) {
4519 switch (prop) {
4520 case 0x0F:
4521 if (GetRoadTramType(resolved_rt) == rtt) {
4522 SetBit(rti->powered_roadtypes, resolved_rt);
4523 } else {
4524 GrfMsg(1, "RoadTypeChangeInfo: Powered road type list: Road type {} road/tram type does not match road type {}, ignoring", resolved_rt, rt);
4526 break;
4527 case 0x18: SetBit(rti->introduction_required_roadtypes, resolved_rt); break;
4528 case 0x19: SetBit(rti->introduces_roadtypes, resolved_rt); break;
4532 break;
4535 case 0x10: // Road Type flags
4536 rti->flags = (RoadTypeFlags)buf.ReadByte();
4537 break;
4539 case 0x13: // Construction cost factor
4540 rti->cost_multiplier = buf.ReadWord();
4541 break;
4543 case 0x14: // Speed limit
4544 rti->max_speed = buf.ReadWord();
4545 break;
4547 case 0x16: // Map colour
4548 rti->map_colour = buf.ReadByte();
4549 break;
4551 case 0x17: // Introduction date
4552 rti->introduction_date = buf.ReadDWord();
4553 break;
4555 case 0x1A: // Sort order
4556 rti->sorting_order = buf.ReadByte();
4557 break;
4559 case 0x1B: // Name of roadtype
4560 AddStringForMapping(buf.ReadWord(), &rti->strings.name);
4561 break;
4563 case 0x1C: // Maintenance cost factor
4564 rti->maintenance_multiplier = buf.ReadWord();
4565 break;
4567 case 0x1D: // Alternate road type label list
4568 /* Skipped here as this is loaded during reservation stage. */
4569 for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4570 break;
4572 default:
4573 ret = CIR_UNKNOWN;
4574 break;
4578 return ret;
4581 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4583 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4586 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4588 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4592 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf, RoadTramType rtt)
4594 ChangeInfoResult ret = CIR_SUCCESS;
4596 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4597 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4599 if (id + numinfo > ROADTYPE_END) {
4600 GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4601 return CIR_INVALID_ID;
4604 for (int i = 0; i < numinfo; i++) {
4605 switch (prop) {
4606 case 0x08: { // Label of road type
4607 RoadTypeLabel rtl = buf.ReadDWord();
4608 rtl = BSWAP32(rtl);
4610 RoadType rt = GetRoadTypeByLabel(rtl, false);
4611 if (rt == INVALID_ROADTYPE) {
4612 /* Set up new road type */
4613 rt = AllocateRoadType(rtl, rtt);
4614 } else if (GetRoadTramType(rt) != rtt) {
4615 GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid type (road/tram), ignoring", id + numinfo);
4616 return CIR_INVALID_ID;
4619 type_map[id + i] = rt;
4620 break;
4622 case 0x09: // Toolbar caption of roadtype
4623 case 0x0A: // Menu text
4624 case 0x0B: // Build window caption
4625 case 0x0C: // Autoreplace text
4626 case 0x0D: // New loco
4627 case 0x13: // Construction cost
4628 case 0x14: // Speed limit
4629 case 0x1B: // Name of roadtype
4630 case 0x1C: // Maintenance cost factor
4631 buf.ReadWord();
4632 break;
4634 case 0x1D: // Alternate road type label list
4635 if (type_map[id + i] != INVALID_ROADTYPE) {
4636 int n = buf.ReadByte();
4637 for (int j = 0; j != n; j++) {
4638 _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf.ReadDWord()));
4640 break;
4642 GrfMsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type {} because no label was set", id + i);
4643 /* FALL THROUGH */
4645 case 0x0F: // Powered roadtype list
4646 case 0x18: // Roadtype list required for date introduction
4647 case 0x19: // Introduced roadtype list
4648 for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4649 break;
4651 case 0x10: // Road Type flags
4652 case 0x16: // Map colour
4653 case 0x1A: // Sort order
4654 buf.ReadByte();
4655 break;
4657 case 0x17: // Introduction date
4658 buf.ReadDWord();
4659 break;
4661 default:
4662 ret = CIR_UNKNOWN;
4663 break;
4667 return ret;
4670 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf)
4672 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4675 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf)
4677 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4680 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader &buf)
4682 ChangeInfoResult ret = CIR_SUCCESS;
4684 if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4685 GrfMsg(1, "AirportTileChangeInfo: Too many airport tiles loaded ({}), max ({}). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4686 return CIR_INVALID_ID;
4689 /* Allocate airport tile specs if they haven't been allocated already. */
4690 if (_cur.grffile->airtspec.size() < airtid + numinfo) _cur.grffile->airtspec.resize(airtid + numinfo);
4692 for (int i = 0; i < numinfo; i++) {
4693 auto &tsp = _cur.grffile->airtspec[airtid + i];
4695 if (prop != 0x08 && tsp == nullptr) {
4696 GrfMsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile {}. Ignoring.", airtid + i);
4697 return CIR_INVALID_ID;
4700 switch (prop) {
4701 case 0x08: { // Substitute airport tile type
4702 uint8_t subs_id = buf.ReadByte();
4703 if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4704 /* The substitute id must be one of the original airport tiles. */
4705 GrfMsg(2, "AirportTileChangeInfo: Attempt to use new airport tile {} as substitute airport tile for {}. Ignoring.", subs_id, airtid + i);
4706 continue;
4709 /* Allocate space for this airport tile. */
4710 if (tsp == nullptr) {
4711 tsp = std::make_unique<AirportTileSpec>(*AirportTileSpec::Get(subs_id));
4713 tsp->enabled = true;
4715 tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
4717 tsp->grf_prop.local_id = airtid + i;
4718 tsp->grf_prop.subst_id = subs_id;
4719 tsp->grf_prop.grffile = _cur.grffile;
4720 _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4722 break;
4725 case 0x09: { // Airport tile override
4726 uint8_t override = buf.ReadByte();
4728 /* The airport tile being overridden must be an original airport tile. */
4729 if (override >= NEW_AIRPORTTILE_OFFSET) {
4730 GrfMsg(2, "AirportTileChangeInfo: Attempt to override new airport tile {} with airport tile id {}. Ignoring.", override, airtid + i);
4731 continue;
4734 _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4735 break;
4738 case 0x0E: // Callback mask
4739 tsp->callback_mask = buf.ReadByte();
4740 break;
4742 case 0x0F: // Animation information
4743 tsp->animation.frames = buf.ReadByte();
4744 tsp->animation.status = buf.ReadByte();
4745 break;
4747 case 0x10: // Animation speed
4748 tsp->animation.speed = buf.ReadByte();
4749 break;
4751 case 0x11: // Animation triggers
4752 tsp->animation.triggers = buf.ReadByte();
4753 break;
4755 default:
4756 ret = CIR_UNKNOWN;
4757 break;
4761 return ret;
4765 * Ignore properties for roadstops
4766 * @param prop The property to ignore.
4767 * @param buf The property value.
4768 * @return ChangeInfoResult.
4770 static ChangeInfoResult IgnoreRoadStopProperty(uint prop, ByteReader &buf)
4772 ChangeInfoResult ret = CIR_SUCCESS;
4774 switch (prop) {
4775 case 0x09:
4776 case 0x0C:
4777 case 0x0F:
4778 case 0x11:
4779 buf.ReadByte();
4780 break;
4782 case 0x0A:
4783 case 0x0B:
4784 case 0x0E:
4785 case 0x10:
4786 case 0x15:
4787 buf.ReadWord();
4788 break;
4790 case 0x08:
4791 case 0x0D:
4792 case 0x12:
4793 buf.ReadDWord();
4794 break;
4796 default:
4797 ret = CIR_UNKNOWN;
4798 break;
4801 return ret;
4804 static ChangeInfoResult RoadStopChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4806 ChangeInfoResult ret = CIR_SUCCESS;
4808 if (id + numinfo > NUM_ROADSTOPS_PER_GRF) {
4809 GrfMsg(1, "RoadStopChangeInfo: RoadStop {} is invalid, max {}, ignoring", id + numinfo, NUM_ROADSTOPS_PER_GRF);
4810 return CIR_INVALID_ID;
4813 if (_cur.grffile->roadstops.size() < id + numinfo) _cur.grffile->roadstops.resize(id + numinfo);
4815 for (int i = 0; i < numinfo; i++) {
4816 auto &rs = _cur.grffile->roadstops[id + i];
4818 if (rs == nullptr && prop != 0x08) {
4819 GrfMsg(1, "RoadStopChangeInfo: Attempt to modify undefined road stop {}, ignoring", id + i);
4820 ChangeInfoResult cir = IgnoreRoadStopProperty(prop, buf);
4821 if (cir > ret) ret = cir;
4822 continue;
4825 switch (prop) {
4826 case 0x08: { // Road Stop Class ID
4827 if (rs == nullptr) {
4828 rs = std::make_unique<RoadStopSpec>();
4831 uint32_t classid = buf.ReadDWord();
4832 rs->class_index = RoadStopClass::Allocate(BSWAP32(classid));
4833 break;
4836 case 0x09: // Road stop type
4837 rs->stop_type = (RoadStopAvailabilityType)buf.ReadByte();
4838 break;
4840 case 0x0A: // Road Stop Name
4841 AddStringForMapping(buf.ReadWord(), &rs->name);
4842 break;
4844 case 0x0B: // Road Stop Class name
4845 AddStringForMapping(buf.ReadWord(), [rs = rs.get()](StringID str) { RoadStopClass::Get(rs->class_index)->name = str; });
4846 break;
4848 case 0x0C: // The draw mode
4849 rs->draw_mode = static_cast<RoadStopDrawMode>(buf.ReadByte());
4850 break;
4852 case 0x0D: // Cargo types for random triggers
4853 rs->cargo_triggers = TranslateRefitMask(buf.ReadDWord());
4854 break;
4856 case 0x0E: // Animation info
4857 rs->animation.frames = buf.ReadByte();
4858 rs->animation.status = buf.ReadByte();
4859 break;
4861 case 0x0F: // Animation speed
4862 rs->animation.speed = buf.ReadByte();
4863 break;
4865 case 0x10: // Animation triggers
4866 rs->animation.triggers = buf.ReadWord();
4867 break;
4869 case 0x11: // Callback mask
4870 rs->callback_mask = buf.ReadByte();
4871 break;
4873 case 0x12: // General flags
4874 rs->flags = (uint16_t)buf.ReadDWord(); // Future-proofing, size this as 4 bytes, but we only need two byte's worth of flags at present
4875 break;
4877 case 0x15: // Cost multipliers
4878 rs->build_cost_multiplier = buf.ReadByte();
4879 rs->clear_cost_multiplier = buf.ReadByte();
4880 break;
4882 default:
4883 ret = CIR_UNKNOWN;
4884 break;
4888 return ret;
4891 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8_t feature, uint8_t property)
4893 switch (cir) {
4894 default: NOT_REACHED();
4896 case CIR_DISABLED:
4897 /* Error has already been printed; just stop parsing */
4898 return true;
4900 case CIR_SUCCESS:
4901 return false;
4903 case CIR_UNHANDLED:
4904 GrfMsg(1, "{}: Ignoring property 0x{:02X} of feature 0x{:02X} (not implemented)", caller, property, feature);
4905 return false;
4907 case CIR_UNKNOWN:
4908 GrfMsg(0, "{}: Unknown property 0x{:02X} of feature 0x{:02X}, disabling", caller, property, feature);
4909 [[fallthrough]];
4911 case CIR_INVALID_ID: {
4912 /* No debug message for an invalid ID, as it has already been output */
4913 GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4914 if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4915 return true;
4920 /* Action 0x00 */
4921 static void FeatureChangeInfo(ByteReader &buf)
4923 /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4925 * B feature
4926 * B num-props how many properties to change per vehicle/station
4927 * B num-info how many vehicles/stations to change
4928 * E id ID of first vehicle/station to change, if num-info is
4929 * greater than one, this one and the following
4930 * vehicles/stations will be changed
4931 * B property what property to change, depends on the feature
4932 * V new-info new bytes of info (variable size; depends on properties) */
4934 static const VCI_Handler handler[] = {
4935 /* GSF_TRAINS */ RailVehicleChangeInfo,
4936 /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4937 /* GSF_SHIPS */ ShipVehicleChangeInfo,
4938 /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4939 /* GSF_STATIONS */ StationChangeInfo,
4940 /* GSF_CANALS */ CanalChangeInfo,
4941 /* GSF_BRIDGES */ BridgeChangeInfo,
4942 /* GSF_HOUSES */ TownHouseChangeInfo,
4943 /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4944 /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4945 /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4946 /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4947 /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4948 /* GSF_AIRPORTS */ AirportChangeInfo,
4949 /* GSF_SIGNALS */ nullptr,
4950 /* GSF_OBJECTS */ ObjectChangeInfo,
4951 /* GSF_RAILTYPES */ RailTypeChangeInfo,
4952 /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4953 /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4954 /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4955 /* GSF_ROADSTOPS */ RoadStopChangeInfo,
4957 static_assert(GSF_END == lengthof(handler));
4959 uint8_t feature = buf.ReadByte();
4960 uint8_t numprops = buf.ReadByte();
4961 uint numinfo = buf.ReadByte();
4962 uint engine = buf.ReadExtendedByte();
4964 if (feature >= GSF_END) {
4965 GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4966 return;
4969 GrfMsg(6, "FeatureChangeInfo: Feature 0x{:02X}, {} properties, to apply to {}+{}",
4970 feature, numprops, engine, numinfo);
4972 if (handler[feature] == nullptr) {
4973 if (feature != GSF_CARGOES) GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4974 return;
4977 /* Mark the feature as used by the grf */
4978 SetBit(_cur.grffile->grf_features, feature);
4980 while (numprops-- && buf.HasData()) {
4981 uint8_t prop = buf.ReadByte();
4983 ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4984 if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4988 /* Action 0x00 (GLS_SAFETYSCAN) */
4989 static void SafeChangeInfo(ByteReader &buf)
4991 uint8_t feature = buf.ReadByte();
4992 uint8_t numprops = buf.ReadByte();
4993 uint numinfo = buf.ReadByte();
4994 buf.ReadExtendedByte(); // id
4996 if (feature == GSF_BRIDGES && numprops == 1) {
4997 uint8_t prop = buf.ReadByte();
4998 /* Bridge property 0x0D is redefinition of sprite layout tables, which
4999 * is considered safe. */
5000 if (prop == 0x0D) return;
5001 } else if (feature == GSF_GLOBALVAR && numprops == 1) {
5002 uint8_t prop = buf.ReadByte();
5003 /* Engine ID Mappings are safe, if the source is static */
5004 if (prop == 0x11) {
5005 bool is_safe = true;
5006 for (uint i = 0; i < numinfo; i++) {
5007 uint32_t s = buf.ReadDWord();
5008 buf.ReadDWord(); // dest
5009 const GRFConfig *grfconfig = GetGRFConfig(s);
5010 if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
5011 is_safe = false;
5012 break;
5015 if (is_safe) return;
5019 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
5021 /* Skip remainder of GRF */
5022 _cur.skip_sprites = -1;
5025 /* Action 0x00 (GLS_RESERVE) */
5026 static void ReserveChangeInfo(ByteReader &buf)
5028 uint8_t feature = buf.ReadByte();
5030 if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
5032 uint8_t numprops = buf.ReadByte();
5033 uint8_t numinfo = buf.ReadByte();
5034 uint8_t index = buf.ReadExtendedByte();
5036 while (numprops-- && buf.HasData()) {
5037 uint8_t prop = buf.ReadByte();
5038 ChangeInfoResult cir = CIR_SUCCESS;
5040 switch (feature) {
5041 default: NOT_REACHED();
5042 case GSF_CARGOES:
5043 cir = CargoChangeInfo(index, numinfo, prop, buf);
5044 break;
5046 case GSF_GLOBALVAR:
5047 cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
5048 break;
5050 case GSF_RAILTYPES:
5051 cir = RailTypeReserveInfo(index, numinfo, prop, buf);
5052 break;
5054 case GSF_ROADTYPES:
5055 cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
5056 break;
5058 case GSF_TRAMTYPES:
5059 cir = TramTypeReserveInfo(index, numinfo, prop, buf);
5060 break;
5063 if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
5067 /* Action 0x01 */
5068 static void NewSpriteSet(ByteReader &buf)
5070 /* Basic format: <01> <feature> <num-sets> <num-ent>
5071 * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
5073 * B feature feature to define sprites for
5074 * 0, 1, 2, 3: veh-type, 4: train stations
5075 * E first-set first sprite set to define
5076 * B num-sets number of sprite sets (extended byte in extended format)
5077 * E num-ent how many entries per sprite set
5078 * For vehicles, this is the number of different
5079 * vehicle directions in each sprite set
5080 * Set num-dirs=8, unless your sprites are symmetric.
5081 * In that case, use num-dirs=4.
5084 uint8_t feature = buf.ReadByte();
5085 uint16_t num_sets = buf.ReadByte();
5086 uint16_t first_set = 0;
5088 if (num_sets == 0 && buf.HasData(3)) {
5089 /* Extended Action1 format.
5090 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5091 first_set = buf.ReadExtendedByte();
5092 num_sets = buf.ReadExtendedByte();
5094 uint16_t num_ents = buf.ReadExtendedByte();
5096 if (feature >= GSF_END) {
5097 _cur.skip_sprites = num_sets * num_ents;
5098 GrfMsg(1, "NewSpriteSet: Unsupported feature 0x{:02X}, skipping {} sprites", feature, _cur.skip_sprites);
5099 return;
5102 _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
5104 GrfMsg(7, "New sprite set at {} of feature 0x{:02X}, consisting of {} sets with {} views each (total {})",
5105 _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
5108 for (int i = 0; i < num_sets * num_ents; i++) {
5109 _cur.nfo_line++;
5110 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
5114 /* Action 0x01 (SKIP) */
5115 static void SkipAct1(ByteReader &buf)
5117 buf.ReadByte();
5118 uint16_t num_sets = buf.ReadByte();
5120 if (num_sets == 0 && buf.HasData(3)) {
5121 /* Extended Action1 format.
5122 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5123 buf.ReadExtendedByte(); // first_set
5124 num_sets = buf.ReadExtendedByte();
5126 uint16_t num_ents = buf.ReadExtendedByte();
5128 _cur.skip_sprites = num_sets * num_ents;
5130 GrfMsg(3, "SkipAct1: Skipping {} sprites", _cur.skip_sprites);
5133 /* Helper function to either create a callback or link to a previously
5134 * defined spritegroup. */
5135 static const SpriteGroup *GetGroupFromGroupID(uint8_t setid, uint8_t type, uint16_t groupid)
5137 if (HasBit(groupid, 15)) {
5138 assert(CallbackResultSpriteGroup::CanAllocateItem());
5139 return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
5142 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5143 GrfMsg(1, "GetGroupFromGroupID(0x{:02X}:0x{:02X}): Groupid 0x{:04X} does not exist, leaving empty", setid, type, groupid);
5144 return nullptr;
5147 return _cur.spritegroups[groupid];
5151 * Helper function to either create a callback or a result sprite group.
5152 * @param feature GrfSpecFeature to define spritegroup for.
5153 * @param setid SetID of the currently being parsed Action2. (only for debug output)
5154 * @param type Type of the currently being parsed Action2. (only for debug output)
5155 * @param spriteid Raw value from the GRF for the new spritegroup; describes either the return value or the referenced spritegroup.
5156 * @return Created spritegroup.
5158 static const SpriteGroup *CreateGroupFromGroupID(uint8_t feature, uint8_t setid, uint8_t type, uint16_t spriteid)
5160 if (HasBit(spriteid, 15)) {
5161 assert(CallbackResultSpriteGroup::CanAllocateItem());
5162 return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
5165 if (!_cur.IsValidSpriteSet(feature, spriteid)) {
5166 GrfMsg(1, "CreateGroupFromGroupID(0x{:02X}:0x{:02X}): Sprite set {} invalid", setid, type, spriteid);
5167 return nullptr;
5170 SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
5171 uint num_sprites = _cur.GetNumEnts(feature, spriteid);
5173 /* Ensure that the sprites are loeded */
5174 assert(spriteset_start + num_sprites <= _cur.spriteid);
5176 assert(ResultSpriteGroup::CanAllocateItem());
5177 return new ResultSpriteGroup(spriteset_start, num_sprites);
5180 /* Action 0x02 */
5181 static void NewSpriteGroup(ByteReader &buf)
5183 /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5185 * B feature see action 1
5186 * B set-id ID of this particular definition
5187 * B type/num-entries
5188 * if 80 or greater, this is a randomized or variational
5189 * list definition, see below
5190 * otherwise it specifies a number of entries, the exact
5191 * meaning depends on the feature
5192 * V feature-specific-data (huge mess, don't even look it up --pasky) */
5193 const SpriteGroup *act_group = nullptr;
5195 uint8_t feature = buf.ReadByte();
5196 if (feature >= GSF_END) {
5197 GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5198 return;
5201 uint8_t setid = buf.ReadByte();
5202 uint8_t type = buf.ReadByte();
5204 /* Sprite Groups are created here but they are allocated from a pool, so
5205 * we do not need to delete anything if there is an exception from the
5206 * ByteReader. */
5208 switch (type) {
5209 /* Deterministic Sprite Group */
5210 case 0x81: // Self scope, byte
5211 case 0x82: // Parent scope, byte
5212 case 0x85: // Self scope, word
5213 case 0x86: // Parent scope, word
5214 case 0x89: // Self scope, dword
5215 case 0x8A: // Parent scope, dword
5217 uint8_t varadjust;
5218 uint8_t varsize;
5220 assert(DeterministicSpriteGroup::CanAllocateItem());
5221 DeterministicSpriteGroup *group = new DeterministicSpriteGroup();
5222 group->nfo_line = _cur.nfo_line;
5223 act_group = group;
5224 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5226 switch (GB(type, 2, 2)) {
5227 default: NOT_REACHED();
5228 case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5229 case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5230 case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5233 /* Loop through the var adjusts. Unfortunately we don't know how many we have
5234 * from the outset, so we shall have to keep reallocing. */
5235 do {
5236 DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5238 /* The first var adjust doesn't have an operation specified, so we set it to add. */
5239 adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf.ReadByte();
5240 adjust.variable = buf.ReadByte();
5241 if (adjust.variable == 0x7E) {
5242 /* Link subroutine group */
5243 adjust.subroutine = GetGroupFromGroupID(setid, type, buf.ReadByte());
5244 } else {
5245 adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf.ReadByte() : 0;
5248 varadjust = buf.ReadByte();
5249 adjust.shift_num = GB(varadjust, 0, 5);
5250 adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5251 adjust.and_mask = buf.ReadVarSize(varsize);
5253 if (adjust.type != DSGA_TYPE_NONE) {
5254 adjust.add_val = buf.ReadVarSize(varsize);
5255 adjust.divmod_val = buf.ReadVarSize(varsize);
5256 } else {
5257 adjust.add_val = 0;
5258 adjust.divmod_val = 0;
5261 /* Continue reading var adjusts while bit 5 is set. */
5262 } while (HasBit(varadjust, 5));
5264 std::vector<DeterministicSpriteGroupRange> ranges;
5265 ranges.resize(buf.ReadByte());
5266 for (auto &range : ranges) {
5267 range.group = GetGroupFromGroupID(setid, type, buf.ReadWord());
5268 range.low = buf.ReadVarSize(varsize);
5269 range.high = buf.ReadVarSize(varsize);
5272 group->default_group = GetGroupFromGroupID(setid, type, buf.ReadWord());
5273 group->error_group = ranges.empty() ? group->default_group : ranges[0].group;
5274 /* nvar == 0 is a special case -- we turn our value into a callback result */
5275 group->calculated_result = ranges.empty();
5277 /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5278 std::vector<uint32_t> bounds;
5279 bounds.reserve(ranges.size());
5280 for (const auto &range : ranges) {
5281 bounds.push_back(range.low);
5282 if (range.high != UINT32_MAX) bounds.push_back(range.high + 1);
5284 std::sort(bounds.begin(), bounds.end());
5285 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5287 std::vector<const SpriteGroup *> target;
5288 target.reserve(bounds.size());
5289 for (const auto &bound : bounds) {
5290 const SpriteGroup *t = group->default_group;
5291 for (const auto &range : ranges) {
5292 if (range.low <= bound && bound <= range.high) {
5293 t = range.group;
5294 break;
5297 target.push_back(t);
5299 assert(target.size() == bounds.size());
5301 for (uint j = 0; j < bounds.size(); ) {
5302 if (target[j] != group->default_group) {
5303 DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5304 r.group = target[j];
5305 r.low = bounds[j];
5306 while (j < bounds.size() && target[j] == r.group) {
5307 j++;
5309 r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5310 } else {
5311 j++;
5315 break;
5318 /* Randomized Sprite Group */
5319 case 0x80: // Self scope
5320 case 0x83: // Parent scope
5321 case 0x84: // Relative scope
5323 assert(RandomizedSpriteGroup::CanAllocateItem());
5324 RandomizedSpriteGroup *group = new RandomizedSpriteGroup();
5325 group->nfo_line = _cur.nfo_line;
5326 act_group = group;
5327 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5329 if (HasBit(type, 2)) {
5330 if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5331 group->count = buf.ReadByte();
5334 uint8_t triggers = buf.ReadByte();
5335 group->triggers = GB(triggers, 0, 7);
5336 group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5337 group->lowest_randbit = buf.ReadByte();
5339 uint8_t num_groups = buf.ReadByte();
5340 if (!HasExactlyOneBit(num_groups)) {
5341 GrfMsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5344 group->groups.reserve(num_groups);
5345 for (uint i = 0; i < num_groups; i++) {
5346 group->groups.push_back(GetGroupFromGroupID(setid, type, buf.ReadWord()));
5349 break;
5352 /* Neither a variable or randomized sprite group... must be a real group */
5353 default:
5355 switch (feature) {
5356 case GSF_TRAINS:
5357 case GSF_ROADVEHICLES:
5358 case GSF_SHIPS:
5359 case GSF_AIRCRAFT:
5360 case GSF_STATIONS:
5361 case GSF_CANALS:
5362 case GSF_CARGOES:
5363 case GSF_AIRPORTS:
5364 case GSF_RAILTYPES:
5365 case GSF_ROADTYPES:
5366 case GSF_TRAMTYPES:
5368 uint8_t num_loaded = type;
5369 uint8_t num_loading = buf.ReadByte();
5371 if (!_cur.HasValidSpriteSets(feature)) {
5372 GrfMsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5373 return;
5376 GrfMsg(6, "NewSpriteGroup: New SpriteGroup 0x{:02X}, {} loaded, {} loading",
5377 setid, num_loaded, num_loading);
5379 if (num_loaded + num_loading == 0) {
5380 GrfMsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5381 break;
5384 if (num_loaded + num_loading == 1) {
5385 /* Avoid creating 'Real' sprite group if only one option. */
5386 uint16_t spriteid = buf.ReadWord();
5387 act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5388 GrfMsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset {}", spriteid);
5389 break;
5392 std::vector<uint16_t> loaded;
5393 std::vector<uint16_t> loading;
5395 loaded.reserve(num_loaded);
5396 for (uint i = 0; i < num_loaded; i++) {
5397 loaded.push_back(buf.ReadWord());
5398 GrfMsg(8, "NewSpriteGroup: + rg->loaded[{}] = subset {}", i, loaded[i]);
5401 loading.reserve(num_loading);
5402 for (uint i = 0; i < num_loading; i++) {
5403 loading.push_back(buf.ReadWord());
5404 GrfMsg(8, "NewSpriteGroup: + rg->loading[{}] = subset {}", i, loading[i]);
5407 bool loaded_same = !loaded.empty() && std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end();
5408 bool loading_same = !loading.empty() && std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end();
5409 if (loaded_same && loading_same && loaded[0] == loading[0]) {
5410 /* Both lists only contain the same value, so don't create 'Real' sprite group */
5411 act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5412 GrfMsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset {}", loaded[0]);
5413 break;
5416 assert(RealSpriteGroup::CanAllocateItem());
5417 RealSpriteGroup *group = new RealSpriteGroup();
5418 group->nfo_line = _cur.nfo_line;
5419 act_group = group;
5421 if (loaded_same && loaded.size() > 1) loaded.resize(1);
5422 group->loaded.reserve(loaded.size());
5423 for (uint16_t spriteid : loaded) {
5424 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5425 group->loaded.push_back(t);
5428 if (loading_same && loading.size() > 1) loading.resize(1);
5429 group->loading.reserve(loading.size());
5430 for (uint16_t spriteid : loading) {
5431 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5432 group->loading.push_back(t);
5435 break;
5438 case GSF_HOUSES:
5439 case GSF_AIRPORTTILES:
5440 case GSF_OBJECTS:
5441 case GSF_INDUSTRYTILES:
5442 case GSF_ROADSTOPS: {
5443 uint8_t num_building_sprites = std::max((uint8_t)1, type);
5445 assert(TileLayoutSpriteGroup::CanAllocateItem());
5446 TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup();
5447 group->nfo_line = _cur.nfo_line;
5448 act_group = group;
5450 /* On error, bail out immediately. Temporary GRF data was already freed */
5451 if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5452 break;
5455 case GSF_INDUSTRIES: {
5456 if (type > 2) {
5457 GrfMsg(1, "NewSpriteGroup: Unsupported industry production version {}, skipping", type);
5458 break;
5461 assert(IndustryProductionSpriteGroup::CanAllocateItem());
5462 IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup();
5463 group->nfo_line = _cur.nfo_line;
5464 act_group = group;
5465 group->version = type;
5466 if (type == 0) {
5467 group->num_input = INDUSTRY_ORIGINAL_NUM_INPUTS;
5468 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) {
5469 group->subtract_input[i] = (int16_t)buf.ReadWord(); // signed
5471 group->num_output = INDUSTRY_ORIGINAL_NUM_OUTPUTS;
5472 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) {
5473 group->add_output[i] = buf.ReadWord(); // unsigned
5475 group->again = buf.ReadByte();
5476 } else if (type == 1) {
5477 group->num_input = INDUSTRY_ORIGINAL_NUM_INPUTS;
5478 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) {
5479 group->subtract_input[i] = buf.ReadByte();
5481 group->num_output = INDUSTRY_ORIGINAL_NUM_OUTPUTS;
5482 for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) {
5483 group->add_output[i] = buf.ReadByte();
5485 group->again = buf.ReadByte();
5486 } else if (type == 2) {
5487 group->num_input = buf.ReadByte();
5488 if (group->num_input > lengthof(group->subtract_input)) {
5489 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5490 error->data = "too many inputs (max 16)";
5491 return;
5493 for (uint i = 0; i < group->num_input; i++) {
5494 uint8_t rawcargo = buf.ReadByte();
5495 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5496 if (!IsValidCargoID(cargo)) {
5497 /* The mapped cargo is invalid. This is permitted at this point,
5498 * as long as the result is not used. Mark it invalid so this
5499 * can be tested later. */
5500 group->version = 0xFF;
5501 } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5502 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5503 error->data = "duplicate input cargo";
5504 return;
5506 group->cargo_input[i] = cargo;
5507 group->subtract_input[i] = buf.ReadByte();
5509 group->num_output = buf.ReadByte();
5510 if (group->num_output > lengthof(group->add_output)) {
5511 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5512 error->data = "too many outputs (max 16)";
5513 return;
5515 for (uint i = 0; i < group->num_output; i++) {
5516 uint8_t rawcargo = buf.ReadByte();
5517 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5518 if (!IsValidCargoID(cargo)) {
5519 /* Mark this result as invalid to use */
5520 group->version = 0xFF;
5521 } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5522 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5523 error->data = "duplicate output cargo";
5524 return;
5526 group->cargo_output[i] = cargo;
5527 group->add_output[i] = buf.ReadByte();
5529 group->again = buf.ReadByte();
5530 } else {
5531 NOT_REACHED();
5533 break;
5536 /* Loading of Tile Layout and Production Callback groups would happen here */
5537 default: GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5542 _cur.spritegroups[setid] = act_group;
5545 static CargoID TranslateCargo(uint8_t feature, uint8_t ctype)
5547 /* Special cargo types for purchase list and stations */
5548 if ((feature == GSF_STATIONS || feature == GSF_ROADSTOPS) && ctype == 0xFE) return SpriteGroupCargo::SG_DEFAULT_NA;
5549 if (ctype == 0xFF) return SpriteGroupCargo::SG_PURCHASE;
5551 if (_cur.grffile->cargo_list.empty()) {
5552 /* No cargo table, so use bitnum values */
5553 if (ctype >= 32) {
5554 GrfMsg(1, "TranslateCargo: Cargo bitnum {} out of range (max 31), skipping.", ctype);
5555 return INVALID_CARGO;
5558 for (const CargoSpec *cs : CargoSpec::Iterate()) {
5559 if (cs->bitnum == ctype) {
5560 GrfMsg(6, "TranslateCargo: Cargo bitnum {} mapped to cargo type {}.", ctype, cs->Index());
5561 return cs->Index();
5565 GrfMsg(5, "TranslateCargo: Cargo bitnum {} not available in this climate, skipping.", ctype);
5566 return INVALID_CARGO;
5569 /* Check if the cargo type is out of bounds of the cargo translation table */
5570 if (ctype >= _cur.grffile->cargo_list.size()) {
5571 GrfMsg(1, "TranslateCargo: Cargo type {} out of range (max {}), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5572 return INVALID_CARGO;
5575 /* Look up the cargo label from the translation table */
5576 CargoLabel cl = _cur.grffile->cargo_list[ctype];
5577 if (cl == CT_INVALID) {
5578 GrfMsg(5, "TranslateCargo: Cargo type {} not available in this climate, skipping.", ctype);
5579 return INVALID_CARGO;
5582 CargoID cid = GetCargoIDByLabel(cl);
5583 if (!IsValidCargoID(cid)) {
5584 GrfMsg(5, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' unsupported, skipping.", GB(cl.base(), 24, 8), GB(cl.base(), 16, 8), GB(cl.base(), 8, 8), GB(cl.base(), 0, 8));
5585 return INVALID_CARGO;
5588 GrfMsg(6, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' mapped to cargo type {}.", GB(cl.base(), 24, 8), GB(cl.base(), 16, 8), GB(cl.base(), 8, 8), GB(cl.base(), 0, 8), cid);
5589 return cid;
5593 static bool IsValidGroupID(uint16_t groupid, const char *function)
5595 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5596 GrfMsg(1, "{}: Spritegroup 0x{:04X} out of range or empty, skipping.", function, groupid);
5597 return false;
5600 return true;
5603 static void VehicleMapSpriteGroup(ByteReader &buf, uint8_t feature, uint8_t idcount)
5605 static std::vector<EngineID> last_engines; // Engine IDs are remembered in case the next action is a wagon override.
5606 bool wagover = false;
5608 /* Test for 'wagon override' flag */
5609 if (HasBit(idcount, 7)) {
5610 wagover = true;
5611 /* Strip off the flag */
5612 idcount = GB(idcount, 0, 7);
5614 if (last_engines.empty()) {
5615 GrfMsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5616 return;
5619 GrfMsg(6, "VehicleMapSpriteGroup: WagonOverride: {} engines, {} wagons", last_engines.size(), idcount);
5620 } else {
5621 last_engines.resize(idcount);
5624 std::vector<EngineID> engines;
5625 engines.reserve(idcount);
5626 for (uint i = 0; i < idcount; i++) {
5627 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf.ReadExtendedByte());
5628 if (e == nullptr) {
5629 /* No engine could be allocated?!? Deal with it. Okay,
5630 * this might look bad. Also make sure this NewGRF
5631 * gets disabled, as a half loaded one is bad. */
5632 HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5633 return;
5636 engines.push_back(e->index);
5637 if (!wagover) last_engines[i] = engines[i];
5640 uint8_t cidcount = buf.ReadByte();
5641 for (uint c = 0; c < cidcount; c++) {
5642 uint8_t ctype = buf.ReadByte();
5643 uint16_t groupid = buf.ReadWord();
5644 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5646 GrfMsg(8, "VehicleMapSpriteGroup: * [{}] Cargo type 0x{:X}, group id 0x{:02X}", c, ctype, groupid);
5648 CargoID cid = TranslateCargo(feature, ctype);
5649 if (!IsValidCargoID(cid)) continue;
5651 for (uint i = 0; i < idcount; i++) {
5652 EngineID engine = engines[i];
5654 GrfMsg(7, "VehicleMapSpriteGroup: [{}] Engine {}...", i, engine);
5656 if (wagover) {
5657 SetWagonOverrideSprites(engine, cid, _cur.spritegroups[groupid], last_engines);
5658 } else {
5659 SetCustomEngineSprites(engine, cid, _cur.spritegroups[groupid]);
5664 uint16_t groupid = buf.ReadWord();
5665 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5667 GrfMsg(8, "-- Default group id 0x{:04X}", groupid);
5669 for (uint i = 0; i < idcount; i++) {
5670 EngineID engine = engines[i];
5672 if (wagover) {
5673 SetWagonOverrideSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid], last_engines);
5674 } else {
5675 SetCustomEngineSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid]);
5676 SetEngineGRF(engine, _cur.grffile);
5682 static void CanalMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5684 std::vector<uint16_t> cfs;
5685 cfs.reserve(idcount);
5686 for (uint i = 0; i < idcount; i++) {
5687 cfs.push_back(buf.ReadExtendedByte());
5690 uint8_t cidcount = buf.ReadByte();
5691 buf.Skip(cidcount * 3);
5693 uint16_t groupid = buf.ReadWord();
5694 if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5696 for (auto &cf : cfs) {
5697 if (cf >= CF_END) {
5698 GrfMsg(1, "CanalMapSpriteGroup: Canal subset {} out of range, skipping", cf);
5699 continue;
5702 _water_feature[cf].grffile = _cur.grffile;
5703 _water_feature[cf].group = _cur.spritegroups[groupid];
5708 static void StationMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5710 if (_cur.grffile->stations.empty()) {
5711 GrfMsg(1, "StationMapSpriteGroup: No stations defined, skipping");
5712 return;
5715 std::vector<uint16_t> stations;
5716 stations.reserve(idcount);
5717 for (uint i = 0; i < idcount; i++) {
5718 stations.push_back(buf.ReadExtendedByte());
5721 uint8_t cidcount = buf.ReadByte();
5722 for (uint c = 0; c < cidcount; c++) {
5723 uint8_t ctype = buf.ReadByte();
5724 uint16_t groupid = buf.ReadWord();
5725 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5727 ctype = TranslateCargo(GSF_STATIONS, ctype);
5728 if (!IsValidCargoID(ctype)) continue;
5730 for (auto &station : stations) {
5731 StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5733 if (statspec == nullptr) {
5734 GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5735 continue;
5738 statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5742 uint16_t groupid = buf.ReadWord();
5743 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5745 for (auto &station : stations) {
5746 StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5748 if (statspec == nullptr) {
5749 GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5750 continue;
5753 if (statspec->grf_prop.grffile != nullptr) {
5754 GrfMsg(1, "StationMapSpriteGroup: Station {} mapped multiple times, skipping", station);
5755 continue;
5758 statspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
5759 statspec->grf_prop.grffile = _cur.grffile;
5760 statspec->grf_prop.local_id = station;
5761 StationClass::Assign(statspec);
5766 static void TownHouseMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5768 if (_cur.grffile->housespec.empty()) {
5769 GrfMsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5770 return;
5773 std::vector<uint16_t> houses;
5774 houses.reserve(idcount);
5775 for (uint i = 0; i < idcount; i++) {
5776 houses.push_back(buf.ReadExtendedByte());
5779 /* Skip the cargo type section, we only care about the default group */
5780 uint8_t cidcount = buf.ReadByte();
5781 buf.Skip(cidcount * 3);
5783 uint16_t groupid = buf.ReadWord();
5784 if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5786 for (auto &house : houses) {
5787 HouseSpec *hs = house >= _cur.grffile->housespec.size() ? nullptr : _cur.grffile->housespec[house].get();
5789 if (hs == nullptr) {
5790 GrfMsg(1, "TownHouseMapSpriteGroup: House {} undefined, skipping.", house);
5791 continue;
5794 hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5798 static void IndustryMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5800 if (_cur.grffile->industryspec.empty()) {
5801 GrfMsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5802 return;
5805 std::vector<uint16_t> industries;
5806 industries.reserve(idcount);
5807 for (uint i = 0; i < idcount; i++) {
5808 industries.push_back(buf.ReadExtendedByte());
5811 /* Skip the cargo type section, we only care about the default group */
5812 uint8_t cidcount = buf.ReadByte();
5813 buf.Skip(cidcount * 3);
5815 uint16_t groupid = buf.ReadWord();
5816 if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5818 for (auto &industry : industries) {
5819 IndustrySpec *indsp = industry >= _cur.grffile->industryspec.size() ? nullptr : _cur.grffile->industryspec[industry].get();
5821 if (indsp == nullptr) {
5822 GrfMsg(1, "IndustryMapSpriteGroup: Industry {} undefined, skipping", industry);
5823 continue;
5826 indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5830 static void IndustrytileMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5832 if (_cur.grffile->indtspec.empty()) {
5833 GrfMsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5834 return;
5837 std::vector<uint16_t> indtiles;
5838 indtiles.reserve(idcount);
5839 for (uint i = 0; i < idcount; i++) {
5840 indtiles.push_back(buf.ReadExtendedByte());
5843 /* Skip the cargo type section, we only care about the default group */
5844 uint8_t cidcount = buf.ReadByte();
5845 buf.Skip(cidcount * 3);
5847 uint16_t groupid = buf.ReadWord();
5848 if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5850 for (auto &indtile : indtiles) {
5851 IndustryTileSpec *indtsp = indtile >= _cur.grffile->indtspec.size() ? nullptr : _cur.grffile->indtspec[indtile].get();
5853 if (indtsp == nullptr) {
5854 GrfMsg(1, "IndustrytileMapSpriteGroup: Industry tile {} undefined, skipping", indtile);
5855 continue;
5858 indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5862 static void CargoMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5864 std::vector<uint16_t> cargoes;
5865 cargoes.reserve(idcount);
5866 for (uint i = 0; i < idcount; i++) {
5867 cargoes.push_back(buf.ReadExtendedByte());
5870 /* Skip the cargo type section, we only care about the default group */
5871 uint8_t cidcount = buf.ReadByte();
5872 buf.Skip(cidcount * 3);
5874 uint16_t groupid = buf.ReadWord();
5875 if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5877 for (auto &cid : cargoes) {
5878 if (cid >= NUM_CARGO) {
5879 GrfMsg(1, "CargoMapSpriteGroup: Cargo ID {} out of range, skipping", cid);
5880 continue;
5883 CargoSpec *cs = CargoSpec::Get(cid);
5884 cs->grffile = _cur.grffile;
5885 cs->group = _cur.spritegroups[groupid];
5889 static void ObjectMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5891 if (_cur.grffile->objectspec.empty()) {
5892 GrfMsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5893 return;
5896 std::vector<uint16_t> objects;
5897 objects.reserve(idcount);
5898 for (uint i = 0; i < idcount; i++) {
5899 objects.push_back(buf.ReadExtendedByte());
5902 uint8_t cidcount = buf.ReadByte();
5903 for (uint c = 0; c < cidcount; c++) {
5904 uint8_t ctype = buf.ReadByte();
5905 uint16_t groupid = buf.ReadWord();
5906 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5908 /* The only valid option here is purchase list sprite groups. */
5909 if (ctype != 0xFF) {
5910 GrfMsg(1, "ObjectMapSpriteGroup: Invalid cargo bitnum {} for objects, skipping.", ctype);
5911 continue;
5914 for (auto &object : objects) {
5915 ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5917 if (spec == nullptr) {
5918 GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5919 continue;
5922 spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_PURCHASE] = _cur.spritegroups[groupid];
5926 uint16_t groupid = buf.ReadWord();
5927 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5929 for (auto &object : objects) {
5930 ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5932 if (spec == nullptr) {
5933 GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5934 continue;
5937 if (spec->grf_prop.grffile != nullptr) {
5938 GrfMsg(1, "ObjectMapSpriteGroup: Object {} mapped multiple times, skipping", object);
5939 continue;
5942 spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_DEFAULT] = _cur.spritegroups[groupid];
5943 spec->grf_prop.grffile = _cur.grffile;
5944 spec->grf_prop.local_id = object;
5948 static void RailTypeMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5950 std::vector<uint8_t> railtypes;
5951 railtypes.reserve(idcount);
5952 for (uint i = 0; i < idcount; i++) {
5953 uint16_t id = buf.ReadExtendedByte();
5954 railtypes.push_back(id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE);
5957 uint8_t cidcount = buf.ReadByte();
5958 for (uint c = 0; c < cidcount; c++) {
5959 uint8_t ctype = buf.ReadByte();
5960 uint16_t groupid = buf.ReadWord();
5961 if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5963 if (ctype >= RTSG_END) continue;
5965 extern RailTypeInfo _railtypes[RAILTYPE_END];
5966 for (auto &railtype : railtypes) {
5967 if (railtype != INVALID_RAILTYPE) {
5968 RailTypeInfo *rti = &_railtypes[railtype];
5970 rti->grffile[ctype] = _cur.grffile;
5971 rti->group[ctype] = _cur.spritegroups[groupid];
5976 /* Railtypes do not use the default group. */
5977 buf.ReadWord();
5980 static void RoadTypeMapSpriteGroup(ByteReader &buf, uint8_t idcount, RoadTramType rtt)
5982 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5984 std::vector<uint8_t> roadtypes;
5985 roadtypes.reserve(idcount);
5986 for (uint i = 0; i < idcount; i++) {
5987 uint16_t id = buf.ReadExtendedByte();
5988 roadtypes.push_back(id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE);
5991 uint8_t cidcount = buf.ReadByte();
5992 for (uint c = 0; c < cidcount; c++) {
5993 uint8_t ctype = buf.ReadByte();
5994 uint16_t groupid = buf.ReadWord();
5995 if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
5997 if (ctype >= ROTSG_END) continue;
5999 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
6000 for (auto &roadtype : roadtypes) {
6001 if (roadtype != INVALID_ROADTYPE) {
6002 RoadTypeInfo *rti = &_roadtypes[roadtype];
6004 rti->grffile[ctype] = _cur.grffile;
6005 rti->group[ctype] = _cur.spritegroups[groupid];
6010 /* Roadtypes do not use the default group. */
6011 buf.ReadWord();
6014 static void AirportMapSpriteGroup(ByteReader &buf, uint8_t idcount)
6016 if (_cur.grffile->airportspec.empty()) {
6017 GrfMsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
6018 return;
6021 std::vector<uint16_t> airports;
6022 airports.reserve(idcount);
6023 for (uint i = 0; i < idcount; i++) {
6024 airports.push_back(buf.ReadExtendedByte());
6027 /* Skip the cargo type section, we only care about the default group */
6028 uint8_t cidcount = buf.ReadByte();
6029 buf.Skip(cidcount * 3);
6031 uint16_t groupid = buf.ReadWord();
6032 if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
6034 for (auto &airport : airports) {
6035 AirportSpec *as = airport >= _cur.grffile->airportspec.size() ? nullptr : _cur.grffile->airportspec[airport].get();
6037 if (as == nullptr) {
6038 GrfMsg(1, "AirportMapSpriteGroup: Airport {} undefined, skipping", airport);
6039 continue;
6042 as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6046 static void AirportTileMapSpriteGroup(ByteReader &buf, uint8_t idcount)
6048 if (_cur.grffile->airtspec.empty()) {
6049 GrfMsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
6050 return;
6053 std::vector<uint16_t> airptiles;
6054 airptiles.reserve(idcount);
6055 for (uint i = 0; i < idcount; i++) {
6056 airptiles.push_back(buf.ReadExtendedByte());
6059 /* Skip the cargo type section, we only care about the default group */
6060 uint8_t cidcount = buf.ReadByte();
6061 buf.Skip(cidcount * 3);
6063 uint16_t groupid = buf.ReadWord();
6064 if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
6066 for (auto &airptile : airptiles) {
6067 AirportTileSpec *airtsp = airptile >= _cur.grffile->airtspec.size() ? nullptr : _cur.grffile->airtspec[airptile].get();
6069 if (airtsp == nullptr) {
6070 GrfMsg(1, "AirportTileMapSpriteGroup: Airport tile {} undefined, skipping", airptile);
6071 continue;
6074 airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6078 static void RoadStopMapSpriteGroup(ByteReader &buf, uint8_t idcount)
6080 if (_cur.grffile->roadstops.empty()) {
6081 GrfMsg(1, "RoadStopMapSpriteGroup: No roadstops defined, skipping");
6082 return;
6085 std::vector<uint16_t> roadstops;
6086 roadstops.reserve(idcount);
6087 for (uint i = 0; i < idcount; i++) {
6088 roadstops.push_back(buf.ReadExtendedByte());
6091 uint8_t cidcount = buf.ReadByte();
6092 for (uint c = 0; c < cidcount; c++) {
6093 uint8_t ctype = buf.ReadByte();
6094 uint16_t groupid = buf.ReadWord();
6095 if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) continue;
6097 ctype = TranslateCargo(GSF_ROADSTOPS, ctype);
6098 if (!IsValidCargoID(ctype)) continue;
6100 for (auto &roadstop : roadstops) {
6101 RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6103 if (roadstopspec == nullptr) {
6104 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping", roadstop);
6105 continue;
6108 roadstopspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
6112 uint16_t groupid = buf.ReadWord();
6113 if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) return;
6115 for (auto &roadstop : roadstops) {
6116 RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6118 if (roadstopspec == nullptr) {
6119 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping.", roadstop);
6120 continue;
6123 if (roadstopspec->grf_prop.grffile != nullptr) {
6124 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} mapped multiple times, skipping", roadstop);
6125 continue;
6128 roadstopspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
6129 roadstopspec->grf_prop.grffile = _cur.grffile;
6130 roadstopspec->grf_prop.local_id = roadstop;
6131 RoadStopClass::Assign(roadstopspec);
6135 /* Action 0x03 */
6136 static void FeatureMapSpriteGroup(ByteReader &buf)
6138 /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
6139 * id-list := [<id>] [id-list]
6140 * cargo-list := <cargo-type> <cid> [cargo-list]
6142 * B feature see action 0
6143 * B n-id bits 0-6: how many IDs this definition applies to
6144 * bit 7: if set, this is a wagon override definition (see below)
6145 * E ids the IDs for which this definition applies
6146 * B num-cid number of cargo IDs (sprite group IDs) in this definition
6147 * can be zero, in that case the def-cid is used always
6148 * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
6149 * W cid cargo ID (sprite group ID) for this type of cargo
6150 * W def-cid default cargo ID (sprite group ID) */
6152 uint8_t feature = buf.ReadByte();
6153 uint8_t idcount = buf.ReadByte();
6155 if (feature >= GSF_END) {
6156 GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6157 return;
6160 /* If idcount is zero, this is a feature callback */
6161 if (idcount == 0) {
6162 /* Skip number of cargo ids? */
6163 buf.ReadByte();
6164 uint16_t groupid = buf.ReadWord();
6165 if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
6167 GrfMsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x{:02X}", feature);
6169 AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
6170 return;
6173 /* Mark the feature as used by the grf (generic callbacks do not count) */
6174 SetBit(_cur.grffile->grf_features, feature);
6176 GrfMsg(6, "FeatureMapSpriteGroup: Feature 0x{:02X}, {} ids", feature, idcount);
6178 switch (feature) {
6179 case GSF_TRAINS:
6180 case GSF_ROADVEHICLES:
6181 case GSF_SHIPS:
6182 case GSF_AIRCRAFT:
6183 VehicleMapSpriteGroup(buf, feature, idcount);
6184 return;
6186 case GSF_CANALS:
6187 CanalMapSpriteGroup(buf, idcount);
6188 return;
6190 case GSF_STATIONS:
6191 StationMapSpriteGroup(buf, idcount);
6192 return;
6194 case GSF_HOUSES:
6195 TownHouseMapSpriteGroup(buf, idcount);
6196 return;
6198 case GSF_INDUSTRIES:
6199 IndustryMapSpriteGroup(buf, idcount);
6200 return;
6202 case GSF_INDUSTRYTILES:
6203 IndustrytileMapSpriteGroup(buf, idcount);
6204 return;
6206 case GSF_CARGOES:
6207 CargoMapSpriteGroup(buf, idcount);
6208 return;
6210 case GSF_AIRPORTS:
6211 AirportMapSpriteGroup(buf, idcount);
6212 return;
6214 case GSF_OBJECTS:
6215 ObjectMapSpriteGroup(buf, idcount);
6216 break;
6218 case GSF_RAILTYPES:
6219 RailTypeMapSpriteGroup(buf, idcount);
6220 break;
6222 case GSF_ROADTYPES:
6223 RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
6224 break;
6226 case GSF_TRAMTYPES:
6227 RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
6228 break;
6230 case GSF_AIRPORTTILES:
6231 AirportTileMapSpriteGroup(buf, idcount);
6232 return;
6234 case GSF_ROADSTOPS:
6235 RoadStopMapSpriteGroup(buf, idcount);
6236 return;
6238 default:
6239 GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6240 return;
6244 /* Action 0x04 */
6245 static void FeatureNewName(ByteReader &buf)
6247 /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
6249 * B veh-type see action 0 (as 00..07, + 0A
6250 * But IF veh-type = 48, then generic text
6251 * B language-id If bit 6 is set, This is the extended language scheme,
6252 * with up to 64 language.
6253 * Otherwise, it is a mapping where set bits have meaning
6254 * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6255 * Bit 7 set means this is a generic text, not a vehicle one (or else)
6256 * B num-veh number of vehicles which are getting a new name
6257 * B/W offset number of the first vehicle that gets a new name
6258 * Byte : ID of vehicle to change
6259 * Word : ID of string to change/add
6260 * S data new texts, each of them zero-terminated, after
6261 * which the next name begins. */
6263 bool new_scheme = _cur.grffile->grf_version >= 7;
6265 uint8_t feature = buf.ReadByte();
6266 if (feature >= GSF_END && feature != 0x48) {
6267 GrfMsg(1, "FeatureNewName: Unsupported feature 0x{:02X}, skipping", feature);
6268 return;
6271 uint8_t lang = buf.ReadByte();
6272 uint8_t num = buf.ReadByte();
6273 bool generic = HasBit(lang, 7);
6274 uint16_t id;
6275 if (generic) {
6276 id = buf.ReadWord();
6277 } else if (feature <= GSF_AIRCRAFT) {
6278 id = buf.ReadExtendedByte();
6279 } else {
6280 id = buf.ReadByte();
6283 ClrBit(lang, 7);
6285 uint16_t endid = id + num;
6287 GrfMsg(6, "FeatureNewName: About to rename engines {}..{} (feature 0x{:02X}) in language 0x{:02X}",
6288 id, endid, feature, lang);
6290 for (; id < endid && buf.HasData(); id++) {
6291 const std::string_view name = buf.ReadString();
6292 GrfMsg(8, "FeatureNewName: 0x{:04X} <- {}", id, StrMakeValid(name));
6294 switch (feature) {
6295 case GSF_TRAINS:
6296 case GSF_ROADVEHICLES:
6297 case GSF_SHIPS:
6298 case GSF_AIRCRAFT:
6299 if (!generic) {
6300 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6301 if (e == nullptr) break;
6302 StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6303 e->info.string_id = string;
6304 } else {
6305 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6307 break;
6309 default:
6310 if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0x10000)) {
6311 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6312 break;
6315 switch (GB(id, 8, 8)) {
6316 case 0xC4: // Station class name
6317 if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6318 GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6319 } else {
6320 StationClassID class_index = _cur.grffile->stations[GB(id, 0, 8)]->class_index;
6321 StationClass::Get(class_index)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6323 break;
6325 case 0xC5: // Station name
6326 if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6327 GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6328 } else {
6329 _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6331 break;
6333 case 0xC7: // Airporttile name
6334 if (GB(id, 0, 8) >= _cur.grffile->airtspec.size() || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6335 GrfMsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x{:X}, ignoring", GB(id, 0, 8));
6336 } else {
6337 _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6339 break;
6341 case 0xC9: // House name
6342 if (GB(id, 0, 8) >= _cur.grffile->housespec.size() || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6343 GrfMsg(1, "FeatureNewName: Attempt to name undefined house 0x{:X}, ignoring.", GB(id, 0, 8));
6344 } else {
6345 _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6347 break;
6349 default:
6350 GrfMsg(7, "FeatureNewName: Unsupported ID (0x{:04X})", id);
6351 break;
6353 break;
6359 * Sanitize incoming sprite offsets for Action 5 graphics replacements.
6360 * @param num The number of sprites to load.
6361 * @param offset Offset from the base.
6362 * @param max_sprites The maximum number of sprites that can be loaded in this action 5.
6363 * @param name Used for error warnings.
6364 * @return The number of sprites that is going to be skipped.
6366 static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const std::string_view name)
6369 if (offset >= max_sprites) {
6370 GrfMsg(1, "GraphicsNew: {} sprite offset must be less than {}, skipping", name, max_sprites);
6371 uint orig_num = num;
6372 num = 0;
6373 return orig_num;
6376 if (offset + num > max_sprites) {
6377 GrfMsg(4, "GraphicsNew: {} sprite overflow, truncating...", name);
6378 uint orig_num = num;
6379 num = std::max(max_sprites - offset, 0);
6380 return orig_num - num;
6383 return 0;
6387 /** The information about action 5 types. */
6388 static constexpr auto _action5_types = std::to_array<Action5Type>({
6389 /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6390 /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6391 /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6392 /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6393 /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6394 /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6395 /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6396 /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6397 /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6398 /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6399 /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6400 /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6401 /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6402 /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6403 /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6404 /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6405 /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6406 /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6407 /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6408 /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6409 /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6410 /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6411 /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6412 /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6413 /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6414 /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6415 /* 0x19 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROAD_WAYPOINTS_BASE, 1, ROAD_WAYPOINTS_SPRITE_COUNT, "Road waypoints" },
6419 * Get list of all action 5 types
6420 * @return Read-only span of action 5 type information.
6422 std::span<const Action5Type> GetAction5Types()
6424 return _action5_types;
6427 /* Action 0x05 */
6428 static void GraphicsNew(ByteReader &buf)
6430 /* <05> <graphics-type> <num-sprites> <other data...>
6432 * B graphics-type What set of graphics the sprites define.
6433 * E num-sprites How many sprites are in this set?
6434 * V other data Graphics type specific data. Currently unused. */
6436 uint8_t type = buf.ReadByte();
6437 uint16_t num = buf.ReadExtendedByte();
6438 uint16_t offset = HasBit(type, 7) ? buf.ReadExtendedByte() : 0;
6439 ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6441 if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6442 /* Special not-TTDP-compatible case used in openttd.grf
6443 * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6444 GrfMsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6445 LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6446 LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6447 LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6448 LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6449 LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6450 LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6451 LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6452 LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6453 LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6454 LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6455 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
6456 return;
6459 /* Supported type? */
6460 if ((type >= std::size(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6461 GrfMsg(2, "GraphicsNew: Custom graphics (type 0x{:02X}) sprite block of length {} (unimplemented, ignoring)", type, num);
6462 _cur.skip_sprites = num;
6463 return;
6466 const Action5Type *action5_type = &_action5_types[type];
6468 /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6469 * except for the long version of the shore type:
6470 * Ignore offset if not allowed */
6471 if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6472 GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6473 offset = 0;
6476 /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6477 * This does not make sense, if <offset> is allowed */
6478 if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6479 GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) count must be at least {}. Only {} were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num);
6480 _cur.skip_sprites = num;
6481 return;
6484 /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6485 uint16_t skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6486 SpriteID replace = action5_type->sprite_base + offset;
6488 /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6489 GrfMsg(2, "GraphicsNew: Replacing sprites {} to {} of {} (type 0x{:02X}) at SpriteID 0x{:04X}", offset, offset + num - 1, action5_type->name, type, replace);
6491 if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
6493 if (type == 0x0B) {
6494 static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6495 static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6496 if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6497 if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6500 /* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */
6501 bool dup_oneway_sprites = ((type == 0x09) && (offset + num <= SPR_ONEWAY_SLOPE_N_OFFSET));
6503 for (; num > 0; num--) {
6504 _cur.nfo_line++;
6505 int load_index = (replace == 0 ? _cur.spriteid++ : replace++);
6506 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line);
6507 if (dup_oneway_sprites) {
6508 DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_N_OFFSET);
6509 DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_S_OFFSET);
6513 _cur.skip_sprites = skip_num;
6516 /* Action 0x05 (SKIP) */
6517 static void SkipAct5(ByteReader &buf)
6519 /* Ignore type byte */
6520 buf.ReadByte();
6522 /* Skip the sprites of this action */
6523 _cur.skip_sprites = buf.ReadExtendedByte();
6525 GrfMsg(3, "SkipAct5: Skipping {} sprites", _cur.skip_sprites);
6529 * Reads a variable common to VarAction2 and Action7/9/D.
6531 * Returns VarAction2 variable 'param' resp. Action7/9/D variable '0x80 + param'.
6532 * If a variable is not accessible from all four actions, it is handled in the action specific functions.
6534 * @param param variable number (as for VarAction2, for Action7/9/D you have to subtract 0x80 first).
6535 * @param value returns the value of the variable.
6536 * @param grffile NewGRF querying the variable
6537 * @return true iff the variable is known and the value is returned in 'value'.
6539 bool GetGlobalVariable(uint8_t param, uint32_t *value, const GRFFile *grffile)
6541 switch (param) {
6542 case 0x00: // current date
6543 *value = std::max(TimerGameCalendar::date - CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR, TimerGameCalendar::Date(0)).base();
6544 return true;
6546 case 0x01: // current year
6547 *value = (Clamp(TimerGameCalendar::year, CalendarTime::ORIGINAL_BASE_YEAR, CalendarTime::ORIGINAL_MAX_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base();
6548 return true;
6550 case 0x02: { // detailed date information: month of year (bit 0-7), day of month (bit 8-12), leap year (bit 15), day of year (bit 16-24)
6551 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date);
6552 TimerGameCalendar::Date start_of_year = TimerGameCalendar::ConvertYMDToDate(ymd.year, 0, 1);
6553 *value = ymd.month | (ymd.day - 1) << 8 | (TimerGameCalendar::IsLeapYear(ymd.year) ? 1 << 15 : 0) | (TimerGameCalendar::date - start_of_year).base() << 16;
6554 return true;
6557 case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6558 *value = _settings_game.game_creation.landscape;
6559 return true;
6561 case 0x06: // road traffic side, bit 4 clear=left, set=right
6562 *value = _settings_game.vehicle.road_side << 4;
6563 return true;
6565 case 0x09: // date fraction
6566 *value = TimerGameCalendar::date_fract * 885;
6567 return true;
6569 case 0x0A: // animation counter
6570 *value = GB(TimerGameTick::counter, 0, 16);
6571 return true;
6573 case 0x0B: { // TTDPatch version
6574 uint major = 2;
6575 uint minor = 6;
6576 uint revision = 1; // special case: 2.0.1 is 2.0.10
6577 uint build = 1382;
6578 *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6579 return true;
6582 case 0x0D: // TTD Version, 00=DOS, 01=Windows
6583 *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6584 return true;
6586 case 0x0E: // Y-offset for train sprites
6587 *value = _cur.grffile->traininfo_vehicle_pitch;
6588 return true;
6590 case 0x0F: // Rail track type cost factors
6591 *value = 0;
6592 SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6593 if (_settings_game.vehicle.disable_elrails) {
6594 /* skip elrail multiplier - disabled */
6595 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6596 } else {
6597 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6598 /* Skip monorail multiplier - no space in result */
6600 SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6601 return true;
6603 case 0x11: // current rail tool type
6604 *value = 0; // constant fake value to avoid desync
6605 return true;
6607 case 0x12: // Game mode
6608 *value = _game_mode;
6609 return true;
6611 /* case 0x13: // Tile refresh offset to left not implemented */
6612 /* case 0x14: // Tile refresh offset to right not implemented */
6613 /* case 0x15: // Tile refresh offset upwards not implemented */
6614 /* case 0x16: // Tile refresh offset downwards not implemented */
6615 /* case 0x17: // temperate snow line not implemented */
6617 case 0x1A: // Always -1
6618 *value = UINT_MAX;
6619 return true;
6621 case 0x1B: // Display options
6622 *value = 0x3F; // constant fake value to avoid desync
6623 return true;
6625 case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6626 *value = 1;
6627 return true;
6629 case 0x1E: // Miscellaneous GRF features
6630 *value = _misc_grf_features;
6632 /* Add the local flags */
6633 assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6634 if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6635 return true;
6637 /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6639 case 0x20: { // snow line height
6640 uint8_t snowline = GetSnowLine();
6641 if (_settings_game.game_creation.landscape == LT_ARCTIC && snowline <= _settings_game.construction.map_height_limit) {
6642 *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6643 } else {
6644 /* No snow */
6645 *value = 0xFF;
6647 return true;
6650 case 0x21: // OpenTTD version
6651 *value = _openttd_newgrf_version;
6652 return true;
6654 case 0x22: // difficulty level
6655 *value = SP_CUSTOM;
6656 return true;
6658 case 0x23: // long format date
6659 *value = TimerGameCalendar::date.base();
6660 return true;
6662 case 0x24: // long format year
6663 *value = TimerGameCalendar::year.base();
6664 return true;
6666 default: return false;
6670 static uint32_t GetParamVal(uint8_t param, uint32_t *cond_val)
6672 /* First handle variable common with VarAction2 */
6673 uint32_t value;
6674 if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6677 /* Non-common variable */
6678 switch (param) {
6679 case 0x84: { // GRF loading stage
6680 uint32_t res = 0;
6682 if (_cur.stage > GLS_INIT) SetBit(res, 0);
6683 if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6684 if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6685 return res;
6688 case 0x85: // TTDPatch flags, only for bit tests
6689 if (cond_val == nullptr) {
6690 /* Supported in Action 0x07 and 0x09, not 0x0D */
6691 return 0;
6692 } else {
6693 uint32_t index = *cond_val / 0x20;
6694 uint32_t param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6695 *cond_val %= 0x20;
6696 return param_val;
6699 case 0x88: // GRF ID check
6700 return 0;
6702 /* case 0x99: Global ID offset not implemented */
6704 default:
6705 /* GRF Parameter */
6706 if (param < 0x80) return _cur.grffile->GetParam(param);
6708 /* In-game variable. */
6709 GrfMsg(1, "Unsupported in-game variable 0x{:02X}", param);
6710 return UINT_MAX;
6714 /* Action 0x06 */
6715 static void CfgApply(ByteReader &buf)
6717 /* <06> <param-num> <param-size> <offset> ... <FF>
6719 * B param-num Number of parameter to substitute (First = "zero")
6720 * Ignored if that parameter was not specified in newgrf.cfg
6721 * B param-size How many bytes to replace. If larger than 4, the
6722 * bytes of the following parameter are used. In that
6723 * case, nothing is applied unless *all* parameters
6724 * were specified.
6725 * B offset Offset into data from beginning of next sprite
6726 * to place where parameter is to be stored. */
6728 /* Preload the next sprite */
6729 SpriteFile &file = *_cur.file;
6730 size_t pos = file.GetPos();
6731 uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6732 uint8_t type = file.ReadByte();
6734 /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6735 if (type != 0xFF) {
6736 GrfMsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6738 /* Reset the file position to the start of the next sprite */
6739 file.SeekTo(pos, SEEK_SET);
6740 return;
6743 /* Get (or create) the override for the next sprite. */
6744 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6745 std::vector<uint8_t> &preload_sprite = _grf_line_to_action6_sprite_override[location];
6747 /* Load new sprite data if it hasn't already been loaded. */
6748 if (preload_sprite.empty()) {
6749 preload_sprite.resize(num);
6750 file.ReadBlock(preload_sprite.data(), num);
6753 /* Reset the file position to the start of the next sprite */
6754 file.SeekTo(pos, SEEK_SET);
6756 /* Now perform the Action 0x06 on our data. */
6757 for (;;) {
6758 uint i;
6759 uint param_num;
6760 uint param_size;
6761 uint offset;
6762 bool add_value;
6764 /* Read the parameter to apply. 0xFF indicates no more data to change. */
6765 param_num = buf.ReadByte();
6766 if (param_num == 0xFF) break;
6768 /* Get the size of the parameter to use. If the size covers multiple
6769 * double words, sequential parameter values are used. */
6770 param_size = buf.ReadByte();
6772 /* Bit 7 of param_size indicates we should add to the original value
6773 * instead of replacing it. */
6774 add_value = HasBit(param_size, 7);
6775 param_size = GB(param_size, 0, 7);
6777 /* Where to apply the data to within the pseudo sprite data. */
6778 offset = buf.ReadExtendedByte();
6780 /* If the parameter is a GRF parameter (not an internal variable) check
6781 * if it (and all further sequential parameters) has been defined. */
6782 if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6783 GrfMsg(2, "CfgApply: Ignoring (param {} not set)", (param_num + (param_size - 1) / 4));
6784 break;
6787 GrfMsg(8, "CfgApply: Applying {} bytes from parameter 0x{:02X} at offset 0x{:04X}", param_size, param_num, offset);
6789 bool carry = false;
6790 for (i = 0; i < param_size && offset + i < num; i++) {
6791 uint32_t value = GetParamVal(param_num + i / 4, nullptr);
6792 /* Reset carry flag for each iteration of the variable (only really
6793 * matters if param_size is greater than 4) */
6794 if (i % 4 == 0) carry = false;
6796 if (add_value) {
6797 uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6798 preload_sprite[offset + i] = GB(new_value, 0, 8);
6799 /* Check if the addition overflowed */
6800 carry = new_value >= 256;
6801 } else {
6802 preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6809 * Disable a static NewGRF when it is influencing another (non-static)
6810 * NewGRF as this could cause desyncs.
6812 * We could just tell the NewGRF querying that the file doesn't exist,
6813 * but that might give unwanted results. Disabling the NewGRF gives the
6814 * best result as no NewGRF author can complain about that.
6815 * @param c The NewGRF to disable.
6817 static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
6819 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6820 error->data = _cur.grfconfig->GetName();
6823 /* Action 0x07
6824 * Action 0x09 */
6825 static void SkipIf(ByteReader &buf)
6827 /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6829 * B param-num
6830 * B param-size
6831 * B condition-type
6832 * V value
6833 * B num-sprites */
6834 uint32_t cond_val = 0;
6835 uint32_t mask = 0;
6836 bool result;
6838 uint8_t param = buf.ReadByte();
6839 uint8_t paramsize = buf.ReadByte();
6840 uint8_t condtype = buf.ReadByte();
6842 if (condtype < 2) {
6843 /* Always 1 for bit tests, the given value should be ignored. */
6844 paramsize = 1;
6847 switch (paramsize) {
6848 case 8: cond_val = buf.ReadDWord(); mask = buf.ReadDWord(); break;
6849 case 4: cond_val = buf.ReadDWord(); mask = 0xFFFFFFFF; break;
6850 case 2: cond_val = buf.ReadWord(); mask = 0x0000FFFF; break;
6851 case 1: cond_val = buf.ReadByte(); mask = 0x000000FF; break;
6852 default: break;
6855 if (param < 0x80 && _cur.grffile->param_end <= param) {
6856 GrfMsg(7, "SkipIf: Param {} undefined, skipping test", param);
6857 return;
6860 GrfMsg(7, "SkipIf: Test condtype {}, param 0x{:02X}, condval 0x{:08X}", condtype, param, cond_val);
6862 /* condtypes that do not use 'param' are always valid.
6863 * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6865 if (condtype >= 0x0B) {
6866 /* Tests that ignore 'param' */
6867 switch (condtype) {
6868 case 0x0B: result = !IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
6869 break;
6870 case 0x0C: result = IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
6871 break;
6872 case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6873 break;
6874 case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6875 break;
6876 case 0x0F: {
6877 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6878 result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6879 break;
6881 case 0x10: {
6882 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6883 result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6884 break;
6886 case 0x11: {
6887 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6888 result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6889 break;
6891 case 0x12: {
6892 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6893 result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6894 break;
6896 default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6898 } else if (param == 0x88) {
6899 /* GRF ID checks */
6901 GRFConfig *c = GetGRFConfig(cond_val, mask);
6903 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6904 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
6905 c = nullptr;
6908 if (condtype != 10 && c == nullptr) {
6909 GrfMsg(7, "SkipIf: GRFID 0x{:08X} unknown, skipping test", BSWAP32(cond_val));
6910 return;
6913 switch (condtype) {
6914 /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6915 case 0x06: // Is GRFID active?
6916 result = c->status == GCS_ACTIVATED;
6917 break;
6919 case 0x07: // Is GRFID non-active?
6920 result = c->status != GCS_ACTIVATED;
6921 break;
6923 case 0x08: // GRFID is not but will be active?
6924 result = c->status == GCS_INITIALISED;
6925 break;
6927 case 0x09: // GRFID is or will be active?
6928 result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6929 break;
6931 case 0x0A: // GRFID is not nor will be active
6932 /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6933 result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6934 break;
6936 default: GrfMsg(1, "SkipIf: Unsupported GRF condition type {:02X}. Ignoring", condtype); return;
6938 } else {
6939 /* Tests that use 'param' and are not GRF ID checks. */
6940 uint32_t param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6941 switch (condtype) {
6942 case 0x00: result = !!(param_val & (1 << cond_val));
6943 break;
6944 case 0x01: result = !(param_val & (1 << cond_val));
6945 break;
6946 case 0x02: result = (param_val & mask) == cond_val;
6947 break;
6948 case 0x03: result = (param_val & mask) != cond_val;
6949 break;
6950 case 0x04: result = (param_val & mask) < cond_val;
6951 break;
6952 case 0x05: result = (param_val & mask) > cond_val;
6953 break;
6954 default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6958 if (!result) {
6959 GrfMsg(2, "SkipIf: Not skipping sprites, test was false");
6960 return;
6963 uint8_t numsprites = buf.ReadByte();
6965 /* numsprites can be a GOTO label if it has been defined in the GRF
6966 * file. The jump will always be the first matching label that follows
6967 * the current nfo_line. If no matching label is found, the first matching
6968 * label in the file is used. */
6969 const GRFLabel *choice = nullptr;
6970 for (const auto &label : _cur.grffile->labels) {
6971 if (label.label != numsprites) continue;
6973 /* Remember a goto before the current line */
6974 if (choice == nullptr) choice = &label;
6975 /* If we find a label here, this is definitely good */
6976 if (label.nfo_line > _cur.nfo_line) {
6977 choice = &label;
6978 break;
6982 if (choice != nullptr) {
6983 GrfMsg(2, "SkipIf: Jumping to label 0x{:X} at line {}, test was true", choice->label, choice->nfo_line);
6984 _cur.file->SeekTo(choice->pos, SEEK_SET);
6985 _cur.nfo_line = choice->nfo_line;
6986 return;
6989 GrfMsg(2, "SkipIf: Skipping {} sprites, test was true", numsprites);
6990 _cur.skip_sprites = numsprites;
6991 if (_cur.skip_sprites == 0) {
6992 /* Zero means there are no sprites to skip, so
6993 * we use -1 to indicate that all further
6994 * sprites should be skipped. */
6995 _cur.skip_sprites = -1;
6997 /* If an action 8 hasn't been encountered yet, disable the grf. */
6998 if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6999 DisableGrf();
7005 /* Action 0x08 (GLS_FILESCAN) */
7006 static void ScanInfo(ByteReader &buf)
7008 uint8_t grf_version = buf.ReadByte();
7009 uint32_t grfid = buf.ReadDWord();
7010 std::string_view name = buf.ReadString();
7012 _cur.grfconfig->ident.grfid = grfid;
7014 if (grf_version < 2 || grf_version > 8) {
7015 SetBit(_cur.grfconfig->flags, GCF_INVALID);
7016 Debug(grf, 0, "{}: NewGRF \"{}\" (GRFID {:08X}) uses GRF version {}, which is incompatible with this version of OpenTTD.", _cur.grfconfig->filename, StrMakeValid(name), BSWAP32(grfid), grf_version);
7019 /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
7020 if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
7022 AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
7024 if (buf.HasData()) {
7025 std::string_view info = buf.ReadString();
7026 AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
7029 /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
7030 _cur.skip_sprites = -1;
7033 /* Action 0x08 */
7034 static void GRFInfo(ByteReader &buf)
7036 /* <08> <version> <grf-id> <name> <info>
7038 * B version newgrf version, currently 06
7039 * 4*B grf-id globally unique ID of this .grf file
7040 * S name name of this .grf set
7041 * S info string describing the set, and e.g. author and copyright */
7043 uint8_t version = buf.ReadByte();
7044 uint32_t grfid = buf.ReadDWord();
7045 std::string_view name = buf.ReadString();
7047 if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
7048 DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
7049 return;
7052 if (_cur.grffile->grfid != grfid) {
7053 Debug(grf, 0, "GRFInfo: GRFID {:08X} in FILESCAN stage does not match GRFID {:08X} in INIT/RESERVE/ACTIVATION stage", BSWAP32(_cur.grffile->grfid), BSWAP32(grfid));
7054 _cur.grffile->grfid = grfid;
7057 _cur.grffile->grf_version = version;
7058 _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
7060 /* Do swap the GRFID for displaying purposes since people expect that */
7061 Debug(grf, 1, "GRFInfo: Loaded GRFv{} set {:08X} - {} (palette: {}, version: {})", version, BSWAP32(grfid), StrMakeValid(name), (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version);
7065 * Check if a sprite ID range is within the GRM reversed range for the currently loading NewGRF.
7066 * @param first_sprite First sprite of range.
7067 * @param num_sprites Number of sprites in the range.
7068 * @return True iff the NewGRF has reserved a range equal to or greater than the provided range.
7070 static bool IsGRMReservedSprite(SpriteID first_sprite, uint16_t num_sprites)
7072 for (const auto &grm_sprite : _grm_sprites) {
7073 if (grm_sprite.first.grfid != _cur.grffile->grfid) continue;
7074 if (grm_sprite.second.first <= first_sprite && grm_sprite.second.first + grm_sprite.second.second >= first_sprite + num_sprites) return true;
7076 return false;
7079 /* Action 0x0A */
7080 static void SpriteReplace(ByteReader &buf)
7082 /* <0A> <num-sets> <set1> [<set2> ...]
7083 * <set>: <num-sprites> <first-sprite>
7085 * B num-sets How many sets of sprites to replace.
7086 * Each set:
7087 * B num-sprites How many sprites are in this set
7088 * W first-sprite First sprite number to replace */
7090 uint8_t num_sets = buf.ReadByte();
7092 for (uint i = 0; i < num_sets; i++) {
7093 uint8_t num_sprites = buf.ReadByte();
7094 uint16_t first_sprite = buf.ReadWord();
7096 GrfMsg(2, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}",
7097 i, num_sprites, first_sprite
7100 if (first_sprite + num_sprites >= SPR_OPENTTD_BASE) {
7101 /* Outside allowed range, check for GRM sprite reservations. */
7102 if (!IsGRMReservedSprite(first_sprite, num_sprites)) {
7103 GrfMsg(0, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}, above limit of {} and not within reserved range, ignoring.",
7104 i, num_sprites, first_sprite, SPR_OPENTTD_BASE);
7106 /* Load the sprites at the current location so they will do nothing instead of appearing to work. */
7107 first_sprite = _cur.spriteid;
7108 _cur.spriteid += num_sprites;
7112 for (uint j = 0; j < num_sprites; j++) {
7113 int load_index = first_sprite + j;
7114 _cur.nfo_line++;
7115 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
7117 /* Shore sprites now located at different addresses.
7118 * So detect when the old ones get replaced. */
7119 if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
7120 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
7126 /* Action 0x0A (SKIP) */
7127 static void SkipActA(ByteReader &buf)
7129 uint8_t num_sets = buf.ReadByte();
7131 for (uint i = 0; i < num_sets; i++) {
7132 /* Skip the sprites this replaces */
7133 _cur.skip_sprites += buf.ReadByte();
7134 /* But ignore where they go */
7135 buf.ReadWord();
7138 GrfMsg(3, "SkipActA: Skipping {} sprites", _cur.skip_sprites);
7141 /* Action 0x0B */
7142 static void GRFLoadError(ByteReader &buf)
7144 /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
7146 * B severity 00: notice, continue loading grf file
7147 * 01: warning, continue loading grf file
7148 * 02: error, but continue loading grf file, and attempt
7149 * loading grf again when loading or starting next game
7150 * 03: error, abort loading and prevent loading again in
7151 * the future (only when restarting the patch)
7152 * B language-id see action 4, use 1F for built-in error messages
7153 * B message-id message to show, see below
7154 * S message for custom messages (message-id FF), text of the message
7155 * not present for built-in messages.
7156 * V data additional data for built-in (or custom) messages
7157 * B parnum parameter numbers to be shown in the message (maximum of 2) */
7159 static const StringID msgstr[] = {
7160 STR_NEWGRF_ERROR_VERSION_NUMBER,
7161 STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
7162 STR_NEWGRF_ERROR_UNSET_SWITCH,
7163 STR_NEWGRF_ERROR_INVALID_PARAMETER,
7164 STR_NEWGRF_ERROR_LOAD_BEFORE,
7165 STR_NEWGRF_ERROR_LOAD_AFTER,
7166 STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
7169 static const StringID sevstr[] = {
7170 STR_NEWGRF_ERROR_MSG_INFO,
7171 STR_NEWGRF_ERROR_MSG_WARNING,
7172 STR_NEWGRF_ERROR_MSG_ERROR,
7173 STR_NEWGRF_ERROR_MSG_FATAL
7176 uint8_t severity = buf.ReadByte();
7177 uint8_t lang = buf.ReadByte();
7178 uint8_t message_id = buf.ReadByte();
7180 /* Skip the error if it isn't valid for the current language. */
7181 if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
7183 /* Skip the error until the activation stage unless bit 7 of the severity
7184 * is set. */
7185 if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
7186 GrfMsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage {}", _cur.stage);
7187 return;
7189 ClrBit(severity, 7);
7191 if (severity >= lengthof(sevstr)) {
7192 GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity);
7193 severity = 2;
7194 } else if (severity == 3) {
7195 /* This is a fatal error, so make sure the GRF is deactivated and no
7196 * more of it gets loaded. */
7197 DisableGrf();
7199 /* Make sure we show fatal errors, instead of silly infos from before */
7200 _cur.grfconfig->error.reset();
7203 if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
7204 GrfMsg(7, "GRFLoadError: Invalid message id.");
7205 return;
7208 if (buf.Remaining() <= 1) {
7209 GrfMsg(7, "GRFLoadError: No message data supplied.");
7210 return;
7213 /* For now we can only show one message per newgrf file. */
7214 if (_cur.grfconfig->error.has_value()) return;
7216 _cur.grfconfig->error = {sevstr[severity]};
7217 GRFError *error = &_cur.grfconfig->error.value();
7219 if (message_id == 0xFF) {
7220 /* This is a custom error message. */
7221 if (buf.HasData()) {
7222 std::string_view message = buf.ReadString();
7224 error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
7225 } else {
7226 GrfMsg(7, "GRFLoadError: No custom message supplied.");
7227 error->custom_message.clear();
7229 } else {
7230 error->message = msgstr[message_id];
7233 if (buf.HasData()) {
7234 std::string_view data = buf.ReadString();
7236 error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
7237 } else {
7238 GrfMsg(7, "GRFLoadError: No message data supplied.");
7239 error->data.clear();
7242 /* Only two parameter numbers can be used in the string. */
7243 for (uint i = 0; i < error->param_value.size() && buf.HasData(); i++) {
7244 uint param_number = buf.ReadByte();
7245 error->param_value[i] = _cur.grffile->GetParam(param_number);
7249 /* Action 0x0C */
7250 static void GRFComment(ByteReader &buf)
7252 /* <0C> [<ignored...>]
7254 * V ignored Anything following the 0C is ignored */
7256 if (!buf.HasData()) return;
7258 std::string_view text = buf.ReadString();
7259 GrfMsg(2, "GRFComment: {}", StrMakeValid(text));
7262 /* Action 0x0D (GLS_SAFETYSCAN) */
7263 static void SafeParamSet(ByteReader &buf)
7265 uint8_t target = buf.ReadByte();
7267 /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
7268 if (target < 0x80 || target == 0x9E) return;
7270 /* GRM could be unsafe, but as here it can only happen after other GRFs
7271 * are loaded, it should be okay. If the GRF tried to use the slots it
7272 * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
7273 * sprites is considered safe. */
7275 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7277 /* Skip remainder of GRF */
7278 _cur.skip_sprites = -1;
7282 static uint32_t GetPatchVariable(uint8_t param)
7284 switch (param) {
7285 /* start year - 1920 */
7286 case 0x0B: return (std::max(_settings_game.game_creation.starting_year, CalendarTime::ORIGINAL_BASE_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base();
7288 /* freight trains weight factor */
7289 case 0x0E: return _settings_game.vehicle.freight_trains;
7291 /* empty wagon speed increase */
7292 case 0x0F: return 0;
7294 /* plane speed factor; our patch option is reversed from TTDPatch's,
7295 * the following is good for 1x, 2x and 4x (most common?) and...
7296 * well not really for 3x. */
7297 case 0x10:
7298 switch (_settings_game.vehicle.plane_speed) {
7299 default:
7300 case 4: return 1;
7301 case 3: return 2;
7302 case 2: return 2;
7303 case 1: return 4;
7307 /* 2CC colourmap base sprite */
7308 case 0x11: return SPR_2CCMAP_BASE;
7310 /* map size: format = -MABXYSS
7311 * M : the type of map
7312 * bit 0 : set : squared map. Bit 1 is now not relevant
7313 * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7314 * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7315 * clear : X is the bigger edge.
7316 * A : minimum edge(log2) of the map
7317 * B : maximum edge(log2) of the map
7318 * XY : edges(log2) of each side of the map.
7319 * SS : combination of both X and Y, thus giving the size(log2) of the map
7321 case 0x13: {
7322 uint8_t map_bits = 0;
7323 uint8_t log_X = Map::LogX() - 6; // subtraction is required to make the minimal size (64) zero based
7324 uint8_t log_Y = Map::LogY() - 6;
7325 uint8_t max_edge = std::max(log_X, log_Y);
7327 if (log_X == log_Y) { // we have a squared map, since both edges are identical
7328 SetBit(map_bits, 0);
7329 } else {
7330 if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7333 return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7334 (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7337 /* The maximum height of the map. */
7338 case 0x14:
7339 return _settings_game.construction.map_height_limit;
7341 /* Extra foundations base sprite */
7342 case 0x15:
7343 return SPR_SLOPES_BASE;
7345 /* Shore base sprite */
7346 case 0x16:
7347 return SPR_SHORE_BASE;
7349 /* Game map seed */
7350 case 0x17:
7351 return _settings_game.game_creation.generation_seed;
7353 default:
7354 GrfMsg(2, "ParamSet: Unknown Patch variable 0x{:02X}.", param);
7355 return 0;
7360 static uint32_t PerformGRM(uint32_t *grm, uint16_t num_ids, uint16_t count, uint8_t op, uint8_t target, const char *type)
7362 uint start = 0;
7363 uint size = 0;
7365 if (op == 6) {
7366 /* Return GRFID of set that reserved ID */
7367 return grm[_cur.grffile->GetParam(target)];
7370 /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7371 if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7373 for (uint i = start; i < num_ids; i++) {
7374 if (grm[i] == 0) {
7375 size++;
7376 } else {
7377 if (op == 2 || op == 3) break;
7378 start = i + 1;
7379 size = 0;
7382 if (size == count) break;
7385 if (size == count) {
7386 /* Got the slot... */
7387 if (op == 0 || op == 3) {
7388 GrfMsg(2, "ParamSet: GRM: Reserving {} {} at {}", count, type, start);
7389 for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7391 return start;
7394 /* Unable to allocate */
7395 if (op != 4 && op != 5) {
7396 /* Deactivate GRF */
7397 GrfMsg(0, "ParamSet: GRM: Unable to allocate {} {}, deactivating", count, type);
7398 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7399 return UINT_MAX;
7402 GrfMsg(1, "ParamSet: GRM: Unable to allocate {} {}", count, type);
7403 return UINT_MAX;
7407 /** Action 0x0D: Set parameter */
7408 static void ParamSet(ByteReader &buf)
7410 /* <0D> <target> <operation> <source1> <source2> [<data>]
7412 * B target parameter number where result is stored
7413 * B operation operation to perform, see below
7414 * B source1 first source operand
7415 * B source2 second source operand
7416 * D data data to use in the calculation, not necessary
7417 * if both source1 and source2 refer to actual parameters
7419 * Operations
7420 * 00 Set parameter equal to source1
7421 * 01 Addition, source1 + source2
7422 * 02 Subtraction, source1 - source2
7423 * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7424 * 04 Signed multiplication, source1 * source2 (both signed)
7425 * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7426 * signed quantity; left shift if positive and right shift if
7427 * negative, source1 is unsigned)
7428 * 06 Signed bit shift, source1 by source2
7429 * (source2 like in 05, and source1 as well)
7432 uint8_t target = buf.ReadByte();
7433 uint8_t oper = buf.ReadByte();
7434 uint32_t src1 = buf.ReadByte();
7435 uint32_t src2 = buf.ReadByte();
7437 uint32_t data = 0;
7438 if (buf.Remaining() >= 4) data = buf.ReadDWord();
7440 /* You can add 80 to the operation to make it apply only if the target
7441 * is not defined yet. In this respect, a parameter is taken to be
7442 * defined if any of the following applies:
7443 * - it has been set to any value in the newgrf(w).cfg parameter list
7444 * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7445 * an earlier action D */
7446 if (HasBit(oper, 7)) {
7447 if (target < 0x80 && target < _cur.grffile->param_end) {
7448 GrfMsg(7, "ParamSet: Param {} already defined, skipping", target);
7449 return;
7452 oper = GB(oper, 0, 7);
7455 if (src2 == 0xFE) {
7456 if (GB(data, 0, 8) == 0xFF) {
7457 if (data == 0x0000FFFF) {
7458 /* Patch variables */
7459 src1 = GetPatchVariable(src1);
7460 } else {
7461 /* GRF Resource Management */
7462 uint8_t op = src1;
7463 uint8_t feature = GB(data, 8, 8);
7464 uint16_t count = GB(data, 16, 16);
7466 if (_cur.stage == GLS_RESERVE) {
7467 if (feature == 0x08) {
7468 /* General sprites */
7469 if (op == 0) {
7470 /* Check if the allocated sprites will fit below the original sprite limit */
7471 if (_cur.spriteid + count >= 16384) {
7472 GrfMsg(0, "ParamSet: GRM: Unable to allocate {} sprites; try changing NewGRF order", count);
7473 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7474 return;
7477 /* Reserve space at the current sprite ID */
7478 GrfMsg(4, "ParamSet: GRM: Allocated {} sprites at {}", count, _cur.spriteid);
7479 _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = std::make_pair(_cur.spriteid, count);
7480 _cur.spriteid += count;
7483 /* Ignore GRM result during reservation */
7484 src1 = 0;
7485 } else if (_cur.stage == GLS_ACTIVATION) {
7486 switch (feature) {
7487 case 0x00: // Trains
7488 case 0x01: // Road Vehicles
7489 case 0x02: // Ships
7490 case 0x03: // Aircraft
7491 if (!_settings_game.vehicle.dynamic_engines) {
7492 src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7493 if (_cur.skip_sprites == -1) return;
7494 } else {
7495 /* GRM does not apply for dynamic engine allocation. */
7496 switch (op) {
7497 case 2:
7498 case 3:
7499 src1 = _cur.grffile->GetParam(target);
7500 break;
7502 default:
7503 src1 = 0;
7504 break;
7507 break;
7509 case 0x08: // General sprites
7510 switch (op) {
7511 case 0:
7512 /* Return space reserved during reservation stage */
7513 src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)].first;
7514 GrfMsg(4, "ParamSet: GRM: Using pre-allocated sprites at {}", src1);
7515 break;
7517 case 1:
7518 src1 = _cur.spriteid;
7519 break;
7521 default:
7522 GrfMsg(1, "ParamSet: GRM: Unsupported operation {} for general sprites", op);
7523 return;
7525 break;
7527 case 0x0B: // Cargo
7528 /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7529 src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7530 if (_cur.skip_sprites == -1) return;
7531 break;
7533 default: GrfMsg(1, "ParamSet: GRM: Unsupported feature 0x{:X}", feature); return;
7535 } else {
7536 /* Ignore GRM during initialization */
7537 src1 = 0;
7540 } else {
7541 /* Read another GRF File's parameter */
7542 const GRFFile *file = GetFileByGRFID(data);
7543 GRFConfig *c = GetGRFConfig(data);
7544 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7545 /* Disable the read GRF if it is a static NewGRF. */
7546 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
7547 src1 = 0;
7548 } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7549 src1 = 0;
7550 } else if (src1 == 0xFE) {
7551 src1 = c->version;
7552 } else {
7553 src1 = file->GetParam(src1);
7556 } else {
7557 /* The source1 and source2 operands refer to the grf parameter number
7558 * like in action 6 and 7. In addition, they can refer to the special
7559 * variables available in action 7, or they can be FF to use the value
7560 * of <data>. If referring to parameters that are undefined, a value
7561 * of 0 is used instead. */
7562 src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7563 src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7566 uint32_t res;
7567 switch (oper) {
7568 case 0x00:
7569 res = src1;
7570 break;
7572 case 0x01:
7573 res = src1 + src2;
7574 break;
7576 case 0x02:
7577 res = src1 - src2;
7578 break;
7580 case 0x03:
7581 res = src1 * src2;
7582 break;
7584 case 0x04:
7585 res = (int32_t)src1 * (int32_t)src2;
7586 break;
7588 case 0x05:
7589 if ((int32_t)src2 < 0) {
7590 res = src1 >> -(int32_t)src2;
7591 } else {
7592 res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7594 break;
7596 case 0x06:
7597 if ((int32_t)src2 < 0) {
7598 res = (int32_t)src1 >> -(int32_t)src2;
7599 } else {
7600 res = (int32_t)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7602 break;
7604 case 0x07: // Bitwise AND
7605 res = src1 & src2;
7606 break;
7608 case 0x08: // Bitwise OR
7609 res = src1 | src2;
7610 break;
7612 case 0x09: // Unsigned division
7613 if (src2 == 0) {
7614 res = src1;
7615 } else {
7616 res = src1 / src2;
7618 break;
7620 case 0x0A: // Signed division
7621 if (src2 == 0) {
7622 res = src1;
7623 } else {
7624 res = (int32_t)src1 / (int32_t)src2;
7626 break;
7628 case 0x0B: // Unsigned modulo
7629 if (src2 == 0) {
7630 res = src1;
7631 } else {
7632 res = src1 % src2;
7634 break;
7636 case 0x0C: // Signed modulo
7637 if (src2 == 0) {
7638 res = src1;
7639 } else {
7640 res = (int32_t)src1 % (int32_t)src2;
7642 break;
7644 default: GrfMsg(0, "ParamSet: Unknown operation {}, skipping", oper); return;
7647 switch (target) {
7648 case 0x8E: // Y-Offset for train sprites
7649 _cur.grffile->traininfo_vehicle_pitch = res;
7650 break;
7652 case 0x8F: { // Rail track type cost factors
7653 extern RailTypeInfo _railtypes[RAILTYPE_END];
7654 _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7655 if (_settings_game.vehicle.disable_elrails) {
7656 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7657 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7658 } else {
7659 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7660 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7662 _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7663 break;
7666 /* not implemented */
7667 case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7668 case 0x94: // Tile refresh offset to right
7669 case 0x95: // Tile refresh offset upwards
7670 case 0x96: // Tile refresh offset downwards
7671 case 0x97: // Snow line height -- Better supported by feature 8 property 10h (snow line table) TODO: implement by filling the entire snow line table with the given value
7672 case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7673 GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7674 break;
7676 case 0x9E: // Miscellaneous GRF features
7677 /* Set train list engine width */
7678 _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7679 /* Remove the local flags from the global flags */
7680 ClrBit(res, GMB_TRAIN_WIDTH_32_PIXELS);
7682 /* Only copy safe bits for static grfs */
7683 if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7684 uint32_t safe_bits = 0;
7685 SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7687 _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7688 } else {
7689 _misc_grf_features = res;
7691 break;
7693 case 0x9F: // locale-dependent settings
7694 GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7695 break;
7697 default:
7698 if (target < 0x80) {
7699 _cur.grffile->param[target] = res;
7700 /* param is zeroed by default */
7701 if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7702 } else {
7703 GrfMsg(7, "ParamSet: Skipping unknown target 0x{:02X}", target);
7705 break;
7709 /* Action 0x0E (GLS_SAFETYSCAN) */
7710 static void SafeGRFInhibit(ByteReader &buf)
7712 /* <0E> <num> <grfids...>
7714 * B num Number of GRFIDs that follow
7715 * D grfids GRFIDs of the files to deactivate */
7717 uint8_t num = buf.ReadByte();
7719 for (uint i = 0; i < num; i++) {
7720 uint32_t grfid = buf.ReadDWord();
7722 /* GRF is unsafe it if tries to deactivate other GRFs */
7723 if (grfid != _cur.grfconfig->ident.grfid) {
7724 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7726 /* Skip remainder of GRF */
7727 _cur.skip_sprites = -1;
7729 return;
7734 /* Action 0x0E */
7735 static void GRFInhibit(ByteReader &buf)
7737 /* <0E> <num> <grfids...>
7739 * B num Number of GRFIDs that follow
7740 * D grfids GRFIDs of the files to deactivate */
7742 uint8_t num = buf.ReadByte();
7744 for (uint i = 0; i < num; i++) {
7745 uint32_t grfid = buf.ReadDWord();
7746 GRFConfig *file = GetGRFConfig(grfid);
7748 /* Unset activation flag */
7749 if (file != nullptr && file != _cur.grfconfig) {
7750 GrfMsg(2, "GRFInhibit: Deactivating file '{}'", file->filename);
7751 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7752 error->data = _cur.grfconfig->GetName();
7757 /** Action 0x0F - Define Town names */
7758 static void FeatureTownName(ByteReader &buf)
7760 /* <0F> <id> <style-name> <num-parts> <parts>
7762 * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7763 * V style-name Name of the style (only for final definition)
7764 * B num-parts Number of parts in this definition
7765 * V parts The parts */
7767 uint32_t grfid = _cur.grffile->grfid;
7769 GRFTownName *townname = AddGRFTownName(grfid);
7771 uint8_t id = buf.ReadByte();
7772 GrfMsg(6, "FeatureTownName: definition 0x{:02X}", id & 0x7F);
7774 if (HasBit(id, 7)) {
7775 /* Final definition */
7776 ClrBit(id, 7);
7777 bool new_scheme = _cur.grffile->grf_version >= 7;
7779 uint8_t lang = buf.ReadByte();
7780 StringID style = STR_UNDEFINED;
7782 do {
7783 ClrBit(lang, 7);
7785 std::string_view name = buf.ReadString();
7787 std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7788 GrfMsg(6, "FeatureTownName: lang 0x{:X} -> '{}'", lang, lang_name);
7790 style = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7792 lang = buf.ReadByte();
7793 } while (lang != 0);
7794 townname->styles.emplace_back(style, id);
7797 uint8_t parts = buf.ReadByte();
7798 GrfMsg(6, "FeatureTownName: {} parts", parts);
7800 townname->partlists[id].reserve(parts);
7801 for (uint partnum = 0; partnum < parts; partnum++) {
7802 NamePartList &partlist = townname->partlists[id].emplace_back();
7803 uint8_t texts = buf.ReadByte();
7804 partlist.bitstart = buf.ReadByte();
7805 partlist.bitcount = buf.ReadByte();
7806 partlist.maxprob = 0;
7807 GrfMsg(6, "FeatureTownName: part {} contains {} texts and will use GB(seed, {}, {})", partnum, texts, partlist.bitstart, partlist.bitcount);
7809 partlist.parts.reserve(texts);
7810 for (uint textnum = 0; textnum < texts; textnum++) {
7811 NamePart &part = partlist.parts.emplace_back();
7812 part.prob = buf.ReadByte();
7814 if (HasBit(part.prob, 7)) {
7815 uint8_t ref_id = buf.ReadByte();
7816 if (ref_id >= GRFTownName::MAX_LISTS || townname->partlists[ref_id].empty()) {
7817 GrfMsg(0, "FeatureTownName: definition 0x{:02X} doesn't exist, deactivating", ref_id);
7818 DelGRFTownName(grfid);
7819 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7820 return;
7822 part.id = ref_id;
7823 GrfMsg(6, "FeatureTownName: part {}, text {}, uses intermediate definition 0x{:02X} (with probability {})", partnum, textnum, ref_id, part.prob & 0x7F);
7824 } else {
7825 std::string_view text = buf.ReadString();
7826 part.text = TranslateTTDPatchCodes(grfid, 0, false, text);
7827 GrfMsg(6, "FeatureTownName: part {}, text {}, '{}' (with probability {})", partnum, textnum, part.text, part.prob);
7829 partlist.maxprob += GB(part.prob, 0, 7);
7831 GrfMsg(6, "FeatureTownName: part {}, total probability {}", partnum, partlist.maxprob);
7835 /** Action 0x10 - Define goto label */
7836 static void DefineGotoLabel(ByteReader &buf)
7838 /* <10> <label> [<comment>]
7840 * B label The label to define
7841 * V comment Optional comment - ignored */
7843 uint8_t nfo_label = buf.ReadByte();
7845 _cur.grffile->labels.emplace_back(nfo_label, _cur.nfo_line, _cur.file->GetPos());
7847 GrfMsg(2, "DefineGotoLabel: GOTO target with label 0x{:02X}", nfo_label);
7851 * Process a sound import from another GRF file.
7852 * @param sound Destination for sound.
7854 static void ImportGRFSound(SoundEntry *sound)
7856 const GRFFile *file;
7857 uint32_t grfid = _cur.file->ReadDword();
7858 SoundID sound_id = _cur.file->ReadWord();
7860 file = GetFileByGRFID(grfid);
7861 if (file == nullptr || file->sound_offset == 0) {
7862 GrfMsg(1, "ImportGRFSound: Source file not available");
7863 return;
7866 if (sound_id >= file->num_sounds) {
7867 GrfMsg(1, "ImportGRFSound: Sound effect {} is invalid", sound_id);
7868 return;
7871 GrfMsg(2, "ImportGRFSound: Copying sound {} ({}) from file {:x}", sound_id, file->sound_offset + sound_id, grfid);
7873 *sound = *GetSound(file->sound_offset + sound_id);
7875 /* Reset volume and priority, which TTDPatch doesn't copy */
7876 sound->volume = SOUND_EFFECT_MAX_VOLUME;
7877 sound->priority = 0;
7881 * Load a sound from a file.
7882 * @param offs File offset to read sound from.
7883 * @param sound Destination for sound.
7885 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7887 /* Set default volume and priority */
7888 sound->volume = SOUND_EFFECT_MAX_VOLUME;
7889 sound->priority = 0;
7891 if (offs != SIZE_MAX) {
7892 /* Sound is present in the NewGRF. */
7893 sound->file = _cur.file;
7894 sound->file_offset = offs;
7895 sound->grf_container_ver = _cur.file->GetContainerVersion();
7899 /* Action 0x11 */
7900 static void GRFSound(ByteReader &buf)
7902 /* <11> <num>
7904 * W num Number of sound files that follow */
7906 uint16_t num = buf.ReadWord();
7907 if (num == 0) return;
7909 SoundEntry *sound;
7910 if (_cur.grffile->sound_offset == 0) {
7911 _cur.grffile->sound_offset = GetNumSounds();
7912 _cur.grffile->num_sounds = num;
7913 sound = AllocateSound(num);
7914 } else {
7915 sound = GetSound(_cur.grffile->sound_offset);
7918 SpriteFile &file = *_cur.file;
7919 uint8_t grf_container_version = file.GetContainerVersion();
7920 for (int i = 0; i < num; i++) {
7921 _cur.nfo_line++;
7923 /* Check whether the index is in range. This might happen if multiple action 11 are present.
7924 * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7925 bool invalid = i >= _cur.grffile->num_sounds;
7927 size_t offs = file.GetPos();
7929 uint32_t len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7930 uint8_t type = file.ReadByte();
7932 if (grf_container_version >= 2 && type == 0xFD) {
7933 /* Reference to sprite section. */
7934 if (invalid) {
7935 GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7936 file.SkipBytes(len);
7937 } else if (len != 4) {
7938 GrfMsg(1, "GRFSound: Invalid sprite section import");
7939 file.SkipBytes(len);
7940 } else {
7941 uint32_t id = file.ReadDword();
7942 if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7944 continue;
7947 if (type != 0xFF) {
7948 GrfMsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7949 file.SkipBytes(7);
7950 SkipSpriteData(*_cur.file, type, len - 8);
7951 continue;
7954 if (invalid) {
7955 GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7956 file.SkipBytes(len);
7959 uint8_t action = file.ReadByte();
7960 switch (action) {
7961 case 0xFF:
7962 /* Allocate sound only in init stage. */
7963 if (_cur.stage == GLS_INIT) {
7964 if (grf_container_version >= 2) {
7965 GrfMsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7966 } else {
7967 LoadGRFSound(offs, sound + i);
7970 file.SkipBytes(len - 1); // already read <action>
7971 break;
7973 case 0xFE:
7974 if (_cur.stage == GLS_ACTIVATION) {
7975 /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7976 * importing sounds, so this is probably all wrong... */
7977 if (file.ReadByte() != 0) GrfMsg(1, "GRFSound: Import type mismatch");
7978 ImportGRFSound(sound + i);
7979 } else {
7980 file.SkipBytes(len - 1); // already read <action>
7982 break;
7984 default:
7985 GrfMsg(1, "GRFSound: Unexpected Action {:x} found, skipping", action);
7986 file.SkipBytes(len - 1); // already read <action>
7987 break;
7992 /* Action 0x11 (SKIP) */
7993 static void SkipAct11(ByteReader &buf)
7995 /* <11> <num>
7997 * W num Number of sound files that follow */
7999 _cur.skip_sprites = buf.ReadWord();
8001 GrfMsg(3, "SkipAct11: Skipping {} sprites", _cur.skip_sprites);
8004 /** Action 0x12 */
8005 static void LoadFontGlyph(ByteReader &buf)
8007 /* <12> <num_def> <font_size> <num_char> <base_char>
8009 * B num_def Number of definitions
8010 * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
8011 * B num_char Number of consecutive glyphs
8012 * W base_char First character index */
8014 uint8_t num_def = buf.ReadByte();
8016 for (uint i = 0; i < num_def; i++) {
8017 FontSize size = (FontSize)buf.ReadByte();
8018 uint8_t num_char = buf.ReadByte();
8019 uint16_t base_char = buf.ReadWord();
8021 if (size >= FS_END) {
8022 GrfMsg(1, "LoadFontGlyph: Size {} is not supported, ignoring", size);
8025 GrfMsg(7, "LoadFontGlyph: Loading {} glyph(s) at 0x{:04X} for size {}", num_char, base_char, size);
8027 for (uint c = 0; c < num_char; c++) {
8028 if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
8029 _cur.nfo_line++;
8030 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
8035 /** Action 0x12 (SKIP) */
8036 static void SkipAct12(ByteReader &buf)
8038 /* <12> <num_def> <font_size> <num_char> <base_char>
8040 * B num_def Number of definitions
8041 * B font_size Size of font (0 = normal, 1 = small, 2 = large)
8042 * B num_char Number of consecutive glyphs
8043 * W base_char First character index */
8045 uint8_t num_def = buf.ReadByte();
8047 for (uint i = 0; i < num_def; i++) {
8048 /* Ignore 'size' byte */
8049 buf.ReadByte();
8051 /* Sum up number of characters */
8052 _cur.skip_sprites += buf.ReadByte();
8054 /* Ignore 'base_char' word */
8055 buf.ReadWord();
8058 GrfMsg(3, "SkipAct12: Skipping {} sprites", _cur.skip_sprites);
8061 /** Action 0x13 */
8062 static void TranslateGRFStrings(ByteReader &buf)
8064 /* <13> <grfid> <num-ent> <offset> <text...>
8066 * 4*B grfid The GRFID of the file whose texts are to be translated
8067 * B num-ent Number of strings
8068 * W offset First text ID
8069 * S text... Zero-terminated strings */
8071 uint32_t grfid = buf.ReadDWord();
8072 const GRFConfig *c = GetGRFConfig(grfid);
8073 if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
8074 GrfMsg(7, "TranslateGRFStrings: GRFID 0x{:08X} unknown, skipping action 13", BSWAP32(grfid));
8075 return;
8078 if (c->status == GCS_INITIALISED) {
8079 /* If the file is not active but will be activated later, give an error
8080 * and disable this file. */
8081 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
8083 error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
8085 return;
8088 /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
8089 * to be added as a generic string, thus the language id of 0x7F. For this to work
8090 * new_scheme has to be true as well, which will also be implicitly the case for version 8
8091 * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
8092 * not change anything if a string has been provided specifically for this language. */
8093 uint8_t language = _cur.grffile->grf_version >= 8 ? buf.ReadByte() : 0x7F;
8094 uint8_t num_strings = buf.ReadByte();
8095 uint16_t first_id = buf.ReadWord();
8097 if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
8098 GrfMsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x{:04X}, number: 0x{:02X})", first_id, num_strings);
8099 return;
8102 for (uint i = 0; i < num_strings && buf.HasData(); i++) {
8103 std::string_view string = buf.ReadString();
8105 if (string.empty()) {
8106 GrfMsg(7, "TranslateGRFString: Ignoring empty string.");
8107 continue;
8110 AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
8114 /** Callback function for 'INFO'->'NAME' to add a translation to the newgrf name. */
8115 static bool ChangeGRFName(uint8_t langid, std::string_view str)
8117 AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
8118 return true;
8121 /** Callback function for 'INFO'->'DESC' to add a translation to the newgrf description. */
8122 static bool ChangeGRFDescription(uint8_t langid, std::string_view str)
8124 AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
8125 return true;
8128 /** Callback function for 'INFO'->'URL_' to set the newgrf url. */
8129 static bool ChangeGRFURL(uint8_t langid, std::string_view str)
8131 AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
8132 return true;
8135 /** Callback function for 'INFO'->'NPAR' to set the number of valid parameters. */
8136 static bool ChangeGRFNumUsedParams(size_t len, ByteReader &buf)
8138 if (len != 1) {
8139 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got {}, ignoring this field", len);
8140 buf.Skip(len);
8141 } else {
8142 _cur.grfconfig->num_valid_params = std::min(buf.ReadByte(), ClampTo<uint8_t>(_cur.grfconfig->param.size()));
8144 return true;
8147 /** Callback function for 'INFO'->'PALS' to set the number of valid parameters. */
8148 static bool ChangeGRFPalette(size_t len, ByteReader &buf)
8150 if (len != 1) {
8151 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got {}, ignoring this field", len);
8152 buf.Skip(len);
8153 } else {
8154 char data = buf.ReadByte();
8155 GRFPalette pal = GRFP_GRF_UNSET;
8156 switch (data) {
8157 case '*':
8158 case 'A': pal = GRFP_GRF_ANY; break;
8159 case 'W': pal = GRFP_GRF_WINDOWS; break;
8160 case 'D': pal = GRFP_GRF_DOS; break;
8161 default:
8162 GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'PALS', ignoring this field", data);
8163 break;
8165 if (pal != GRFP_GRF_UNSET) {
8166 _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
8167 _cur.grfconfig->palette |= pal;
8170 return true;
8173 /** Callback function for 'INFO'->'BLTR' to set the blitter info. */
8174 static bool ChangeGRFBlitter(size_t len, ByteReader &buf)
8176 if (len != 1) {
8177 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got {}, ignoring this field", len);
8178 buf.Skip(len);
8179 } else {
8180 char data = buf.ReadByte();
8181 GRFPalette pal = GRFP_BLT_UNSET;
8182 switch (data) {
8183 case '8': pal = GRFP_BLT_UNSET; break;
8184 case '3': pal = GRFP_BLT_32BPP; break;
8185 default:
8186 GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'BLTR', ignoring this field", data);
8187 return true;
8189 _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
8190 _cur.grfconfig->palette |= pal;
8192 return true;
8195 /** Callback function for 'INFO'->'VRSN' to the version of the NewGRF. */
8196 static bool ChangeGRFVersion(size_t len, ByteReader &buf)
8198 if (len != 4) {
8199 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got {}, ignoring this field", len);
8200 buf.Skip(len);
8201 } else {
8202 /* Set min_loadable_version as well (default to minimal compatibility) */
8203 _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf.ReadDWord();
8205 return true;
8208 /** Callback function for 'INFO'->'MINV' to the minimum compatible version of the NewGRF. */
8209 static bool ChangeGRFMinVersion(size_t len, ByteReader &buf)
8211 if (len != 4) {
8212 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got {}, ignoring this field", len);
8213 buf.Skip(len);
8214 } else {
8215 _cur.grfconfig->min_loadable_version = buf.ReadDWord();
8216 if (_cur.grfconfig->version == 0) {
8217 GrfMsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
8218 _cur.grfconfig->min_loadable_version = 0;
8220 if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
8221 GrfMsg(2, "StaticGRFInfo: 'MINV' defined as {}, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
8222 _cur.grfconfig->min_loadable_version = _cur.grfconfig->version;
8225 return true;
8228 static GRFParameterInfo *_cur_parameter; ///< The parameter which info is currently changed by the newgrf.
8230 /** Callback function for 'INFO'->'PARAM'->param_num->'NAME' to set the name of a parameter. */
8231 static bool ChangeGRFParamName(uint8_t langid, std::string_view str)
8233 AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
8234 return true;
8237 /** Callback function for 'INFO'->'PARAM'->param_num->'DESC' to set the description of a parameter. */
8238 static bool ChangeGRFParamDescription(uint8_t langid, std::string_view str)
8240 AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
8241 return true;
8244 /** Callback function for 'INFO'->'PARAM'->param_num->'TYPE' to set the typeof a parameter. */
8245 static bool ChangeGRFParamType(size_t len, ByteReader &buf)
8247 if (len != 1) {
8248 GrfMsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got {}, ignoring this field", len);
8249 buf.Skip(len);
8250 } else {
8251 GRFParameterType type = (GRFParameterType)buf.ReadByte();
8252 if (type < PTYPE_END) {
8253 _cur_parameter->type = type;
8254 } else {
8255 GrfMsg(3, "StaticGRFInfo: unknown parameter type {}, ignoring this field", type);
8258 return true;
8261 /** Callback function for 'INFO'->'PARAM'->param_num->'LIMI' to set the min/max value of a parameter. */
8262 static bool ChangeGRFParamLimits(size_t len, ByteReader &buf)
8264 if (_cur_parameter->type != PTYPE_UINT_ENUM) {
8265 GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8266 buf.Skip(len);
8267 } else if (len != 8) {
8268 GrfMsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got {}, ignoring this field", len);
8269 buf.Skip(len);
8270 } else {
8271 uint32_t min_value = buf.ReadDWord();
8272 uint32_t max_value = buf.ReadDWord();
8273 if (min_value <= max_value) {
8274 _cur_parameter->min_value = min_value;
8275 _cur_parameter->max_value = max_value;
8276 } else {
8277 GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8280 return true;
8283 /** Callback function for 'INFO'->'PARAM'->param_num->'MASK' to set the parameter and bits to use. */
8284 static bool ChangeGRFParamMask(size_t len, ByteReader &buf)
8286 if (len < 1 || len > 3) {
8287 GrfMsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got {}, ignoring this field", len);
8288 buf.Skip(len);
8289 } else {
8290 uint8_t param_nr = buf.ReadByte();
8291 if (param_nr >= _cur.grfconfig->param.size()) {
8292 GrfMsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param {}, ignoring this field", param_nr);
8293 buf.Skip(len - 1);
8294 } else {
8295 _cur_parameter->param_nr = param_nr;
8296 if (len >= 2) _cur_parameter->first_bit = std::min<uint8_t>(buf.ReadByte(), 31);
8297 if (len >= 3) _cur_parameter->num_bit = std::min<uint8_t>(buf.ReadByte(), 32 - _cur_parameter->first_bit);
8301 return true;
8304 /** Callback function for 'INFO'->'PARAM'->param_num->'DFLT' to set the default value. */
8305 static bool ChangeGRFParamDefault(size_t len, ByteReader &buf)
8307 if (len != 4) {
8308 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got {}, ignoring this field", len);
8309 buf.Skip(len);
8310 } else {
8311 _cur_parameter->def_value = buf.ReadDWord();
8313 _cur.grfconfig->has_param_defaults = true;
8314 return true;
8317 typedef bool (*DataHandler)(size_t, ByteReader &); ///< Type of callback function for binary nodes
8318 typedef bool (*TextHandler)(uint8_t, std::string_view str); ///< Type of callback function for text nodes
8319 typedef bool (*BranchHandler)(ByteReader &); ///< Type of callback function for branch nodes
8322 * Data structure to store the allowed id/type combinations for action 14. The
8323 * data can be represented as a tree with 3 types of nodes:
8324 * 1. Branch nodes (identified by 'C' for choice).
8325 * 2. Binary leaf nodes (identified by 'B').
8326 * 3. Text leaf nodes (identified by 'T').
8328 struct AllowedSubtags {
8329 /** Create empty subtags object used to identify the end of a list. */
8330 AllowedSubtags() :
8331 id(0),
8332 type(0)
8336 * Create a binary leaf node.
8337 * @param id The id for this node.
8338 * @param handler The callback function to call.
8340 AllowedSubtags(uint32_t id, DataHandler handler) :
8341 id(id),
8342 type('B')
8344 this->handler.data = handler;
8348 * Create a text leaf node.
8349 * @param id The id for this node.
8350 * @param handler The callback function to call.
8352 AllowedSubtags(uint32_t id, TextHandler handler) :
8353 id(id),
8354 type('T')
8356 this->handler.text = handler;
8360 * Create a branch node with a callback handler
8361 * @param id The id for this node.
8362 * @param handler The callback function to call.
8364 AllowedSubtags(uint32_t id, BranchHandler handler) :
8365 id(id),
8366 type('C')
8368 this->handler.call_handler = true;
8369 this->handler.u.branch = handler;
8373 * Create a branch node with a list of sub-nodes.
8374 * @param id The id for this node.
8375 * @param subtags Array with all valid subtags.
8377 AllowedSubtags(uint32_t id, AllowedSubtags *subtags) :
8378 id(id),
8379 type('C')
8381 this->handler.call_handler = false;
8382 this->handler.u.subtags = subtags;
8385 uint32_t id; ///< The identifier for this node
8386 uint8_t type; ///< The type of the node, must be one of 'C', 'B' or 'T'.
8387 union {
8388 DataHandler data; ///< Callback function for a binary node, only valid if type == 'B'.
8389 TextHandler text; ///< Callback function for a text node, only valid if type == 'T'.
8390 struct {
8391 union {
8392 BranchHandler branch; ///< Callback function for a branch node, only valid if type == 'C' && call_handler.
8393 AllowedSubtags *subtags; ///< Pointer to a list of subtags, only valid if type == 'C' && !call_handler.
8394 } u;
8395 bool call_handler; ///< True if there is a callback function for this node, false if there is a list of subnodes.
8397 } handler;
8400 static bool SkipUnknownInfo(ByteReader &buf, uint8_t type);
8401 static bool HandleNodes(ByteReader &buf, AllowedSubtags *tags);
8404 * Callback function for 'INFO'->'PARA'->param_num->'VALU' to set the names
8405 * of some parameter values (type uint/enum) or the names of some bits
8406 * (type bitmask). In both cases the format is the same:
8407 * Each subnode should be a text node with the value/bit number as id.
8409 static bool ChangeGRFParamValueNames(ByteReader &buf)
8411 uint8_t type = buf.ReadByte();
8412 while (type != 0) {
8413 uint32_t id = buf.ReadDWord();
8414 if (type != 'T' || id > _cur_parameter->max_value) {
8415 GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8416 if (!SkipUnknownInfo(buf, type)) return false;
8417 type = buf.ReadByte();
8418 continue;
8421 uint8_t langid = buf.ReadByte();
8422 std::string_view name_string = buf.ReadString();
8424 auto val_name = _cur_parameter->value_names.find(id);
8425 if (val_name != _cur_parameter->value_names.end()) {
8426 AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8427 } else {
8428 GRFTextList list;
8429 AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8430 _cur_parameter->value_names[id] = list;
8433 type = buf.ReadByte();
8435 return true;
8438 /** Action14 parameter tags */
8439 AllowedSubtags _tags_parameters[] = {
8440 AllowedSubtags('NAME', ChangeGRFParamName),
8441 AllowedSubtags('DESC', ChangeGRFParamDescription),
8442 AllowedSubtags('TYPE', ChangeGRFParamType),
8443 AllowedSubtags('LIMI', ChangeGRFParamLimits),
8444 AllowedSubtags('MASK', ChangeGRFParamMask),
8445 AllowedSubtags('VALU', ChangeGRFParamValueNames),
8446 AllowedSubtags('DFLT', ChangeGRFParamDefault),
8447 AllowedSubtags()
8451 * Callback function for 'INFO'->'PARA' to set extra information about the
8452 * parameters. Each subnode of 'INFO'->'PARA' should be a branch node with
8453 * the parameter number as id. The first parameter has id 0. The maximum
8454 * parameter that can be changed is set by 'INFO'->'NPAR' which defaults to 80.
8456 static bool HandleParameterInfo(ByteReader &buf)
8458 uint8_t type = buf.ReadByte();
8459 while (type != 0) {
8460 uint32_t id = buf.ReadDWord();
8461 if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8462 GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8463 if (!SkipUnknownInfo(buf, type)) return false;
8464 type = buf.ReadByte();
8465 continue;
8468 if (id >= _cur.grfconfig->param_info.size()) {
8469 _cur.grfconfig->param_info.resize(id + 1);
8471 if (!_cur.grfconfig->param_info[id].has_value()) {
8472 _cur.grfconfig->param_info[id] = GRFParameterInfo(id);
8474 _cur_parameter = &_cur.grfconfig->param_info[id].value();
8475 /* Read all parameter-data and process each node. */
8476 if (!HandleNodes(buf, _tags_parameters)) return false;
8477 type = buf.ReadByte();
8479 return true;
8482 /** Action14 tags for the INFO node */
8483 AllowedSubtags _tags_info[] = {
8484 AllowedSubtags('NAME', ChangeGRFName),
8485 AllowedSubtags('DESC', ChangeGRFDescription),
8486 AllowedSubtags('URL_', ChangeGRFURL),
8487 AllowedSubtags('NPAR', ChangeGRFNumUsedParams),
8488 AllowedSubtags('PALS', ChangeGRFPalette),
8489 AllowedSubtags('BLTR', ChangeGRFBlitter),
8490 AllowedSubtags('VRSN', ChangeGRFVersion),
8491 AllowedSubtags('MINV', ChangeGRFMinVersion),
8492 AllowedSubtags('PARA', HandleParameterInfo),
8493 AllowedSubtags()
8496 /** Action14 root tags */
8497 AllowedSubtags _tags_root[] = {
8498 AllowedSubtags('INFO', _tags_info),
8499 AllowedSubtags()
8504 * Try to skip the current node and all subnodes (if it's a branch node).
8505 * @param buf Buffer.
8506 * @param type The node type to skip.
8507 * @return True if we could skip the node, false if an error occurred.
8509 static bool SkipUnknownInfo(ByteReader &buf, uint8_t type)
8511 /* type and id are already read */
8512 switch (type) {
8513 case 'C': {
8514 uint8_t new_type = buf.ReadByte();
8515 while (new_type != 0) {
8516 buf.ReadDWord(); // skip the id
8517 if (!SkipUnknownInfo(buf, new_type)) return false;
8518 new_type = buf.ReadByte();
8520 break;
8523 case 'T':
8524 buf.ReadByte(); // lang
8525 buf.ReadString(); // actual text
8526 break;
8528 case 'B': {
8529 uint16_t size = buf.ReadWord();
8530 buf.Skip(size);
8531 break;
8534 default:
8535 return false;
8538 return true;
8542 * Handle the nodes of an Action14
8543 * @param type Type of node.
8544 * @param id ID.
8545 * @param buf Buffer.
8546 * @param subtags Allowed subtags.
8547 * @return Whether all tags could be handled.
8549 static bool HandleNode(uint8_t type, uint32_t id, ByteReader &buf, AllowedSubtags subtags[])
8551 uint i = 0;
8552 AllowedSubtags *tag;
8553 while ((tag = &subtags[i++])->type != 0) {
8554 if (tag->id != BSWAP32(id) || tag->type != type) continue;
8555 switch (type) {
8556 default: NOT_REACHED();
8558 case 'T': {
8559 uint8_t langid = buf.ReadByte();
8560 return tag->handler.text(langid, buf.ReadString());
8563 case 'B': {
8564 size_t len = buf.ReadWord();
8565 if (buf.Remaining() < len) return false;
8566 return tag->handler.data(len, buf);
8569 case 'C': {
8570 if (tag->handler.call_handler) {
8571 return tag->handler.u.branch(buf);
8573 return HandleNodes(buf, tag->handler.u.subtags);
8577 GrfMsg(2, "StaticGRFInfo: unknown type/id combination found, type={:c}, id={:x}", type, id);
8578 return SkipUnknownInfo(buf, type);
8582 * Handle the contents of a 'C' choice of an Action14
8583 * @param buf Buffer.
8584 * @param subtags List of subtags.
8585 * @return Whether the nodes could all be handled.
8587 static bool HandleNodes(ByteReader &buf, AllowedSubtags subtags[])
8589 uint8_t type = buf.ReadByte();
8590 while (type != 0) {
8591 uint32_t id = buf.ReadDWord();
8592 if (!HandleNode(type, id, buf, subtags)) return false;
8593 type = buf.ReadByte();
8595 return true;
8599 * Handle Action 0x14
8600 * @param buf Buffer.
8602 static void StaticGRFInfo(ByteReader &buf)
8604 /* <14> <type> <id> <text/data...> */
8605 HandleNodes(buf, _tags_root);
8609 * Set the current NewGRF as unsafe for static use
8610 * @note Used during safety scan on unsafe actions.
8612 static void GRFUnsafe(ByteReader &)
8614 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8616 /* Skip remainder of GRF */
8617 _cur.skip_sprites = -1;
8621 /** Initialize the TTDPatch flags */
8622 static void InitializeGRFSpecial()
8624 _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1U : 0U) << 0x0C) // keepsmallairport
8625 | (1U << 0x0D) // newairports
8626 | (1U << 0x0E) // largestations
8627 | ((_settings_game.construction.max_bridge_length > 16 ? 1U : 0U) << 0x0F) // longbridges
8628 | (0U << 0x10) // loadtime
8629 | (1U << 0x12) // presignals
8630 | (1U << 0x13) // extpresignals
8631 | ((_settings_game.vehicle.never_expire_vehicles ? 1U : 0U) << 0x16) // enginespersist
8632 | (1U << 0x1B) // multihead
8633 | (1U << 0x1D) // lowmemory
8634 | (1U << 0x1E); // generalfixes
8636 _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1U : 0U) << 0x07) // moreairports - based on units of noise
8637 | (1U << 0x08) // mammothtrains
8638 | (1U << 0x09) // trainrefit
8639 | (0U << 0x0B) // subsidiaries
8640 | ((_settings_game.order.gradual_loading ? 1U : 0U) << 0x0C) // gradualloading
8641 | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8642 | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8643 | (1U << 0x14) // bridgespeedlimits
8644 | (1U << 0x16) // eternalgame
8645 | (1U << 0x17) // newtrains
8646 | (1U << 0x18) // newrvs
8647 | (1U << 0x19) // newships
8648 | (1U << 0x1A) // newplanes
8649 | ((_settings_game.construction.train_signal_side == 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8650 | ((_settings_game.vehicle.disable_elrails ? 0U : 1U) << 0x1C); // electrifiedrailway
8652 _ttdpatch_flags[2] = (1U << 0x01) // loadallgraphics - obsolote
8653 | (1U << 0x03) // semaphores
8654 | (1U << 0x0A) // newobjects
8655 | (0U << 0x0B) // enhancedgui
8656 | (0U << 0x0C) // newagerating
8657 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x0D) // buildonslopes
8658 | (1U << 0x0E) // fullloadany
8659 | (1U << 0x0F) // planespeed
8660 | (0U << 0x10) // moreindustriesperclimate - obsolete
8661 | (0U << 0x11) // moretoylandfeatures
8662 | (1U << 0x12) // newstations
8663 | (1U << 0x13) // tracktypecostdiff
8664 | (1U << 0x14) // manualconvert
8665 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x15) // buildoncoasts
8666 | (1U << 0x16) // canals
8667 | (1U << 0x17) // newstartyear
8668 | ((_settings_game.vehicle.freight_trains > 1 ? 1U : 0U) << 0x18) // freighttrains
8669 | (1U << 0x19) // newhouses
8670 | (1U << 0x1A) // newbridges
8671 | (1U << 0x1B) // newtownnames
8672 | (1U << 0x1C) // moreanimation
8673 | ((_settings_game.vehicle.wagon_speed_limits ? 1U : 0U) << 0x1D) // wagonspeedlimits
8674 | (1U << 0x1E) // newshistory
8675 | (0U << 0x1F); // custombridgeheads
8677 _ttdpatch_flags[3] = (0U << 0x00) // newcargodistribution
8678 | (1U << 0x01) // windowsnap
8679 | ((_settings_game.economy.allow_town_roads || _generating_world ? 0U : 1U) << 0x02) // townbuildnoroad
8680 | (1U << 0x03) // pathbasedsignalling
8681 | (0U << 0x04) // aichoosechance
8682 | (1U << 0x05) // resolutionwidth
8683 | (1U << 0x06) // resolutionheight
8684 | (1U << 0x07) // newindustries
8685 | ((_settings_game.order.improved_load ? 1U : 0U) << 0x08) // fifoloading
8686 | (0U << 0x09) // townroadbranchprob
8687 | (0U << 0x0A) // tempsnowline
8688 | (1U << 0x0B) // newcargo
8689 | (1U << 0x0C) // enhancemultiplayer
8690 | (1U << 0x0D) // onewayroads
8691 | (1U << 0x0E) // irregularstations
8692 | (1U << 0x0F) // statistics
8693 | (1U << 0x10) // newsounds
8694 | (1U << 0x11) // autoreplace
8695 | (1U << 0x12) // autoslope
8696 | (0U << 0x13) // followvehicle
8697 | (1U << 0x14) // trams
8698 | (0U << 0x15) // enhancetunnels
8699 | (1U << 0x16) // shortrvs
8700 | (1U << 0x17) // articulatedrvs
8701 | ((_settings_game.vehicle.dynamic_engines ? 1U : 0U) << 0x18) // dynamic engines
8702 | (1U << 0x1E) // variablerunningcosts
8703 | (1U << 0x1F); // any switch is on
8705 _ttdpatch_flags[4] = (1U << 0x00) // larger persistent storage
8706 | ((_settings_game.economy.inflation ? 1U : 0U) << 0x01) // inflation is on
8707 | (1U << 0x02); // extended string range
8710 /** Reset and clear all NewGRF stations */
8711 static void ResetCustomStations()
8713 for (GRFFile * const file : _grf_files) {
8714 file->stations.clear();
8718 /** Reset and clear all NewGRF houses */
8719 static void ResetCustomHouses()
8721 for (GRFFile * const file : _grf_files) {
8722 file->housespec.clear();
8726 /** Reset and clear all NewGRF airports */
8727 static void ResetCustomAirports()
8729 for (GRFFile * const file : _grf_files) {
8730 file->airportspec.clear();
8731 file->airtspec.clear();
8735 /** Reset and clear all NewGRF industries */
8736 static void ResetCustomIndustries()
8738 for (GRFFile * const file : _grf_files) {
8739 file->industryspec.clear();
8740 file->indtspec.clear();
8744 /** Reset and clear all NewObjects */
8745 static void ResetCustomObjects()
8747 for (GRFFile * const file : _grf_files) {
8748 file->objectspec.clear();
8752 static void ResetCustomRoadStops()
8754 for (auto file : _grf_files) {
8755 file->roadstops.clear();
8759 /** Reset and clear all NewGRFs */
8760 static void ResetNewGRF()
8762 for (GRFFile * const file : _grf_files) {
8763 delete file;
8766 _grf_files.clear();
8767 _cur.grffile = nullptr;
8770 /** Clear all NewGRF errors */
8771 static void ResetNewGRFErrors()
8773 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8774 c->error.reset();
8779 * Reset all NewGRF loaded data
8781 void ResetNewGRFData()
8783 CleanUpStrings();
8784 CleanUpGRFTownNames();
8786 /* Copy/reset original engine info data */
8787 SetupEngines();
8789 /* Copy/reset original bridge info data */
8790 ResetBridges();
8792 /* Reset rail type information */
8793 ResetRailTypes();
8795 /* Copy/reset original road type info data */
8796 ResetRoadTypes();
8798 /* Allocate temporary refit/cargo class data */
8799 _gted.resize(Engine::GetPoolSize());
8801 /* Fill rail type label temporary data for default trains */
8802 for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8803 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8806 /* Reset GRM reservations */
8807 memset(&_grm_engines, 0, sizeof(_grm_engines));
8808 memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8810 /* Reset generic feature callback lists */
8811 ResetGenericCallbacks();
8813 /* Reset price base data */
8814 ResetPriceBaseMultipliers();
8816 /* Reset the curencies array */
8817 ResetCurrencies();
8819 /* Reset the house array */
8820 ResetCustomHouses();
8821 ResetHouses();
8823 /* Reset the industries structures*/
8824 ResetCustomIndustries();
8825 ResetIndustries();
8827 /* Reset the objects. */
8828 ObjectClass::Reset();
8829 ResetCustomObjects();
8830 ResetObjects();
8832 /* Reset station classes */
8833 StationClass::Reset();
8834 ResetCustomStations();
8836 /* Reset airport-related structures */
8837 AirportClass::Reset();
8838 ResetCustomAirports();
8839 AirportSpec::ResetAirports();
8840 AirportTileSpec::ResetAirportTiles();
8842 /* Reset road stop classes */
8843 RoadStopClass::Reset();
8844 ResetCustomRoadStops();
8846 /* Reset canal sprite groups and flags */
8847 memset(_water_feature, 0, sizeof(_water_feature));
8849 /* Reset the snowline table. */
8850 ClearSnowLine();
8852 /* Reset NewGRF files */
8853 ResetNewGRF();
8855 /* Reset NewGRF errors. */
8856 ResetNewGRFErrors();
8858 /* Set up the default cargo types */
8859 SetupCargoForClimate(_settings_game.game_creation.landscape);
8861 /* Reset misc GRF features and train list display variables */
8862 _misc_grf_features = 0;
8864 _loaded_newgrf_features.has_2CC = false;
8865 _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8866 _loaded_newgrf_features.shore = SHORE_REPLACE_NONE;
8867 _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NONE;
8869 /* Clear all GRF overrides */
8870 _grf_id_overrides.clear();
8872 InitializeSoundPool();
8873 _spritegroup_pool.CleanPool();
8877 * Reset NewGRF data which is stored persistently in savegames.
8879 void ResetPersistentNewGRFData()
8881 /* Reset override managers */
8882 _engine_mngr.ResetToDefaultMapping();
8883 _house_mngr.ResetMapping();
8884 _industry_mngr.ResetMapping();
8885 _industile_mngr.ResetMapping();
8886 _airport_mngr.ResetMapping();
8887 _airporttile_mngr.ResetMapping();
8891 * Construct the Cargo Mapping
8892 * @note This is the reverse of a cargo translation table
8894 static void BuildCargoTranslationMap()
8896 _cur.grffile->cargo_map.fill(UINT8_MAX);
8898 for (const CargoSpec *cs : CargoSpec::Iterate()) {
8899 if (!cs->IsValid()) continue;
8901 if (_cur.grffile->cargo_list.empty()) {
8902 /* Default translation table, so just a straight mapping to bitnum */
8903 _cur.grffile->cargo_map[cs->Index()] = cs->bitnum;
8904 } else {
8905 /* Check the translation table for this cargo's label */
8906 int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8907 if (idx >= 0) _cur.grffile->cargo_map[cs->Index()] = idx;
8913 * Prepare loading a NewGRF file with its config
8914 * @param config The NewGRF configuration struct with name, id, parameters and alike.
8916 static void InitNewGRFFile(const GRFConfig *config)
8918 GRFFile *newfile = GetFileByFilename(config->filename);
8919 if (newfile != nullptr) {
8920 /* We already loaded it once. */
8921 _cur.grffile = newfile;
8922 return;
8925 newfile = new GRFFile(config);
8926 _grf_files.push_back(_cur.grffile = newfile);
8930 * Constructor for GRFFile
8931 * @param config GRFConfig to copy name, grfid and parameters from.
8933 GRFFile::GRFFile(const GRFConfig *config)
8935 this->filename = config->filename;
8936 this->grfid = config->ident.grfid;
8938 /* Initialise local settings to defaults */
8939 this->traininfo_vehicle_pitch = 0;
8940 this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8942 /* Mark price_base_multipliers as 'not set' */
8943 for (Price i = PR_BEGIN; i < PR_END; i++) {
8944 this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8947 /* Initialise rail type map with default rail types */
8948 std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8949 this->railtype_map[0] = RAILTYPE_RAIL;
8950 this->railtype_map[1] = RAILTYPE_ELECTRIC;
8951 this->railtype_map[2] = RAILTYPE_MONO;
8952 this->railtype_map[3] = RAILTYPE_MAGLEV;
8954 /* Initialise road type map with default road types */
8955 std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8956 this->roadtype_map[0] = ROADTYPE_ROAD;
8958 /* Initialise tram type map with default tram types */
8959 std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8960 this->tramtype_map[0] = ROADTYPE_TRAM;
8962 /* Copy the initial parameter list
8963 * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8964 this->param = config->param;
8965 this->param_end = config->num_params;
8969 * Find first cargo label that exists and is active from a list of cargo labels.
8970 * @param labels List of cargo labels.
8971 * @returns First cargo label in list that exists, or CT_INVALID if none exist.
8973 static CargoLabel GetActiveCargoLabel(const std::initializer_list<CargoLabel> &labels)
8975 for (const CargoLabel &label : labels) {
8976 CargoID cid = GetCargoIDByLabel(label);
8977 if (cid != INVALID_CARGO) return label;
8979 return CT_INVALID;
8983 * Get active cargo label from either a cargo label or climate-dependent mixed cargo type.
8984 * @param label Cargo label or climate-dependent mixed cargo type.
8985 * @returns Active cargo label, or CT_INVALID if cargo label is not active.
8987 static CargoLabel GetActiveCargoLabel(const std::variant<CargoLabel, MixedCargoType> &label)
8989 if (std::holds_alternative<CargoLabel>(label)) return std::get<CargoLabel>(label);
8990 if (std::holds_alternative<MixedCargoType>(label)) {
8991 switch (std::get<MixedCargoType>(label)) {
8992 case MCT_LIVESTOCK_FRUIT: return GetActiveCargoLabel({CT_LIVESTOCK, CT_FRUIT});
8993 case MCT_GRAIN_WHEAT_MAIZE: return GetActiveCargoLabel({CT_GRAIN, CT_WHEAT, CT_MAIZE});
8994 case MCT_VALUABLES_GOLD_DIAMONDS: return GetActiveCargoLabel({CT_VALUABLES, CT_GOLD, CT_DIAMONDS});
8995 default: NOT_REACHED();
8998 NOT_REACHED();
9002 * Precalculate refit masks from cargo classes for all vehicles.
9004 static void CalculateRefitMasks()
9006 CargoTypes original_known_cargoes = 0;
9007 for (CargoID cid = 0; cid != NUM_CARGO; ++cid) {
9008 if (IsDefaultCargo(cid)) SetBit(original_known_cargoes, cid);
9011 for (Engine *e : Engine::Iterate()) {
9012 EngineID engine = e->index;
9013 EngineInfo *ei = &e->info;
9014 bool only_defaultcargo; ///< Set if the vehicle shall carry only the default cargo
9016 /* Apply default cargo translation map if cargo type hasn't been set, either explicitly or by aircraft cargo handling. */
9017 if (!IsValidCargoID(e->info.cargo_type)) {
9018 e->info.cargo_type = GetCargoIDByLabel(GetActiveCargoLabel(e->info.cargo_label));
9021 /* If the NewGRF did not set any cargo properties, we apply default values. */
9022 if (_gted[engine].defaultcargo_grf == nullptr) {
9023 /* If the vehicle has any capacity, apply the default refit masks */
9024 if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
9025 static constexpr uint8_t T = 1 << LT_TEMPERATE;
9026 static constexpr uint8_t A = 1 << LT_ARCTIC;
9027 static constexpr uint8_t S = 1 << LT_TROPIC;
9028 static constexpr uint8_t Y = 1 << LT_TOYLAND;
9029 static const struct DefaultRefitMasks {
9030 uint8_t climate;
9031 CargoLabel cargo_label;
9032 CargoClasses cargo_allowed;
9033 CargoClasses cargo_disallowed;
9034 } _default_refit_masks[] = {
9035 {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
9036 {T | A | S , CT_MAIL, CC_MAIL, 0},
9037 {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
9038 { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
9039 {T | A , CT_COAL, CC_BULK, 0},
9040 { S , CT_COPPER_ORE, CC_BULK, 0},
9041 { Y, CT_SUGAR, CC_BULK, 0},
9042 {T | A | S , CT_OIL, CC_LIQUID, 0},
9043 { Y, CT_COLA, CC_LIQUID, 0},
9044 {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
9045 { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
9046 { A | S , CT_FOOD, CC_REFRIGERATED, 0},
9047 { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
9050 if (e->type == VEH_AIRCRAFT) {
9051 /* Aircraft default to "light" cargoes */
9052 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
9053 _gted[engine].cargo_disallowed = CC_LIQUID;
9054 } else if (e->type == VEH_SHIP) {
9055 CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
9056 switch (label.base()) {
9057 case CT_PASSENGERS.base():
9058 /* Ferries */
9059 _gted[engine].cargo_allowed = CC_PASSENGERS;
9060 _gted[engine].cargo_disallowed = 0;
9061 break;
9062 case CT_OIL.base():
9063 /* Tankers */
9064 _gted[engine].cargo_allowed = CC_LIQUID;
9065 _gted[engine].cargo_disallowed = 0;
9066 break;
9067 default:
9068 /* Cargo ships */
9069 if (_settings_game.game_creation.landscape == LT_TOYLAND) {
9070 /* No tanker in toyland :( */
9071 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9072 _gted[engine].cargo_disallowed = CC_PASSENGERS;
9073 } else {
9074 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
9075 _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
9077 break;
9079 e->u.ship.old_refittable = true;
9080 } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
9081 /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
9082 * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
9083 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9084 _gted[engine].cargo_disallowed = 0;
9085 } else {
9086 /* Train wagons and road vehicles are classified by their default cargo type */
9087 CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
9088 for (const auto &drm : _default_refit_masks) {
9089 if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
9090 if (drm.cargo_label != label) continue;
9092 _gted[engine].cargo_allowed = drm.cargo_allowed;
9093 _gted[engine].cargo_disallowed = drm.cargo_disallowed;
9094 break;
9097 /* All original cargoes have specialised vehicles, so exclude them */
9098 _gted[engine].ctt_exclude_mask = original_known_cargoes;
9101 _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
9103 if (IsValidCargoID(ei->cargo_type)) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
9106 /* Compute refittability */
9108 CargoTypes mask = 0;
9109 CargoTypes not_mask = 0;
9110 CargoTypes xor_mask = ei->refit_mask;
9112 /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
9113 * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
9114 only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
9116 if (_gted[engine].cargo_allowed != 0) {
9117 /* Build up the list of cargo types from the set cargo classes. */
9118 for (const CargoSpec *cs : CargoSpec::Iterate()) {
9119 if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
9120 if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
9124 ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
9126 /* Apply explicit refit includes/excludes. */
9127 ei->refit_mask |= _gted[engine].ctt_include_mask;
9128 ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
9131 /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
9132 if (IsValidCargoID(ei->cargo_type) && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = INVALID_CARGO;
9134 /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
9135 * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
9136 if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && IsValidCargoID(ei->cargo_type) && !HasBit(ei->refit_mask, ei->cargo_type)) {
9137 ei->cargo_type = INVALID_CARGO;
9140 /* Check if this engine's cargo type is valid. If not, set to the first refittable
9141 * cargo type. Finally disable the vehicle, if there is still no cargo. */
9142 if (!IsValidCargoID(ei->cargo_type) && ei->refit_mask != 0) {
9143 /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
9144 const GRFFile *file = _gted[engine].defaultcargo_grf;
9145 if (file == nullptr) file = e->GetGRF();
9146 if (file != nullptr && file->grf_version >= 8 && !file->cargo_list.empty()) {
9147 /* Use first refittable cargo from cargo translation table */
9148 uint8_t best_local_slot = UINT8_MAX;
9149 for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
9150 uint8_t local_slot = file->cargo_map[cargo_type];
9151 if (local_slot < best_local_slot) {
9152 best_local_slot = local_slot;
9153 ei->cargo_type = cargo_type;
9158 if (!IsValidCargoID(ei->cargo_type)) {
9159 /* Use first refittable cargo slot */
9160 ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
9163 if (!IsValidCargoID(ei->cargo_type) && e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON && e->u.rail.capacity == 0) {
9164 /* For train engines which do not carry cargo it does not matter if their cargo type is invalid.
9165 * Fallback to the first available instead, if the cargo type has not been changed (as indicated by
9166 * cargo_label not being CT_INVALID). */
9167 if (GetActiveCargoLabel(ei->cargo_label) != CT_INVALID) {
9168 ei->cargo_type = static_cast<CargoID>(FindFirstBit(_standard_cargo_mask));
9171 if (!IsValidCargoID(ei->cargo_type)) ei->climates = 0;
9173 /* Clear refit_mask for not refittable ships */
9174 if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
9175 ei->refit_mask = 0;
9180 /** Set to use the correct action0 properties for each canal feature */
9181 static void FinaliseCanals()
9183 for (uint i = 0; i < CF_END; i++) {
9184 if (_water_feature[i].grffile != nullptr) {
9185 _water_feature[i].callback_mask = _water_feature[i].grffile->canal_local_properties[i].callback_mask;
9186 _water_feature[i].flags = _water_feature[i].grffile->canal_local_properties[i].flags;
9191 /** Check for invalid engines */
9192 static void FinaliseEngineArray()
9194 for (Engine *e : Engine::Iterate()) {
9195 if (e->GetGRF() == nullptr) {
9196 const EngineIDMapping &eid = _engine_mngr[e->index];
9197 if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
9198 e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
9202 /* Do final mapping on variant engine ID. */
9203 if (e->info.variant_id != INVALID_ENGINE) {
9204 e->info.variant_id = GetNewEngineID(e->grf_prop.grffile, e->type, e->info.variant_id);
9207 if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
9209 /* Skip wagons, there livery is defined via the engine */
9210 if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
9211 LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, nullptr);
9212 SetBit(_loaded_newgrf_features.used_liveries, ls);
9213 /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9215 if (e->type == VEH_TRAIN) {
9216 SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
9217 switch (ls) {
9218 case LS_STEAM:
9219 case LS_DIESEL:
9220 case LS_ELECTRIC:
9221 case LS_MONORAIL:
9222 case LS_MAGLEV:
9223 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
9224 break;
9226 case LS_DMU:
9227 case LS_EMU:
9228 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
9229 break;
9231 default: NOT_REACHED();
9237 /* Check engine variants don't point back on themselves (either directly or via a loop) then set appropriate flags
9238 * on variant engine. This is performed separately as all variant engines need to have been resolved. */
9239 for (Engine *e : Engine::Iterate()) {
9240 EngineID parent = e->info.variant_id;
9241 while (parent != INVALID_ENGINE) {
9242 parent = Engine::Get(parent)->info.variant_id;
9243 if (parent != e->index) continue;
9245 /* Engine looped back on itself, so clear the variant. */
9246 e->info.variant_id = INVALID_ENGINE;
9248 GrfMsg(1, "FinaliseEngineArray: Variant of engine {:x} in '{}' loops back on itself", _engine_mngr[e->index].internal_id, e->GetGRF()->filename);
9249 break;
9252 if (e->info.variant_id != INVALID_ENGINE) {
9253 Engine::Get(e->info.variant_id)->display_flags |= EngineDisplayFlags::HasVariants | EngineDisplayFlags::IsFolded;
9258 /** Check for invalid cargoes */
9259 void FinaliseCargoArray()
9261 for (CargoSpec &cs : CargoSpec::array) {
9262 if (cs.town_production_effect == INVALID_TPE) {
9263 /* Set default town production effect by cargo label. */
9264 switch (cs.label.base()) {
9265 case CT_PASSENGERS.base(): cs.town_production_effect = TPE_PASSENGERS; break;
9266 case CT_MAIL.base(): cs.town_production_effect = TPE_MAIL; break;
9267 default: cs.town_production_effect = TPE_NONE; break;
9270 if (!cs.IsValid()) {
9271 cs.name = cs.name_single = cs.units_volume = STR_NEWGRF_INVALID_CARGO;
9272 cs.quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9273 cs.abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9279 * Check if a given housespec is valid and disable it if it's not.
9280 * The housespecs that follow it are used to check the validity of
9281 * multitile houses.
9282 * @param hs The housespec to check.
9283 * @param next1 The housespec that follows \c hs.
9284 * @param next2 The housespec that follows \c next1.
9285 * @param next3 The housespec that follows \c next2.
9286 * @param filename The filename of the newgrf this house was defined in.
9287 * @return Whether the given housespec is valid.
9289 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const std::string &filename)
9291 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9292 (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9293 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9294 (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9295 next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9296 hs->enabled = false;
9297 if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9298 return false;
9301 /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9302 * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9303 * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9304 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9305 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9306 hs->enabled = false;
9307 if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines multitile house {} with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
9308 return false;
9311 /* Substitute type is also used for override, and having an override with a different size causes crashes.
9312 * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9313 if (!filename.empty() && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9314 hs->enabled = false;
9315 Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9316 return false;
9319 /* Make sure that additional parts of multitile houses are not available. */
9320 if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9321 hs->enabled = false;
9322 if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
9323 return false;
9326 return true;
9330 * Make sure there is at least one house available in the year 0 for the given
9331 * climate / housezone combination.
9332 * @param bitmask The climate and housezone to check for. Exactly one climate
9333 * bit and one housezone bit should be set.
9335 static void EnsureEarlyHouse(HouseZones bitmask)
9337 TimerGameCalendar::Year min_year = CalendarTime::MAX_YEAR;
9339 for (const auto &hs : HouseSpec::Specs()) {
9340 if (!hs.enabled) continue;
9341 if ((hs.building_availability & bitmask) != bitmask) continue;
9342 if (hs.min_year < min_year) min_year = hs.min_year;
9345 if (min_year == 0) return;
9347 for (auto &hs : HouseSpec::Specs()) {
9348 if (!hs.enabled) continue;
9349 if ((hs.building_availability & bitmask) != bitmask) continue;
9350 if (hs.min_year == min_year) hs.min_year = 0;
9355 * Add all new houses to the house array. House properties can be set at any
9356 * time in the GRF file, so we can only add a house spec to the house array
9357 * after the file has finished loading. We also need to check the dates, due to
9358 * the TTDPatch behaviour described below that we need to emulate.
9360 static void FinaliseHouseArray()
9362 /* If there are no houses with start dates before 1930, then all houses
9363 * with start dates of 1930 have them reset to 0. This is in order to be
9364 * compatible with TTDPatch, where if no houses have start dates before
9365 * 1930 and the date is before 1930, the game pretends that this is 1930.
9366 * If there have been any houses defined with start dates before 1930 then
9367 * the dates are left alone.
9368 * On the other hand, why 1930? Just 'fix' the houses with the lowest
9369 * minimum introduction date to 0.
9371 for (GRFFile * const file : _grf_files) {
9372 if (file->housespec.empty()) continue;
9374 size_t num_houses = file->housespec.size();
9375 for (size_t i = 0; i < num_houses; i++) {
9376 HouseSpec *hs = file->housespec[i].get();
9378 if (hs == nullptr) continue;
9380 const HouseSpec *next1 = (i + 1 < num_houses ? file->housespec[i + 1].get() : nullptr);
9381 const HouseSpec *next2 = (i + 2 < num_houses ? file->housespec[i + 2].get() : nullptr);
9382 const HouseSpec *next3 = (i + 3 < num_houses ? file->housespec[i + 3].get() : nullptr);
9384 if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9386 _house_mngr.SetEntitySpec(hs);
9390 for (size_t i = 0; i < HouseSpec::Specs().size(); i++) {
9391 HouseSpec *hs = HouseSpec::Get(i);
9392 const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9393 const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9394 const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9396 /* We need to check all houses again to we are sure that multitile houses
9397 * did get consecutive IDs and none of the parts are missing. */
9398 if (!IsHouseSpecValid(hs, next1, next2, next3, std::string{})) {
9399 /* GetHouseNorthPart checks 3 houses that are directly before
9400 * it in the house pool. If any of those houses have multi-tile
9401 * flags set it assumes it's part of a multitile house. Since
9402 * we can have invalid houses in the pool marked as disabled, we
9403 * don't want to have them influencing valid tiles. As such set
9404 * building_flags to zero here to make sure any house following
9405 * this one in the pool is properly handled as 1x1 house. */
9406 hs->building_flags = TILE_NO_FLAG;
9409 /* Apply default cargo translation map for unset cargo slots */
9410 for (uint i = 0; i < lengthof(hs->accepts_cargo); ++i) {
9411 if (!IsValidCargoID(hs->accepts_cargo[i])) hs->accepts_cargo[i] = GetCargoIDByLabel(hs->accepts_cargo_label[i]);
9412 /* Disable acceptance if cargo type is invalid. */
9413 if (!IsValidCargoID(hs->accepts_cargo[i])) hs->cargo_acceptance[i] = 0;
9417 HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9418 EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9419 EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9420 EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9421 EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9422 EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9424 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9425 EnsureEarlyHouse(HZ_ZON1 | HZ_SUBARTC_ABOVE);
9426 EnsureEarlyHouse(HZ_ZON2 | HZ_SUBARTC_ABOVE);
9427 EnsureEarlyHouse(HZ_ZON3 | HZ_SUBARTC_ABOVE);
9428 EnsureEarlyHouse(HZ_ZON4 | HZ_SUBARTC_ABOVE);
9429 EnsureEarlyHouse(HZ_ZON5 | HZ_SUBARTC_ABOVE);
9434 * Add all new industries to the industry array. Industry properties can be set at any
9435 * time in the GRF file, so we can only add a industry spec to the industry array
9436 * after the file has finished loading.
9438 static void FinaliseIndustriesArray()
9440 for (GRFFile * const file : _grf_files) {
9441 for (const auto &indsp : file->industryspec) {
9442 if (indsp == nullptr || !indsp->enabled) continue;
9444 StringID strid;
9445 /* process the conversion of text at the end, so to be sure everything will be fine
9446 * and available. Check if it does not return undefind marker, which is a very good sign of a
9447 * substitute industry who has not changed the string been examined, thus using it as such */
9448 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9449 if (strid != STR_UNDEFINED) indsp->name = strid;
9451 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9452 if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9454 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9455 if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9457 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9458 if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9460 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9461 if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9463 if (indsp->station_name != STR_NULL) {
9464 /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9465 * station's name. Don't want to lose the value, therefore, do not process. */
9466 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9467 if (strid != STR_UNDEFINED) indsp->station_name = strid;
9470 _industry_mngr.SetEntitySpec(indsp.get());
9473 for (const auto &indtsp : file->indtspec) {
9474 if (indtsp != nullptr) {
9475 _industile_mngr.SetEntitySpec(indtsp.get());
9480 for (auto &indsp : _industry_specs) {
9481 if (indsp.enabled && indsp.grf_prop.grffile != nullptr) {
9482 for (auto &conflicting : indsp.conflicting) {
9483 conflicting = MapNewGRFIndustryType(conflicting, indsp.grf_prop.grffile->grfid);
9486 if (!indsp.enabled) {
9487 indsp.name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9490 /* Apply default cargo translation map for unset cargo slots */
9491 for (size_t i = 0; i < std::size(indsp.produced_cargo); ++i) {
9492 if (!IsValidCargoID(indsp.produced_cargo[i])) indsp.produced_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.produced_cargo_label[i]));
9494 for (size_t i = 0; i < std::size(indsp.accepts_cargo); ++i) {
9495 if (!IsValidCargoID(indsp.accepts_cargo[i])) indsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.accepts_cargo_label[i]));
9499 for (auto &indtsp : _industry_tile_specs) {
9500 /* Apply default cargo translation map for unset cargo slots */
9501 for (size_t i = 0; i < indtsp.accepts_cargo.size(); ++i) {
9502 if (!IsValidCargoID(indtsp.accepts_cargo[i])) indtsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indtsp.accepts_cargo_label[i]));
9508 * Add all new objects to the object array. Object properties can be set at any
9509 * time in the GRF file, so we can only add an object spec to the object array
9510 * after the file has finished loading.
9512 static void FinaliseObjectsArray()
9514 for (GRFFile * const file : _grf_files) {
9515 for (auto &objectspec : file->objectspec) {
9516 if (objectspec != nullptr && objectspec->grf_prop.grffile != nullptr && objectspec->IsEnabled()) {
9517 _object_mngr.SetEntitySpec(objectspec.get());
9522 ObjectSpec::BindToClasses();
9526 * Add all new airports to the airport array. Airport properties can be set at any
9527 * time in the GRF file, so we can only add a airport spec to the airport array
9528 * after the file has finished loading.
9530 static void FinaliseAirportsArray()
9532 for (GRFFile * const file : _grf_files) {
9533 for (auto &as : file->airportspec) {
9534 if (as != nullptr && as->enabled) {
9535 _airport_mngr.SetEntitySpec(as.get());
9539 for (auto &ats : file->airtspec) {
9540 if (ats != nullptr && ats->enabled) {
9541 _airporttile_mngr.SetEntitySpec(ats.get());
9547 /* Here we perform initial decoding of some special sprites (as are they
9548 * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9549 * partial implementation yet).
9550 * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9551 * a crafted invalid GRF file. We should tell that to the user somehow, or
9552 * better make this more robust in the future. */
9553 static void DecodeSpecialSprite(uint8_t *buf, uint num, GrfLoadingStage stage)
9555 /* XXX: There is a difference between staged loading in TTDPatch and
9556 * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9557 * during stage 1, whilst action 3 is carried out during stage 2 (to
9558 * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9559 * IDs are valid only within a given set (action 1) block, and may be
9560 * overwritten after action 3 associates them. But overwriting happens
9561 * in an earlier stage than associating, so... We just process actions
9562 * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9563 * --pasky
9564 * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9565 * is not in memory and scanning the file every time would be too expensive.
9566 * In other stages we skip action 0x10 since it's already dealt with. */
9567 static const SpecialSpriteHandler handlers[][GLS_END] = {
9568 /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9569 /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9570 /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9571 /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9572 /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9573 /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9574 /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9575 /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9576 /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9577 /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9578 /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9579 /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9580 /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9581 /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9582 /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9583 /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9584 /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9585 /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9586 /* 0x12 */ { SkipAct12, SkipAct12, SkipAct12, SkipAct12, SkipAct12, LoadFontGlyph, },
9587 /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9588 /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9591 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9593 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9594 if (it == _grf_line_to_action6_sprite_override.end()) {
9595 /* No preloaded sprite to work with; read the
9596 * pseudo sprite content. */
9597 _cur.file->ReadBlock(buf, num);
9598 } else {
9599 /* Use the preloaded sprite data. */
9600 buf = _grf_line_to_action6_sprite_override[location].data();
9601 GrfMsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9603 /* Skip the real (original) content of this action. */
9604 _cur.file->SeekTo(num, SEEK_CUR);
9607 ByteReader br(buf, buf + num);
9609 try {
9610 uint8_t action = br.ReadByte();
9612 if (action == 0xFF) {
9613 GrfMsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9614 } else if (action == 0xFE) {
9615 GrfMsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9616 } else if (action >= lengthof(handlers)) {
9617 GrfMsg(7, "DecodeSpecialSprite: Skipping unknown action 0x{:02X}", action);
9618 } else if (handlers[action][stage] == nullptr) {
9619 GrfMsg(7, "DecodeSpecialSprite: Skipping action 0x{:02X} in stage {}", action, stage);
9620 } else {
9621 GrfMsg(7, "DecodeSpecialSprite: Handling action 0x{:02X} in stage {}", action, stage);
9622 handlers[action][stage](br);
9624 } catch (...) {
9625 GrfMsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9626 DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9631 * Load a particular NewGRF from a SpriteFile.
9632 * @param config The configuration of the to be loaded NewGRF.
9633 * @param stage The loading stage of the NewGRF.
9634 * @param file The file to load the GRF data from.
9636 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9638 _cur.file = &file;
9639 _cur.grfconfig = config;
9641 Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9643 uint8_t grf_container_version = file.GetContainerVersion();
9644 if (grf_container_version == 0) {
9645 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9646 return;
9649 if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9650 /* We need the sprite offsets in the init stage for NewGRF sounds
9651 * and in the activation stage for real sprites. */
9652 ReadGRFSpriteOffsets(file);
9653 } else {
9654 /* Skip sprite section offset if present. */
9655 if (grf_container_version >= 2) file.ReadDword();
9658 if (grf_container_version >= 2) {
9659 /* Read compression value. */
9660 uint8_t compression = file.ReadByte();
9661 if (compression != 0) {
9662 Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9663 return;
9667 /* Skip the first sprite; we don't care about how many sprites this
9668 * does contain; newest TTDPatches and George's longvehicles don't
9669 * neither, apparently. */
9670 uint32_t num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9671 if (num == 4 && file.ReadByte() == 0xFF) {
9672 file.ReadDword();
9673 } else {
9674 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9675 return;
9678 _cur.ClearDataForNextFile();
9680 ReusableBuffer<uint8_t> buf;
9682 while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9683 uint8_t type = file.ReadByte();
9684 _cur.nfo_line++;
9686 if (type == 0xFF) {
9687 if (_cur.skip_sprites == 0) {
9688 DecodeSpecialSprite(buf.Allocate(num), num, stage);
9690 /* Stop all processing if we are to skip the remaining sprites */
9691 if (_cur.skip_sprites == -1) break;
9693 continue;
9694 } else {
9695 file.SkipBytes(num);
9697 } else {
9698 if (_cur.skip_sprites == 0) {
9699 GrfMsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9700 DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9701 break;
9704 if (grf_container_version >= 2 && type == 0xFD) {
9705 /* Reference to data section. Container version >= 2 only. */
9706 file.SkipBytes(num);
9707 } else {
9708 file.SkipBytes(7);
9709 SkipSpriteData(file, type, num - 8);
9713 if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9718 * Load a particular NewGRF.
9719 * @param config The configuration of the to be loaded NewGRF.
9720 * @param stage The loading stage of the NewGRF.
9721 * @param subdir The sub directory to find the NewGRF in.
9722 * @param temporary The NewGRF/sprite file is to be loaded temporarily and should be closed immediately,
9723 * contrary to loading the SpriteFile and having it cached by the SpriteCache.
9725 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9727 const std::string &filename = config->filename;
9729 /* A .grf file is activated only if it was active when the game was
9730 * started. If a game is loaded, only its active .grfs will be
9731 * reactivated, unless "loadallgraphics on" is used. A .grf file is
9732 * considered active if its action 8 has been processed, i.e. its
9733 * action 8 hasn't been skipped using an action 7.
9735 * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9736 * carried out. All others are ignored, because they only need to be
9737 * processed once at initialization. */
9738 if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9739 _cur.grffile = GetFileByFilename(filename);
9740 if (_cur.grffile == nullptr) UserError("File '{}' lost in cache.\n", filename);
9741 if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9742 if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9745 bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9746 if (temporary) {
9747 SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9748 LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9749 } else {
9750 LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9755 * Relocates the old shore sprites at new positions.
9757 * 1. If shore sprites are neither loaded by Action5 nor ActionA, the extra sprites from openttd(w/d).grf are used. (SHORE_REPLACE_ONLY_NEW)
9758 * 2. If a newgrf replaces some shore sprites by ActionA. The (maybe also replaced) grass tiles are used for corner shores. (SHORE_REPLACE_ACTION_A)
9759 * 3. If a newgrf replaces shore sprites by Action5 any shore replacement by ActionA has no effect. (SHORE_REPLACE_ACTION_5)
9761 static void ActivateOldShore()
9763 /* Use default graphics, if no shore sprites were loaded.
9764 * Should not happen, as the base set's extra grf should include some. */
9765 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
9767 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
9768 DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9769 DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9770 DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9771 DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9772 DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9773 DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9774 DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9775 DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9778 if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
9779 DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9780 DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9781 DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9782 DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9783 DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9784 DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9785 DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9786 DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9788 /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9789 * If they would be used somewhen, then these grass tiles will most like not look as needed */
9790 DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9791 DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9796 * Replocate the old tram depot sprites to the new position, if no new ones were loaded.
9798 static void ActivateOldTramDepot()
9800 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK) {
9801 DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9802 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9803 DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9804 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9805 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9806 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9811 * Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them
9813 static void FinalisePriceBaseMultipliers()
9815 extern const PriceBaseSpec _price_base_specs[];
9816 /** Features, to which '_grf_id_overrides' applies. Currently vehicle features only. */
9817 static const uint32_t override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9819 /* Evaluate grf overrides */
9820 int num_grfs = (uint)_grf_files.size();
9821 std::vector<int> grf_overrides(num_grfs, -1);
9822 for (int i = 0; i < num_grfs; i++) {
9823 GRFFile *source = _grf_files[i];
9824 auto it = _grf_id_overrides.find(source->grfid);
9825 if (it == std::end(_grf_id_overrides)) continue;
9826 uint32_t override = it->second;
9828 GRFFile *dest = GetFileByGRFID(override);
9829 if (dest == nullptr) continue;
9831 grf_overrides[i] = find_index(_grf_files, dest);
9832 assert(grf_overrides[i] >= 0);
9835 /* Override features and price base multipliers of earlier loaded grfs */
9836 for (int i = 0; i < num_grfs; i++) {
9837 if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9838 GRFFile *source = _grf_files[i];
9839 GRFFile *dest = _grf_files[grf_overrides[i]];
9841 uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9842 source->grf_features |= features;
9843 dest->grf_features |= features;
9845 for (Price p = PR_BEGIN; p < PR_END; p++) {
9846 /* No price defined -> nothing to do */
9847 if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9848 Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9849 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9853 /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9854 for (int i = num_grfs - 1; i >= 0; i--) {
9855 if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9856 GRFFile *source = _grf_files[i];
9857 GRFFile *dest = _grf_files[grf_overrides[i]];
9859 uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9860 source->grf_features |= features;
9861 dest->grf_features |= features;
9863 for (Price p = PR_BEGIN; p < PR_END; p++) {
9864 /* Already a price defined -> nothing to do */
9865 if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9866 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9867 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9871 /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9872 for (int i = 0; i < num_grfs; i++) {
9873 if (grf_overrides[i] < 0) continue;
9874 GRFFile *source = _grf_files[i];
9875 GRFFile *dest = _grf_files[grf_overrides[i]];
9877 uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9878 source->grf_features |= features;
9879 dest->grf_features |= features;
9881 for (Price p = PR_BEGIN; p < PR_END; p++) {
9882 if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9883 if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9884 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9886 source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9890 /* Apply fallback prices for grf version < 8 */
9891 for (GRFFile * const file : _grf_files) {
9892 if (file->grf_version >= 8) continue;
9893 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9894 for (Price p = PR_BEGIN; p < PR_END; p++) {
9895 Price fallback_price = _price_base_specs[p].fallback_price;
9896 if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9897 /* No price multiplier has been set.
9898 * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9899 price_base_multipliers[p] = price_base_multipliers[fallback_price];
9904 /* Decide local/global scope of price base multipliers */
9905 for (GRFFile * const file : _grf_files) {
9906 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9907 for (Price p = PR_BEGIN; p < PR_END; p++) {
9908 if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9909 /* No multiplier was set; set it to a neutral value */
9910 price_base_multipliers[p] = 0;
9911 } else {
9912 if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9913 /* The grf does not define any objects of the feature,
9914 * so it must be a difficulty setting. Apply it globally */
9915 Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9916 SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9917 price_base_multipliers[p] = 0;
9918 } else {
9919 Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9926 extern void InitGRFTownGeneratorNames();
9928 /** Finish loading NewGRFs and execute needed post-processing */
9929 static void AfterLoadGRFs()
9931 for (StringIDMapping &it : _string_to_grf_mapping) {
9932 it.func(MapGRFStringID(it.grfid, it.source));
9934 _string_to_grf_mapping.clear();
9936 /* Clear the action 6 override sprites. */
9937 _grf_line_to_action6_sprite_override.clear();
9939 /* Polish cargoes */
9940 FinaliseCargoArray();
9942 /* Pre-calculate all refit masks after loading GRF files. */
9943 CalculateRefitMasks();
9945 /* Polish engines */
9946 FinaliseEngineArray();
9948 /* Set the actually used Canal properties */
9949 FinaliseCanals();
9951 /* Add all new houses to the house array. */
9952 FinaliseHouseArray();
9954 /* Add all new industries to the industry array. */
9955 FinaliseIndustriesArray();
9957 /* Add all new objects to the object array. */
9958 FinaliseObjectsArray();
9960 InitializeSortedCargoSpecs();
9962 /* Sort the list of industry types. */
9963 SortIndustryTypes();
9965 /* Create dynamic list of industry legends for smallmap_gui.cpp */
9966 BuildIndustriesLegend();
9968 /* Build the routemap legend, based on the available cargos */
9969 BuildLinkStatsLegend();
9971 /* Add all new airports to the airports array. */
9972 FinaliseAirportsArray();
9973 BindAirportSpecs();
9975 /* Update the townname generators list */
9976 InitGRFTownGeneratorNames();
9978 /* Run all queued vehicle list order changes */
9979 CommitVehicleListOrderChanges();
9981 /* Load old shore sprites in new position, if they were replaced by ActionA */
9982 ActivateOldShore();
9984 /* Load old tram depot sprites in new position, if no new ones are present */
9985 ActivateOldTramDepot();
9987 /* Set up custom rail types */
9988 InitRailTypes();
9989 InitRoadTypes();
9991 for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9992 if (_gted[e->index].rv_max_speed != 0) {
9993 /* Set RV maximum speed from the mph/0.8 unit value */
9994 e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9997 RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9999 const GRFFile *file = e->GetGRF();
10000 if (file == nullptr || _gted[e->index].roadtramtype == 0) {
10001 e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
10002 continue;
10005 /* Remove +1 offset. */
10006 _gted[e->index].roadtramtype--;
10008 const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
10009 if (_gted[e->index].roadtramtype < list->size())
10011 RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
10012 RoadType rt = GetRoadTypeByLabel(rtl);
10013 if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
10014 e->u.road.roadtype = rt;
10015 continue;
10019 /* Road type is not available, so disable this engine */
10020 e->info.climates = 0;
10023 for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
10024 RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
10025 if (railtype == INVALID_RAILTYPE) {
10026 /* Rail type is not available, so disable this engine */
10027 e->info.climates = 0;
10028 } else {
10029 e->u.rail.railtype = railtype;
10030 e->u.rail.intended_railtype = railtype;
10034 SetYearEngineAgingStops();
10036 FinalisePriceBaseMultipliers();
10038 /* Deallocate temporary loading data */
10039 _gted.clear();
10040 _grm_sprites.clear();
10044 * Load all the NewGRFs.
10045 * @param load_index The offset for the first sprite to add.
10046 * @param num_baseset Number of NewGRFs at the front of the list to look up in the baseset dir instead of the newgrf dir.
10048 void LoadNewGRF(uint load_index, uint num_baseset)
10050 /* In case of networking we need to "sync" the start values
10051 * so all NewGRFs are loaded equally. For this we use the
10052 * start date of the game and we set the counters, etc. to
10053 * 0 so they're the same too. */
10054 TimerGameCalendar::Date date = TimerGameCalendar::date;
10055 TimerGameCalendar::Year year = TimerGameCalendar::year;
10056 TimerGameCalendar::DateFract date_fract = TimerGameCalendar::date_fract;
10058 TimerGameEconomy::Date economy_date = TimerGameEconomy::date;
10059 TimerGameEconomy::Year economy_year = TimerGameEconomy::year;
10060 TimerGameEconomy::DateFract economy_date_fract = TimerGameEconomy::date_fract;
10062 uint64_t tick_counter = TimerGameTick::counter;
10063 uint8_t display_opt = _display_opt;
10065 if (_networking) {
10066 TimerGameCalendar::year = _settings_game.game_creation.starting_year;
10067 TimerGameCalendar::date = TimerGameCalendar::ConvertYMDToDate(TimerGameCalendar::year, 0, 1);
10068 TimerGameCalendar::date_fract = 0;
10070 TimerGameEconomy::year = _settings_game.game_creation.starting_year.base();
10071 TimerGameEconomy::date = TimerGameEconomy::ConvertYMDToDate(TimerGameEconomy::year, 0, 1);
10072 TimerGameEconomy::date_fract = 0;
10074 TimerGameTick::counter = 0;
10075 _display_opt = 0;
10078 InitializeGRFSpecial();
10080 ResetNewGRFData();
10083 * Reset the status of all files, so we can 'retry' to load them.
10084 * This is needed when one for example rearranges the NewGRFs in-game
10085 * and a previously disabled NewGRF becomes usable. If it would not
10086 * be reset, the NewGRF would remain disabled even though it should
10087 * have been enabled.
10089 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10090 if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
10093 _cur.spriteid = load_index;
10095 /* Load newgrf sprites
10096 * in each loading stage, (try to) open each file specified in the config
10097 * and load information from it. */
10098 for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
10099 /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
10100 * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
10101 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10102 if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
10105 if (stage == GLS_RESERVE) {
10106 static const std::pair<uint32_t, uint32_t> default_grf_overrides[] = {
10107 { BSWAP32(0x44442202), BSWAP32(0x44440111) }, // UKRS addons modifies UKRS
10108 { BSWAP32(0x6D620402), BSWAP32(0x6D620401) }, // DBSetXL ECS extension modifies DBSetXL
10109 { BSWAP32(0x4D656f20), BSWAP32(0x4D656F17) }, // LV4cut modifies LV4
10111 for (const auto &grf_override : default_grf_overrides) {
10112 SetNewGRFOverride(grf_override.first, grf_override.second);
10116 uint num_grfs = 0;
10117 uint num_non_static = 0;
10119 _cur.stage = stage;
10120 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10121 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
10122 if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
10124 Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
10125 if (!FioCheckFileExists(c->filename, subdir)) {
10126 Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
10127 c->status = GCS_NOT_FOUND;
10128 continue;
10131 if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
10133 if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
10134 if (num_non_static == NETWORK_MAX_GRF_COUNT) {
10135 Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
10136 c->status = GCS_DISABLED;
10137 c->error = {STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED};
10138 continue;
10140 num_non_static++;
10143 num_grfs++;
10145 LoadNewGRFFile(c, stage, subdir, false);
10146 if (stage == GLS_RESERVE) {
10147 SetBit(c->flags, GCF_RESERVED);
10148 } else if (stage == GLS_ACTIVATION) {
10149 ClrBit(c->flags, GCF_RESERVED);
10150 assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
10151 ClearTemporaryNewGRFData(_cur.grffile);
10152 BuildCargoTranslationMap();
10153 Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
10154 } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
10155 /* We're not going to activate this, so free whatever data we allocated */
10156 ClearTemporaryNewGRFData(_cur.grffile);
10161 /* Pseudo sprite processing is finished; free temporary stuff */
10162 _cur.ClearDataForNextFile();
10164 /* Call any functions that should be run after GRFs have been loaded. */
10165 AfterLoadGRFs();
10167 /* Now revert back to the original situation */
10168 TimerGameCalendar::year = year;
10169 TimerGameCalendar::date = date;
10170 TimerGameCalendar::date_fract = date_fract;
10172 TimerGameEconomy::year = economy_year;
10173 TimerGameEconomy::date = economy_date;
10174 TimerGameEconomy::date_fract = economy_date_fract;
10176 TimerGameTick::counter = tick_counter;
10177 _display_opt = display_opt;