OpenTTD Source: src/newgrf.cpp Source File

OpenTTD Source 14.0-beta1

newgrf.cpp
Go to the documentation of this file.
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 */
7
10 #include "stdafx.h"
11
12 #include "core/container_func.hpp"
13 #include "debug.h"
14 #include "fileio_func.h"
15 #include "engine_func.h"
16 #include "engine_base.h"
17 #include "bridge.h"
18 #include "town.h"
19 #include "newgrf_engine.h"
20 #include "newgrf_text.h"
21 #include "fontcache.h"
22 #include "currency.h"
23 #include "landscape.h"
24 #include "newgrf_cargo.h"
25 #include "newgrf_house.h"
26 #include "newgrf_sound.h"
27 #include "newgrf_station.h"
28 #include "industrytype.h"
29 #include "industry_map.h"
30 #include "newgrf_canal.h"
31 #include "newgrf_townname.h"
32 #include "newgrf_industries.h"
33 #include "newgrf_airporttiles.h"
34 #include "newgrf_airport.h"
35 #include "newgrf_object.h"
36 #include "rev.h"
37 #include "fios.h"
38 #include "strings_func.h"
39 #include "timer/timer_game_tick.h"
40 #include "timer/timer_game_calendar.h"
41 #include "string_func.h"
42 #include "network/core/config.h"
43 #include "smallmap_gui.h"
44 #include "genworld.h"
45 #include "error.h"
46 #include "error_func.h"
47 #include "vehicle_func.h"
48 #include "language.h"
49 #include "vehicle_base.h"
50 #include "road.h"
51 #include "newgrf_roadstop.h"
52
53 #include "table/strings.h"
54 #include "table/build_industry.h"
55
56 #include "safeguards.h"
57
58 /* TTDPatch extended GRF format codec
59 * (c) Petr Baudis 2004 (GPL'd)
60 * Changes by Florian octo Forster are (c) by the OpenTTD development team.
61 *
62 * Contains portions of documentation by TTDPatch team.
63 * Thanks especially to Josef Drexler for the documentation as well as a lot
64 * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
65 * served as subject to the initial testing of this codec. */
66
68 static std::vector<GRFFile *> _grf_files;
69
70 const std::vector<GRFFile *> &GetAllGRFFiles()
71 {
72 return _grf_files;
73 }
74
76 byte _misc_grf_features = 0;
77
79 static uint32_t _ttdpatch_flags[8];
80
82 GRFLoadedFeatures _loaded_newgrf_features;
83
84 static const uint MAX_SPRITEGROUP = UINT8_MAX;
85
87 struct GrfProcessingState {
88 private:
90 struct SpriteSet {
91 SpriteID sprite;
92 uint num_sprites;
93 };
94
96 std::map<uint, SpriteSet> spritesets[GSF_END];
97
98 public:
99 /* Global state */
100 GrfLoadingStage stage;
101 SpriteID spriteid;
102
103 /* Local state in the file */
104 SpriteFile *file;
105 GRFFile *grffile;
106 GRFConfig *grfconfig;
107 uint32_t nfo_line;
108
109 /* Kind of return values when processing certain actions */
110 int skip_sprites;
111
112 /* Currently referenceable spritegroups */
113 const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
114
116 void ClearDataForNextFile()
117 {
118 this->nfo_line = 0;
119 this->skip_sprites = 0;
120
121 for (uint i = 0; i < GSF_END; i++) {
122 this->spritesets[i].clear();
123 }
124
125 memset(this->spritegroups, 0, sizeof(this->spritegroups));
126 }
127
136 void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
137 {
138 assert(feature < GSF_END);
139 for (uint i = 0; i < numsets; i++) {
140 SpriteSet &set = this->spritesets[feature][first_set + i];
141 set.sprite = first_sprite + i * numents;
142 set.num_sprites = numents;
143 }
144 }
145
152 bool HasValidSpriteSets(byte feature) const
153 {
154 assert(feature < GSF_END);
155 return !this->spritesets[feature].empty();
156 }
157
165 bool IsValidSpriteSet(byte feature, uint set) const
166 {
167 assert(feature < GSF_END);
168 return this->spritesets[feature].find(set) != this->spritesets[feature].end();
169 }
170
177 SpriteID GetSprite(byte feature, uint set) const
178 {
179 assert(IsValidSpriteSet(feature, set));
180 return this->spritesets[feature].find(set)->second.sprite;
181 }
182
189 uint GetNumEnts(byte feature, uint set) const
190 {
191 assert(IsValidSpriteSet(feature, set));
192 return this->spritesets[feature].find(set)->second.num_sprites;
193 }
194 };
195
196 static GrfProcessingState _cur;
197
198
205 template <VehicleType T>
206 static inline bool IsValidNewGRFImageIndex(uint8_t image_index)
207 {
208 return image_index == 0xFD || IsValidImageIndex<T>(image_index);
209 }
210
211 class OTTDByteReaderSignal { };
212
214 class ByteReader {
215 protected:
216 byte *data;
217 byte *end;
218
219 public:
220 ByteReader(byte *data, byte *end) : data(data), end(end) { }
221
222 inline byte *ReadBytes(size_t size)
223 {
224 if (data + size >= end) {
225 /* Put data at the end, as would happen if every byte had been individually read. */
226 data = end;
227 throw OTTDByteReaderSignal();
228 }
229
230 byte *ret = data;
231 data += size;
232 return ret;
233 }
234
235 inline byte ReadByte()
236 {
237 if (data < end) return *(data)++;
238 throw OTTDByteReaderSignal();
239 }
240
241 uint16_t ReadWord()
242 {
243 uint16_t val = ReadByte();
244 return val | (ReadByte() << 8);
245 }
246
247 uint16_t ReadExtendedByte()
248 {
249 uint16_t val = ReadByte();
250 return val == 0xFF ? ReadWord() : val;
251 }
252
253 uint32_t ReadDWord()
254 {
255 uint32_t val = ReadWord();
256 return val | (ReadWord() << 16);
257 }
258
259 uint32_t ReadVarSize(byte size)
260 {
261 switch (size) {
262 case 1: return ReadByte();
263 case 2: return ReadWord();
264 case 4: return ReadDWord();
265 default:
266 NOT_REACHED();
267 return 0;
268 }
269 }
270
271 const char *ReadString()
272 {
273 char *string = reinterpret_cast<char *>(data);
274 size_t string_length = ttd_strnlen(string, Remaining());
275
276 if (string_length == Remaining()) {
277 /* String was not NUL terminated, so make sure it is now. */
278 string[string_length - 1] = '\0';
279 GrfMsg(7, "String was not terminated with a zero byte.");
280 } else {
281 /* Increase the string length to include the NUL byte. */
282 string_length++;
283 }
284 Skip(string_length);
285
286 return string;
287 }
288
289 inline size_t Remaining() const
290 {
291 return end - data;
292 }
293
294 inline bool HasData(size_t count = 1) const
295 {
296 return data + count <= end;
297 }
298
299 inline byte *Data()
300 {
301 return data;
302 }
303
304 inline void Skip(size_t len)
305 {
306 data += len;
307 /* It is valid to move the buffer to exactly the end of the data,
308 * as there may not be any more data read. */
309 if (data > end) throw OTTDByteReaderSignal();
310 }
311 };
312
313 typedef void (*SpecialSpriteHandler)(ByteReader *buf);
314
316 static const uint NUM_STATIONS_PER_GRF = UINT16_MAX - 1;
317
319 struct GRFTempEngineData {
321 enum Refittability {
322 UNSET = 0,
323 EMPTY,
324 NONEMPTY,
325 };
326
327 uint16_t cargo_allowed;
328 uint16_t cargo_disallowed;
329 RailTypeLabel railtypelabel;
330 uint8_t roadtramtype;
331 const GRFFile *defaultcargo_grf;
332 Refittability refittability;
333 uint8_t rv_max_speed;
334 CargoTypes ctt_include_mask;
335 CargoTypes ctt_exclude_mask;
336
341 void UpdateRefittability(bool non_empty)
342 {
343 if (non_empty) {
344 this->refittability = NONEMPTY;
345 } else if (this->refittability == UNSET) {
346 this->refittability = EMPTY;
347 }
348 }
349 };
350
351 static std::vector<GRFTempEngineData> _gted;
352
357 static uint32_t _grm_engines[256];
358
360 static uint32_t _grm_cargoes[NUM_CARGO * 2];
361
362 struct GRFLocation {
363 uint32_t grfid;
364 uint32_t nfoline;
365
366 GRFLocation(uint32_t grfid, uint32_t nfoline) : grfid(grfid), nfoline(nfoline) { }
367
368 bool operator<(const GRFLocation &other) const
369 {
370 return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
371 }
372
373 bool operator == (const GRFLocation &other) const
374 {
375 return this->grfid == other.grfid && this->nfoline == other.nfoline;
376 }
377 };
378
379 static std::map<GRFLocation, SpriteID> _grm_sprites;
380 typedef std::map<GRFLocation, std::vector<byte>> GRFLineToSpriteOverride;
381 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
382
393 void GrfMsgI(int severity, const std::string &msg)
394 {
395 Debug(grf, severity, "[{}:{}] {}", _cur.grfconfig->filename, _cur.nfo_line, msg);
396 }
397
403 static GRFFile *GetFileByGRFID(uint32_t grfid)
404 {
405 for (GRFFile * const file : _grf_files) {
406 if (file->grfid == grfid) return file;
407 }
408 return nullptr;
409 }
410
416 static GRFFile *GetFileByFilename(const std::string &filename)
417 {
418 for (GRFFile * const file : _grf_files) {
419 if (file->filename == filename) return file;
420 }
421 return nullptr;
422 }
423
425 static void ClearTemporaryNewGRFData(GRFFile *gf)
426 {
427 gf->labels.clear();
428 }
429
436 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
437 {
438 GRFFile *file;
439 if (config != nullptr) {
440 file = GetFileByGRFID(config->ident.grfid);
441 } else {
442 config = _cur.grfconfig;
443 file = _cur.grffile;
444 }
445
446 config->status = GCS_DISABLED;
447 if (file != nullptr) ClearTemporaryNewGRFData(file);
448 if (config == _cur.grfconfig) _cur.skip_sprites = -1;
449
450 if (message == STR_NULL) return nullptr;
451
452 config->error = {STR_NEWGRF_ERROR_MSG_FATAL, message};
453 if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
454 return &config->error.value();
455 }
456
460 struct StringIDMapping {
461 uint32_t grfid;
462 StringID source;
463 StringID *target;
464 };
465 typedef std::vector<StringIDMapping> StringIDMappingVector;
466 static StringIDMappingVector _string_to_grf_mapping;
467
473 static void AddStringForMapping(StringID source, StringID *target)
474 {
475 *target = STR_UNDEFINED;
476 _string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
477 }
478
486 static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
487 {
488 /* StringID table for TextIDs 0x4E->0x6D */
489 static const StringID units_volume[] = {
490 STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
491 STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
492 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
493 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
494 STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
495 STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
496 STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
497 STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
498 };
499
500 /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
501 assert(!IsInsideMM(str, 0xD000, 0xD7FF));
502
503 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
504 static_assert(stringend - stringid == end - begin); \
505 if (str >= begin && str <= end) return str + (stringid - begin)
506
507 /* We have some changes in our cargo strings, resulting in some missing. */
508 TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
509 TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
510 if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
511 TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
512 TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
513 TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
514
515 /* Map building names according to our lang file changes. There are several
516 * ranges of house ids, all of which need to be remapped to allow newgrfs
517 * to use original house names. */
518 TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
519 TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
520 TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
521
522 /* Same thing for industries */
523 TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
524 TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
525 TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
526 TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
527 TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
528
529 switch (str) {
530 case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
531 case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
532 case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
533 }
534 #undef TEXTID_TO_STRINGID
535
536 if (str == STR_NULL) return STR_EMPTY;
537
538 Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
539
540 return STR_EMPTY;
541 }
542
550 StringID MapGRFStringID(uint32_t grfid, StringID str)
551 {
552 if (IsInsideMM(str, 0xD800, 0x10000)) {
553 /* General text provided by NewGRF.
554 * In the specs this is called the 0xDCxx range (misc persistent texts),
555 * but we meanwhile extended the range to 0xD800-0xFFFF.
556 * Note: We are not involved in the "persistent" business, since we do not store
557 * any NewGRF strings in savegames. */
558 return GetGRFStringID(grfid, str);
559 } else if (IsInsideMM(str, 0xD000, 0xD800)) {
560 /* Callback text provided by NewGRF.
561 * In the specs this is called the 0xD0xx range (misc graphics texts).
562 * These texts can be returned by various callbacks.
563 *
564 * Due to how TTDP implements the GRF-local- to global-textid translation
565 * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
566 * We do not care about that difference and just mask out the 0x400 bit.
567 */
568 str &= ~0x400;
569 return GetGRFStringID(grfid, str);
570 } else {
571 /* The NewGRF wants to include/reference an original TTD string.
572 * Try our best to find an equivalent one. */
573 return TTDPStringIDToOTTDStringIDMapping(str);
574 }
575 }
576
577 static std::map<uint32_t, uint32_t> _grf_id_overrides;
578
584 static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
585 {
586 _grf_id_overrides[source_grfid] = target_grfid;
587 GrfMsg(5, "SetNewGRFOverride: Added override of 0x{:X} to 0x{:X}", BSWAP32(source_grfid), BSWAP32(target_grfid));
588 }
589
598 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access = false)
599 {
600 /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
601 * them use the same engine slots. */
602 uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
603 if (_settings_game.vehicle.dynamic_engines) {
604 /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
605 scope_grfid = file->grfid;
606 uint32_t override = _grf_id_overrides[file->grfid];
607 if (override != 0) {
608 scope_grfid = override;
609 const GRFFile *grf_match = GetFileByGRFID(override);
610 if (grf_match == nullptr) {
611 GrfMsg(5, "Tried mapping from GRFID {:x} to {:x} but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
612 } else {
613 GrfMsg(5, "Mapping from GRFID {:x} to {:x}", BSWAP32(file->grfid), BSWAP32(override));
614 }
615 }
616
617 /* Check if the engine is registered in the override manager */
618 EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
619 if (engine != INVALID_ENGINE) {
620 Engine *e = Engine::Get(engine);
621 if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
622 return e;
623 }
624 }
625
626 /* Check if there is an unreserved slot */
627 EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
628 if (engine != INVALID_ENGINE) {
629 Engine *e = Engine::Get(engine);
630
631 if (e->grf_prop.grffile == nullptr) {
632 e->grf_prop.grffile = file;
633 GrfMsg(5, "Replaced engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
634 }
635
636 /* Reserve the engine slot */
637 if (!static_access) {
638 EngineIDMapping *eid = _engine_mngr.data() + engine;
639 eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
640 }
641
642 return e;
643 }
644
645 if (static_access) return nullptr;
646
647 if (!Engine::CanAllocateItem()) {
648 GrfMsg(0, "Can't allocate any more engines");
649 return nullptr;
650 }
651
652 size_t engine_pool_size = Engine::GetPoolSize();
653
654 /* ... it's not, so create a new one based off an existing engine */
655 Engine *e = new Engine(type, internal_id);
656 e->grf_prop.grffile = file;
657
658 /* Reserve the engine slot */
659 assert(_engine_mngr.size() == e->index);
660 _engine_mngr.push_back({
661 scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
662 internal_id,
663 type,
664 std::min<uint8_t>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
665 });
666
667 if (engine_pool_size != Engine::GetPoolSize()) {
668 /* Resize temporary engine data ... */
669 _gted.resize(Engine::GetPoolSize());
670 }
671 if (type == VEH_TRAIN) {
672 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
673 }
674
675 GrfMsg(5, "Created new engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
676
677 return e;
678 }
679
690 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
691 {
692 uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
693 if (_settings_game.vehicle.dynamic_engines) {
694 scope_grfid = file->grfid;
695 uint32_t override = _grf_id_overrides[file->grfid];
696 if (override != 0) scope_grfid = override;
697 }
698
699 return _engine_mngr.GetID(type, internal_id, scope_grfid);
700 }
701
706 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
707 {
708 if (HasBit(grf_sprite->pal, 14)) {
709 ClrBit(grf_sprite->pal, 14);
710 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
711 }
712
713 if (HasBit(grf_sprite->sprite, 14)) {
714 ClrBit(grf_sprite->sprite, 14);
715 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
716 }
717
718 if (HasBit(grf_sprite->sprite, 15)) {
719 ClrBit(grf_sprite->sprite, 15);
720 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
721 }
722 }
723
737 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)
738 {
739 grf_sprite->sprite = buf->ReadWord();
740 grf_sprite->pal = buf->ReadWord();
741 TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
742
743 MapSpriteMappingRecolour(grf_sprite);
744
745 bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
746 ClrBit(grf_sprite->pal, 15);
747 if (custom_sprite) {
748 /* Use sprite from Action 1 */
749 uint index = GB(grf_sprite->sprite, 0, 14);
750 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
751 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {}", index);
752 grf_sprite->sprite = SPR_IMG_QUERY;
753 grf_sprite->pal = PAL_NONE;
754 } else {
755 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
756 if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
757 SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
758 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
759 }
760 } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
761 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
762 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
763 return flags;
764 }
765
766 if (flags & TLF_CUSTOM_PALETTE) {
767 /* Use palette from Action 1 */
768 uint index = GB(grf_sprite->pal, 0, 14);
769 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
770 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {} for 'palette'", index);
771 grf_sprite->pal = PAL_NONE;
772 } else {
773 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
774 if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
775 SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
776 SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
777 }
778 } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
779 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
780 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
781 return flags;
782 }
783
784 return flags;
785 }
786
795 static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
796 {
797 if (!(flags & TLF_DRAWING_FLAGS)) return;
798
799 if (dts->registers == nullptr) dts->AllocateRegisters();
800 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
801 regs.flags = flags & TLF_DRAWING_FLAGS;
802
803 if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
804 if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
805 if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
806
807 if (is_parent) {
808 if (flags & TLF_BB_XY_OFFSET) {
809 regs.delta.parent[0] = buf->ReadByte();
810 regs.delta.parent[1] = buf->ReadByte();
811 }
812 if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
813 } else {
814 if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
815 if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
816 }
817
818 if (flags & TLF_SPRITE_VAR10) {
819 regs.sprite_var10 = buf->ReadByte();
820 if (regs.sprite_var10 > TLR_MAX_VAR10) {
821 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.sprite_var10, TLR_MAX_VAR10);
822 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
823 return;
824 }
825 }
826
827 if (flags & TLF_PALETTE_VAR10) {
828 regs.palette_var10 = buf->ReadByte();
829 if (regs.palette_var10 > TLR_MAX_VAR10) {
830 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.palette_var10, TLR_MAX_VAR10);
831 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
832 return;
833 }
834 }
835 }
836
848 static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
849 {
850 bool has_flags = HasBit(num_building_sprites, 6);
851 ClrBit(num_building_sprites, 6);
852 TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
853 if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
854 dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
855
856 std::vector<uint16_t> max_sprite_offset(num_building_sprites + 1, 0);
857 std::vector<uint16_t> max_palette_offset(num_building_sprites + 1, 0);
858
859 /* Groundsprite */
860 TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset.data(), max_palette_offset.data());
861 if (_cur.skip_sprites < 0) return true;
862
863 if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
864 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x{:X} for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
865 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
866 return true;
867 }
868
869 ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
870 if (_cur.skip_sprites < 0) return true;
871
872 for (uint i = 0; i < num_building_sprites; i++) {
873 DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
874
875 flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset.data() + i + 1, max_palette_offset.data() + i + 1);
876 if (_cur.skip_sprites < 0) return true;
877
878 if (flags & ~valid_flags) {
879 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x{:X}", flags & ~valid_flags);
880 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
881 return true;
882 }
883
884 seq->delta_x = buf->ReadByte();
885 seq->delta_y = buf->ReadByte();
886
887 if (!no_z_position) seq->delta_z = buf->ReadByte();
888
889 if (seq->IsParentSprite()) {
890 seq->size_x = buf->ReadByte();
891 seq->size_y = buf->ReadByte();
892 seq->size_z = buf->ReadByte();
893 }
894
895 ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
896 if (_cur.skip_sprites < 0) return true;
897 }
898
899 /* Check if the number of sprites per spriteset is consistent */
900 bool is_consistent = true;
901 dts->consistent_max_offset = 0;
902 for (uint i = 0; i < num_building_sprites + 1; i++) {
903 if (max_sprite_offset[i] > 0) {
904 if (dts->consistent_max_offset == 0) {
905 dts->consistent_max_offset = max_sprite_offset[i];
906 } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
907 is_consistent = false;
908 break;
909 }
910 }
911 if (max_palette_offset[i] > 0) {
912 if (dts->consistent_max_offset == 0) {
913 dts->consistent_max_offset = max_palette_offset[i];
914 } else if (dts->consistent_max_offset != max_palette_offset[i]) {
915 is_consistent = false;
916 break;
917 }
918 }
919 }
920
921 /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
922 assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
923
924 if (!is_consistent || dts->registers != nullptr) {
925 dts->consistent_max_offset = 0;
926 if (dts->registers == nullptr) dts->AllocateRegisters();
927
928 for (uint i = 0; i < num_building_sprites + 1; i++) {
929 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
930 regs.max_sprite_offset = max_sprite_offset[i];
931 regs.max_palette_offset = max_palette_offset[i];
932 }
933 }
934
935 return false;
936 }
937
941 static CargoTypes TranslateRefitMask(uint32_t refit_mask)
942 {
943 CargoTypes result = 0;
944 for (uint8_t bit : SetBitIterator(refit_mask)) {
945 CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
946 if (IsValidCargoID(cargo)) SetBit(result, cargo);
947 }
948 return result;
949 }
950
958 static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
959 {
960 /* Special value for 'none' */
961 if (base_pointer == 0) {
962 *index = INVALID_PRICE;
963 return;
964 }
965
966 static const uint32_t start = 0x4B34;
967 static const uint32_t size = 6;
968
969 if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
970 GrfMsg(1, "{}: Unsupported running cost base 0x{:04X}, ignoring", error_location, base_pointer);
971 return;
972 }
973
974 *index = (Price)((base_pointer - start) / size);
975 }
976
978 enum ChangeInfoResult {
979 CIR_SUCCESS,
980 CIR_DISABLED,
981 CIR_UNHANDLED,
982 CIR_UNKNOWN,
983 CIR_INVALID_ID,
984 };
985
986 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader *buf);
987
995 static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
996 {
997 switch (prop) {
998 case 0x00: // Introduction date
999 ei->base_intro = buf->ReadWord() + CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1000 break;
1001
1002 case 0x02: // Decay speed
1003 ei->decay_speed = buf->ReadByte();
1004 break;
1005
1006 case 0x03: // Vehicle life
1007 ei->lifelength = buf->ReadByte();
1008 break;
1009
1010 case 0x04: // Model life
1011 ei->base_life = buf->ReadByte();
1012 break;
1013
1014 case 0x06: // Climates available
1015 ei->climates = buf->ReadByte();
1016 break;
1017
1018 case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1019 /* Amount of cargo loaded during a vehicle's "loading tick" */
1020 ei->load_amount = buf->ReadByte();
1021 break;
1022
1023 default:
1024 return CIR_UNKNOWN;
1025 }
1026
1027 return CIR_SUCCESS;
1028 }
1029
1038 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1039 {
1040 ChangeInfoResult ret = CIR_SUCCESS;
1041
1042 for (int i = 0; i < numinfo; i++) {
1043 Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1044 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1045
1046 EngineInfo *ei = &e->info;
1047 RailVehicleInfo *rvi = &e->u.rail;
1048
1049 switch (prop) {
1050 case 0x05: { // Track type
1051 uint8_t tracktype = buf->ReadByte();
1052
1053 if (tracktype < _cur.grffile->railtype_list.size()) {
1054 _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1055 break;
1056 }
1057
1058 switch (tracktype) {
1059 case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_LABEL_ELECTRIC : RAILTYPE_LABEL_RAIL; break;
1060 case 1: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MONO; break;
1061 case 2: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MAGLEV; break;
1062 default:
1063 GrfMsg(1, "RailVehicleChangeInfo: Invalid track type {} specified, ignoring", tracktype);
1064 break;
1065 }
1066 break;
1067 }
1068
1069 case 0x08: // AI passenger service
1070 /* Tells the AI that this engine is designed for
1071 * passenger services and shouldn't be used for freight. */
1072 rvi->ai_passenger_only = buf->ReadByte();
1073 break;
1074
1075 case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1076 uint16_t speed = buf->ReadWord();
1077 if (speed == 0xFFFF) speed = 0;
1078
1079 rvi->max_speed = speed;
1080 break;
1081 }
1082
1083 case PROP_TRAIN_POWER: // 0x0B Power
1084 rvi->power = buf->ReadWord();
1085
1086 /* Set engine / wagon state based on power */
1087 if (rvi->power != 0) {
1088 if (rvi->railveh_type == RAILVEH_WAGON) {
1089 rvi->railveh_type = RAILVEH_SINGLEHEAD;
1090 }
1091 } else {
1092 rvi->railveh_type = RAILVEH_WAGON;
1093 }
1094 break;
1095
1096 case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1097 rvi->running_cost = buf->ReadByte();
1098 break;
1099
1100 case 0x0E: // Running cost base
1101 ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1102 break;
1103
1104 case 0x12: { // Sprite ID
1105 uint8_t spriteid = buf->ReadByte();
1106 uint8_t orig_spriteid = spriteid;
1107
1108 /* TTD sprite IDs point to a location in a 16bit array, but we use it
1109 * as an array index, so we need it to be half the original value. */
1110 if (spriteid < 0xFD) spriteid >>= 1;
1111
1112 if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1113 rvi->image_index = spriteid;
1114 } else {
1115 GrfMsg(1, "RailVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1116 rvi->image_index = 0;
1117 }
1118 break;
1119 }
1120
1121 case 0x13: { // Dual-headed
1122 uint8_t dual = buf->ReadByte();
1123
1124 if (dual != 0) {
1125 rvi->railveh_type = RAILVEH_MULTIHEAD;
1126 } else {
1127 rvi->railveh_type = rvi->power == 0 ?
1128 RAILVEH_WAGON : RAILVEH_SINGLEHEAD;
1129 }
1130 break;
1131 }
1132
1133 case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1134 rvi->capacity = buf->ReadByte();
1135 break;
1136
1137 case 0x15: { // Cargo type
1138 _gted[e->index].defaultcargo_grf = _cur.grffile;
1139 uint8_t ctype = buf->ReadByte();
1140
1141 if (ctype == 0xFF) {
1142 /* 0xFF is specified as 'use first refittable' */
1143 ei->cargo_type = INVALID_CARGO;
1144 } else if (_cur.grffile->grf_version >= 8) {
1145 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1146 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1147 } else if (ctype < NUM_CARGO) {
1148 /* Use untranslated cargo. */
1149 ei->cargo_type = ctype;
1150 } else {
1151 ei->cargo_type = INVALID_CARGO;
1152 GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1153 }
1154 break;
1155 }
1156
1157 case PROP_TRAIN_WEIGHT: // 0x16 Weight
1158 SB(rvi->weight, 0, 8, buf->ReadByte());
1159 break;
1160
1161 case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1162 rvi->cost_factor = buf->ReadByte();
1163 break;
1164
1165 case 0x18: // AI rank
1166 GrfMsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1167 buf->ReadByte();
1168 break;
1169
1170 case 0x19: { // Engine traction type
1171 /* What do the individual numbers mean?
1172 * 0x00 .. 0x07: Steam
1173 * 0x08 .. 0x27: Diesel
1174 * 0x28 .. 0x31: Electric
1175 * 0x32 .. 0x37: Monorail
1176 * 0x38 .. 0x41: Maglev
1177 */
1178 uint8_t traction = buf->ReadByte();
1179 EngineClass engclass;
1180
1181 if (traction <= 0x07) {
1182 engclass = EC_STEAM;
1183 } else if (traction <= 0x27) {
1184 engclass = EC_DIESEL;
1185 } else if (traction <= 0x31) {
1186 engclass = EC_ELECTRIC;
1187 } else if (traction <= 0x37) {
1188 engclass = EC_MONORAIL;
1189 } else if (traction <= 0x41) {
1190 engclass = EC_MAGLEV;
1191 } else {
1192 break;
1193 }
1194
1195 if (_cur.grffile->railtype_list.empty()) {
1196 /* Use traction type to select between normal and electrified
1197 * rail only when no translation list is in place. */
1198 if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_RAIL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_ELECTRIC;
1199 if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_ELECTRIC && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_RAIL;
1200 }
1201
1202 rvi->engclass = engclass;
1203 break;
1204 }
1205
1206 case 0x1A: // Alter purchase list sort order
1207 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1208 break;
1209
1210 case 0x1B: // Powered wagons power bonus
1211 rvi->pow_wag_power = buf->ReadWord();
1212 break;
1213
1214 case 0x1C: // Refit cost
1215 ei->refit_cost = buf->ReadByte();
1216 break;
1217
1218 case 0x1D: { // Refit cargo
1219 uint32_t mask = buf->ReadDWord();
1220 _gted[e->index].UpdateRefittability(mask != 0);
1221 ei->refit_mask = TranslateRefitMask(mask);
1222 _gted[e->index].defaultcargo_grf = _cur.grffile;
1223 break;
1224 }
1225
1226 case 0x1E: // Callback
1227 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1228 break;
1229
1230 case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1231 rvi->tractive_effort = buf->ReadByte();
1232 break;
1233
1234 case 0x20: // Air drag
1235 rvi->air_drag = buf->ReadByte();
1236 break;
1237
1238 case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1239 rvi->shorten_factor = buf->ReadByte();
1240 break;
1241
1242 case 0x22: // Visual effect
1243 rvi->visual_effect = buf->ReadByte();
1244 /* Avoid accidentally setting visual_effect to the default value
1245 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1246 if (rvi->visual_effect == VE_DEFAULT) {
1247 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1248 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1249 }
1250 break;
1251
1252 case 0x23: // Powered wagons weight bonus
1253 rvi->pow_wag_weight = buf->ReadByte();
1254 break;
1255
1256 case 0x24: { // High byte of vehicle weight
1257 byte weight = buf->ReadByte();
1258
1259 if (weight > 4) {
1260 GrfMsg(2, "RailVehicleChangeInfo: Nonsensical weight of {} tons, ignoring", weight << 8);
1261 } else {
1262 SB(rvi->weight, 8, 8, weight);
1263 }
1264 break;
1265 }
1266
1267 case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1268 rvi->user_def_data = buf->ReadByte();
1269 break;
1270
1271 case 0x26: // Retire vehicle early
1272 ei->retire_early = buf->ReadByte();
1273 break;
1274
1275 case 0x27: // Miscellaneous flags
1276 ei->misc_flags = buf->ReadByte();
1277 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1278 break;
1279
1280 case 0x28: // Cargo classes allowed
1281 _gted[e->index].cargo_allowed = buf->ReadWord();
1282 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1283 _gted[e->index].defaultcargo_grf = _cur.grffile;
1284 break;
1285
1286 case 0x29: // Cargo classes disallowed
1287 _gted[e->index].cargo_disallowed = buf->ReadWord();
1288 _gted[e->index].UpdateRefittability(false);
1289 break;
1290
1291 case 0x2A: // Long format introduction date (days since year 0)
1292 ei->base_intro = buf->ReadDWord();
1293 break;
1294
1295 case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1296 ei->cargo_age_period = buf->ReadWord();
1297 break;
1298
1299 case 0x2C: // CTT refit include list
1300 case 0x2D: { // CTT refit exclude list
1301 uint8_t count = buf->ReadByte();
1302 _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1303 if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1304 CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1305 ctt = 0;
1306 while (count--) {
1307 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1308 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1309 }
1310 break;
1311 }
1312
1313 case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1314 rvi->curve_speed_mod = buf->ReadWord();
1315 break;
1316
1317 case 0x2F: // Engine variant
1318 ei->variant_id = buf->ReadWord();
1319 break;
1320
1321 case 0x30: // Extra miscellaneous flags
1322 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1323 break;
1324
1325 case 0x31: // Callback additional mask
1326 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1327 break;
1328
1329 default:
1330 ret = CommonVehicleChangeInfo(ei, prop, buf);
1331 break;
1332 }
1333 }
1334
1335 return ret;
1336 }
1337
1346 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1347 {
1348 ChangeInfoResult ret = CIR_SUCCESS;
1349
1350 for (int i = 0; i < numinfo; i++) {
1351 Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1352 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1353
1354 EngineInfo *ei = &e->info;
1355 RoadVehicleInfo *rvi = &e->u.road;
1356
1357 switch (prop) {
1358 case 0x05: // Road/tram type
1359 /* RoadTypeLabel is looked up later after the engine's road/tram
1360 * flag is set, however 0 means the value has not been set. */
1361 _gted[e->index].roadtramtype = buf->ReadByte() + 1;
1362 break;
1363
1364 case 0x08: // Speed (1 unit is 0.5 kmh)
1365 rvi->max_speed = buf->ReadByte();
1366 break;
1367
1368 case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1369 rvi->running_cost = buf->ReadByte();
1370 break;
1371
1372 case 0x0A: // Running cost base
1373 ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1374 break;
1375
1376 case 0x0E: { // Sprite ID
1377 uint8_t spriteid = buf->ReadByte();
1378 uint8_t orig_spriteid = spriteid;
1379
1380 /* cars have different custom id in the GRF file */
1381 if (spriteid == 0xFF) spriteid = 0xFD;
1382
1383 if (spriteid < 0xFD) spriteid >>= 1;
1384
1385 if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1386 rvi->image_index = spriteid;
1387 } else {
1388 GrfMsg(1, "RoadVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1389 rvi->image_index = 0;
1390 }
1391 break;
1392 }
1393
1394 case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1395 rvi->capacity = buf->ReadByte();
1396 break;
1397
1398 case 0x10: { // Cargo type
1399 _gted[e->index].defaultcargo_grf = _cur.grffile;
1400 uint8_t ctype = buf->ReadByte();
1401
1402 if (ctype == 0xFF) {
1403 /* 0xFF is specified as 'use first refittable' */
1404 ei->cargo_type = INVALID_CARGO;
1405 } else if (_cur.grffile->grf_version >= 8) {
1406 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1407 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1408 } else if (ctype < NUM_CARGO) {
1409 /* Use untranslated cargo. */
1410 ei->cargo_type = ctype;
1411 } else {
1412 ei->cargo_type = INVALID_CARGO;
1413 GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1414 }
1415 break;
1416 }
1417
1418 case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1419 rvi->cost_factor = buf->ReadByte();
1420 break;
1421
1422 case 0x12: // SFX
1423 rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1424 break;
1425
1426 case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1427 rvi->power = buf->ReadByte();
1428 break;
1429
1430 case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1431 rvi->weight = buf->ReadByte();
1432 break;
1433
1434 case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1435 _gted[e->index].rv_max_speed = buf->ReadByte();
1436 break;
1437
1438 case 0x16: { // Cargoes available for refitting
1439 uint32_t mask = buf->ReadDWord();
1440 _gted[e->index].UpdateRefittability(mask != 0);
1441 ei->refit_mask = TranslateRefitMask(mask);
1442 _gted[e->index].defaultcargo_grf = _cur.grffile;
1443 break;
1444 }
1445
1446 case 0x17: // Callback mask
1447 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1448 break;
1449
1450 case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1451 rvi->tractive_effort = buf->ReadByte();
1452 break;
1453
1454 case 0x19: // Air drag
1455 rvi->air_drag = buf->ReadByte();
1456 break;
1457
1458 case 0x1A: // Refit cost
1459 ei->refit_cost = buf->ReadByte();
1460 break;
1461
1462 case 0x1B: // Retire vehicle early
1463 ei->retire_early = buf->ReadByte();
1464 break;
1465
1466 case 0x1C: // Miscellaneous flags
1467 ei->misc_flags = buf->ReadByte();
1468 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1469 break;
1470
1471 case 0x1D: // Cargo classes allowed
1472 _gted[e->index].cargo_allowed = buf->ReadWord();
1473 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1474 _gted[e->index].defaultcargo_grf = _cur.grffile;
1475 break;
1476
1477 case 0x1E: // Cargo classes disallowed
1478 _gted[e->index].cargo_disallowed = buf->ReadWord();
1479 _gted[e->index].UpdateRefittability(false);
1480 break;
1481
1482 case 0x1F: // Long format introduction date (days since year 0)
1483 ei->base_intro = buf->ReadDWord();
1484 break;
1485
1486 case 0x20: // Alter purchase list sort order
1487 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1488 break;
1489
1490 case 0x21: // Visual effect
1491 rvi->visual_effect = buf->ReadByte();
1492 /* Avoid accidentally setting visual_effect to the default value
1493 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1494 if (rvi->visual_effect == VE_DEFAULT) {
1495 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1496 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1497 }
1498 break;
1499
1500 case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1501 ei->cargo_age_period = buf->ReadWord();
1502 break;
1503
1504 case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1505 rvi->shorten_factor = buf->ReadByte();
1506 break;
1507
1508 case 0x24: // CTT refit include list
1509 case 0x25: { // CTT refit exclude list
1510 uint8_t count = buf->ReadByte();
1511 _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1512 if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1513 CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1514 ctt = 0;
1515 while (count--) {
1516 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1517 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1518 }
1519 break;
1520 }
1521
1522 case 0x26: // Engine variant
1523 ei->variant_id = buf->ReadWord();
1524 break;
1525
1526 case 0x27: // Extra miscellaneous flags
1527 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1528 break;
1529
1530 case 0x28: // Callback additional mask
1531 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1532 break;
1533
1534 default:
1535 ret = CommonVehicleChangeInfo(ei, prop, buf);
1536 break;
1537 }
1538 }
1539
1540 return ret;
1541 }
1542
1551 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1552 {
1553 ChangeInfoResult ret = CIR_SUCCESS;
1554
1555 for (int i = 0; i < numinfo; i++) {
1556 Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1557 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1558
1559 EngineInfo *ei = &e->info;
1560 ShipVehicleInfo *svi = &e->u.ship;
1561
1562 switch (prop) {
1563 case 0x08: { // Sprite ID
1564 uint8_t spriteid = buf->ReadByte();
1565 uint8_t orig_spriteid = spriteid;
1566
1567 /* ships have different custom id in the GRF file */
1568 if (spriteid == 0xFF) spriteid = 0xFD;
1569
1570 if (spriteid < 0xFD) spriteid >>= 1;
1571
1572 if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1573 svi->image_index = spriteid;
1574 } else {
1575 GrfMsg(1, "ShipVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1576 svi->image_index = 0;
1577 }
1578 break;
1579 }
1580
1581 case 0x09: // Refittable
1582 svi->old_refittable = (buf->ReadByte() != 0);
1583 break;
1584
1585 case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1586 svi->cost_factor = buf->ReadByte();
1587 break;
1588
1589 case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h). Use 0x23 to achieve higher speeds.
1590 svi->max_speed = buf->ReadByte();
1591 break;
1592
1593 case 0x0C: { // Cargo type
1594 _gted[e->index].defaultcargo_grf = _cur.grffile;
1595 uint8_t ctype = buf->ReadByte();
1596
1597 if (ctype == 0xFF) {
1598 /* 0xFF is specified as 'use first refittable' */
1599 ei->cargo_type = INVALID_CARGO;
1600 } else if (_cur.grffile->grf_version >= 8) {
1601 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1602 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1603 } else if (ctype < NUM_CARGO) {
1604 /* Use untranslated cargo. */
1605 ei->cargo_type = ctype;
1606 } else {
1607 ei->cargo_type = INVALID_CARGO;
1608 GrfMsg(2, "ShipVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1609 }
1610 break;
1611 }
1612
1613 case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1614 svi->capacity = buf->ReadWord();
1615 break;
1616
1617 case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1618 svi->running_cost = buf->ReadByte();
1619 break;
1620
1621 case 0x10: // SFX
1622 svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1623 break;
1624
1625 case 0x11: { // Cargoes available for refitting
1626 uint32_t mask = buf->ReadDWord();
1627 _gted[e->index].UpdateRefittability(mask != 0);
1628 ei->refit_mask = TranslateRefitMask(mask);
1629 _gted[e->index].defaultcargo_grf = _cur.grffile;
1630 break;
1631 }
1632
1633 case 0x12: // Callback mask
1634 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1635 break;
1636
1637 case 0x13: // Refit cost
1638 ei->refit_cost = buf->ReadByte();
1639 break;
1640
1641 case 0x14: // Ocean speed fraction
1642 svi->ocean_speed_frac = buf->ReadByte();
1643 break;
1644
1645 case 0x15: // Canal speed fraction
1646 svi->canal_speed_frac = buf->ReadByte();
1647 break;
1648
1649 case 0x16: // Retire vehicle early
1650 ei->retire_early = buf->ReadByte();
1651 break;
1652
1653 case 0x17: // Miscellaneous flags
1654 ei->misc_flags = buf->ReadByte();
1655 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1656 break;
1657
1658 case 0x18: // Cargo classes allowed
1659 _gted[e->index].cargo_allowed = buf->ReadWord();
1660 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1661 _gted[e->index].defaultcargo_grf = _cur.grffile;
1662 break;
1663
1664 case 0x19: // Cargo classes disallowed
1665 _gted[e->index].cargo_disallowed = buf->ReadWord();
1666 _gted[e->index].UpdateRefittability(false);
1667 break;
1668
1669 case 0x1A: // Long format introduction date (days since year 0)
1670 ei->base_intro = buf->ReadDWord();
1671 break;
1672
1673 case 0x1B: // Alter purchase list sort order
1674 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1675 break;
1676
1677 case 0x1C: // Visual effect
1678 svi->visual_effect = buf->ReadByte();
1679 /* Avoid accidentally setting visual_effect to the default value
1680 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1681 if (svi->visual_effect == VE_DEFAULT) {
1682 assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1683 SB(svi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1684 }
1685 break;
1686
1687 case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1688 ei->cargo_age_period = buf->ReadWord();
1689 break;
1690
1691 case 0x1E: // CTT refit include list
1692 case 0x1F: { // CTT refit exclude list
1693 uint8_t count = buf->ReadByte();
1694 _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1695 if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1696 CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1697 ctt = 0;
1698 while (count--) {
1699 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1700 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1701 }
1702 break;
1703 }
1704
1705 case 0x20: // Engine variant
1706 ei->variant_id = buf->ReadWord();
1707 break;
1708
1709 case 0x21: // Extra miscellaneous flags
1710 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1711 break;
1712
1713 case 0x22: // Callback additional mask
1714 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1715 break;
1716
1717 case 0x23: // Speed (1 unit is 0.5 km-ish/h)
1718 svi->max_speed = buf->ReadWord();
1719 break;
1720
1721 case 0x24: // Acceleration (1 unit is 0.5 km-ish/h per tick)
1722 svi->acceleration = std::max<uint8_t>(1, buf->ReadByte());
1723 break;
1724
1725 default:
1726 ret = CommonVehicleChangeInfo(ei, prop, buf);
1727 break;
1728 }
1729 }
1730
1731 return ret;
1732 }
1733
1742 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1743 {
1744 ChangeInfoResult ret = CIR_SUCCESS;
1745
1746 for (int i = 0; i < numinfo; i++) {
1747 Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1748 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1749
1750 EngineInfo *ei = &e->info;
1751 AircraftVehicleInfo *avi = &e->u.air;
1752
1753 switch (prop) {
1754 case 0x08: { // Sprite ID
1755 uint8_t spriteid = buf->ReadByte();
1756 uint8_t orig_spriteid = spriteid;
1757
1758 /* aircraft have different custom id in the GRF file */
1759 if (spriteid == 0xFF) spriteid = 0xFD;
1760
1761 if (spriteid < 0xFD) spriteid >>= 1;
1762
1763 if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1764 avi->image_index = spriteid;
1765 } else {
1766 GrfMsg(1, "AircraftVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1767 avi->image_index = 0;
1768 }
1769 break;
1770 }
1771
1772 case 0x09: // Helicopter
1773 if (buf->ReadByte() == 0) {
1774 avi->subtype = AIR_HELI;
1775 } else {
1776 SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1777 }
1778 break;
1779
1780 case 0x0A: // Large
1781 SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1782 break;
1783
1784 case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1785 avi->cost_factor = buf->ReadByte();
1786 break;
1787
1788 case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1789 avi->max_speed = (buf->ReadByte() * 128) / 10;
1790 break;
1791
1792 case 0x0D: // Acceleration
1793 avi->acceleration = buf->ReadByte();
1794 break;
1795
1796 case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1797 avi->running_cost = buf->ReadByte();
1798 break;
1799
1800 case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1801 avi->passenger_capacity = buf->ReadWord();
1802 break;
1803
1804 case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1805 avi->mail_capacity = buf->ReadByte();
1806 break;
1807
1808 case 0x12: // SFX
1809 avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1810 break;
1811
1812 case 0x13: { // Cargoes available for refitting
1813 uint32_t mask = buf->ReadDWord();
1814 _gted[e->index].UpdateRefittability(mask != 0);
1815 ei->refit_mask = TranslateRefitMask(mask);
1816 _gted[e->index].defaultcargo_grf = _cur.grffile;
1817 break;
1818 }
1819
1820 case 0x14: // Callback mask
1821 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1822 break;
1823
1824 case 0x15: // Refit cost
1825 ei->refit_cost = buf->ReadByte();
1826 break;
1827
1828 case 0x16: // Retire vehicle early
1829 ei->retire_early = buf->ReadByte();
1830 break;
1831
1832 case 0x17: // Miscellaneous flags
1833 ei->misc_flags = buf->ReadByte();
1834 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1835 break;
1836
1837 case 0x18: // Cargo classes allowed
1838 _gted[e->index].cargo_allowed = buf->ReadWord();
1839 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1840 _gted[e->index].defaultcargo_grf = _cur.grffile;
1841 break;
1842
1843 case 0x19: // Cargo classes disallowed
1844 _gted[e->index].cargo_disallowed = buf->ReadWord();
1845 _gted[e->index].UpdateRefittability(false);
1846 break;
1847
1848 case 0x1A: // Long format introduction date (days since year 0)
1849 ei->base_intro = buf->ReadDWord();
1850 break;
1851
1852 case 0x1B: // Alter purchase list sort order
1853 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1854 break;
1855
1856 case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1857 ei->cargo_age_period = buf->ReadWord();
1858 break;
1859
1860 case 0x1D: // CTT refit include list
1861 case 0x1E: { // CTT refit exclude list
1862 uint8_t count = buf->ReadByte();
1863 _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1864 if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1865 CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1866 ctt = 0;
1867 while (count--) {
1868 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1869 if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1870 }
1871 break;
1872 }
1873
1874 case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1875 avi->max_range = buf->ReadWord();
1876 break;
1877
1878 case 0x20: // Engine variant
1879 ei->variant_id = buf->ReadWord();
1880 break;
1881
1882 case 0x21: // Extra miscellaneous flags
1883 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1884 break;
1885
1886 case 0x22: // Callback additional mask
1887 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1888 break;
1889
1890 default:
1891 ret = CommonVehicleChangeInfo(ei, prop, buf);
1892 break;
1893 }
1894 }
1895
1896 return ret;
1897 }
1898
1907 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
1908 {
1909 ChangeInfoResult ret = CIR_SUCCESS;
1910
1911 if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1912 GrfMsg(1, "StationChangeInfo: Station {} is invalid, max {}, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1913 return CIR_INVALID_ID;
1914 }
1915
1916 /* Allocate station specs if necessary */
1917 if (_cur.grffile->stations.size() < stid + numinfo) _cur.grffile->stations.resize(stid + numinfo);
1918
1919 for (int i = 0; i < numinfo; i++) {
1920 StationSpec *statspec = _cur.grffile->stations[stid + i].get();
1921
1922 /* Check that the station we are modifying is defined. */
1923 if (statspec == nullptr && prop != 0x08) {
1924 GrfMsg(2, "StationChangeInfo: Attempt to modify undefined station {}, ignoring", stid + i);
1925 return CIR_INVALID_ID;
1926 }
1927
1928 switch (prop) {
1929 case 0x08: { // Class ID
1930 /* Property 0x08 is special; it is where the station is allocated */
1931 if (statspec == nullptr) {
1932 _cur.grffile->stations[stid + i] = std::make_unique<StationSpec>();
1933 statspec = _cur.grffile->stations[stid + i].get();
1934 }
1935
1936 /* Swap classid because we read it in BE meaning WAYP or DFLT */
1937 uint32_t classid = buf->ReadDWord();
1938 statspec->cls_id = StationClass::Allocate(BSWAP32(classid));
1939 break;
1940 }
1941
1942 case 0x09: { // Define sprite layout
1943 uint16_t tiles = buf->ReadExtendedByte();
1944 statspec->renderdata.clear(); // delete earlier loaded stuff
1945 statspec->renderdata.reserve(tiles);
1946
1947 for (uint t = 0; t < tiles; t++) {
1948 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1949 dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1950
1951 if (buf->HasData(4) && *(uint32_t*)buf->Data() == 0) {
1952 buf->Skip(4);
1953 extern const DrawTileSprites _station_display_datas_rail[8];
1954 dts->Clone(&_station_display_datas_rail[t % 8]);
1955 continue;
1956 }
1957
1958 ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1959 /* On error, bail out immediately. Temporary GRF data was already freed */
1960 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1961
1962 static std::vector<DrawTileSeqStruct> tmp_layout;
1963 tmp_layout.clear();
1964 for (;;) {
1965 /* no relative bounding box support */
1966 DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1967 MemSetT(&dtss, 0);
1968
1969 dtss.delta_x = buf->ReadByte();
1970 if (dtss.IsTerminator()) break;
1971 dtss.delta_y = buf->ReadByte();
1972 dtss.delta_z = buf->ReadByte();
1973 dtss.size_x = buf->ReadByte();
1974 dtss.size_y = buf->ReadByte();
1975 dtss.size_z = buf->ReadByte();
1976
1977 ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1978 /* On error, bail out immediately. Temporary GRF data was already freed */
1979 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1980 }
1981 dts->Clone(tmp_layout.data());
1982 }
1983
1984 /* Number of layouts must be even, alternating X and Y */
1985 if (statspec->renderdata.size() & 1) {
1986 GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
1987 statspec->renderdata.pop_back();
1988 }
1989 break;
1990 }
1991
1992 case 0x0A: { // Copy sprite layout
1993 uint16_t srcid = buf->ReadExtendedByte();
1994 const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
1995
1996 if (srcstatspec == nullptr) {
1997 GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy sprite layout to {}.", srcid, stid + i);
1998 continue;
1999 }
2000
2001 statspec->renderdata.clear(); // delete earlier loaded stuff
2002 statspec->renderdata.reserve(srcstatspec->renderdata.size());
2003
2004 for (const auto &it : srcstatspec->renderdata) {
2005 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2006 dts->Clone(&it);
2007 }
2008 break;
2009 }
2010
2011 case 0x0B: // Callback mask
2012 statspec->callback_mask = buf->ReadByte();
2013 break;
2014
2015 case 0x0C: // Disallowed number of platforms
2016 statspec->disallowed_platforms = buf->ReadByte();
2017 break;
2018
2019 case 0x0D: // Disallowed platform lengths
2020 statspec->disallowed_lengths = buf->ReadByte();
2021 break;
2022
2023 case 0x0E: // Define custom layout
2024 while (buf->HasData()) {
2025 byte length = buf->ReadByte();
2026 byte number = buf->ReadByte();
2027
2028 if (length == 0 || number == 0) break;
2029
2030 if (statspec->layouts.size() < length) statspec->layouts.resize(length);
2031 if (statspec->layouts[length - 1].size() < number) statspec->layouts[length - 1].resize(number);
2032
2033 const byte *layout = buf->ReadBytes(length * number);
2034 statspec->layouts[length - 1][number - 1].assign(layout, layout + length * number);
2035
2036 /* Validate tile values are only the permitted 00, 02, 04 and 06. */
2037 for (auto &tile : statspec->layouts[length - 1][number - 1]) {
2038 if ((tile & 6) != tile) {
2039 GrfMsg(1, "StationChangeInfo: Invalid tile {} in layout {}x{}", tile, length, number);
2040 tile &= 6;
2041 }
2042 }
2043 }
2044 break;
2045
2046 case 0x0F: { // Copy custom layout
2047 uint16_t srcid = buf->ReadExtendedByte();
2048 const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
2049
2050 if (srcstatspec == nullptr) {
2051 GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy tile layout to {}.", srcid, stid + i);
2052 continue;
2053 }
2054
2055 statspec->layouts = srcstatspec->layouts;
2056 break;
2057 }
2058
2059 case 0x10: // Little/lots cargo threshold
2060 statspec->cargo_threshold = buf->ReadWord();
2061 break;
2062
2063 case 0x11: // Pylon placement
2064 statspec->pylons = buf->ReadByte();
2065 break;
2066
2067 case 0x12: // Cargo types for random triggers
2068 if (_cur.grffile->grf_version >= 7) {
2069 statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
2070 } else {
2071 statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
2072 }
2073 break;
2074
2075 case 0x13: // General flags
2076 statspec->flags = buf->ReadByte();
2077 break;
2078
2079 case 0x14: // Overhead wire placement
2080 statspec->wires = buf->ReadByte();
2081 break;
2082
2083 case 0x15: // Blocked tiles
2084 statspec->blocked = buf->ReadByte();
2085 break;
2086
2087 case 0x16: // Animation info
2088 statspec->animation.frames = buf->ReadByte();
2089 statspec->animation.status = buf->ReadByte();
2090 break;
2091
2092 case 0x17: // Animation speed
2093 statspec->animation.speed = buf->ReadByte();
2094 break;
2095
2096 case 0x18: // Animation triggers
2097 statspec->animation.triggers = buf->ReadWord();
2098 break;
2099
2100 /* 0x19 road routing (not implemented) */
2101
2102 case 0x1A: { // Advanced sprite layout
2103 uint16_t tiles = buf->ReadExtendedByte();
2104 statspec->renderdata.clear(); // delete earlier loaded stuff
2105 statspec->renderdata.reserve(tiles);
2106
2107 for (uint t = 0; t < tiles; t++) {
2108 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2109 uint num_building_sprites = buf->ReadByte();
2110 /* On error, bail out immediately. Temporary GRF data was already freed */
2111 if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2112 }
2113
2114 /* Number of layouts must be even, alternating X and Y */
2115 if (statspec->renderdata.size() & 1) {
2116 GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
2117 statspec->renderdata.pop_back();
2118 }
2119 break;
2120 }
2121
2122 case 0x1B: // Minimum bridge height (not implemented)
2123 buf->ReadWord();
2124 buf->ReadWord();
2125 buf->ReadWord();
2126 buf->ReadWord();
2127 break;
2128
2129 case 0x1C: // Station Name
2130 AddStringForMapping(buf->ReadWord(), &statspec->name);
2131 break;
2132
2133 case 0x1D: // Station Class name
2134 AddStringForMapping(buf->ReadWord(), &StationClass::Get(statspec->cls_id)->name);
2135 break;
2136
2137 default:
2138 ret = CIR_UNKNOWN;
2139 break;
2140 }
2141 }
2142
2143 return ret;
2144 }
2145
2154 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
2155 {
2156 ChangeInfoResult ret = CIR_SUCCESS;
2157
2158 if (id + numinfo > CF_END) {
2159 GrfMsg(1, "CanalChangeInfo: Canal feature 0x{:02X} is invalid, max {}, ignoring", id + numinfo, CF_END);
2160 return CIR_INVALID_ID;
2161 }
2162
2163 for (int i = 0; i < numinfo; i++) {
2164 CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2165
2166 switch (prop) {
2167 case 0x08:
2168 cp->callback_mask = buf->ReadByte();
2169 break;
2170
2171 case 0x09:
2172 cp->flags = buf->ReadByte();
2173 break;
2174
2175 default:
2176 ret = CIR_UNKNOWN;
2177 break;
2178 }
2179 }
2180
2181 return ret;
2182 }
2183
2192 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
2193 {
2194 ChangeInfoResult ret = CIR_SUCCESS;
2195
2196 if (brid + numinfo > MAX_BRIDGES) {
2197 GrfMsg(1, "BridgeChangeInfo: Bridge {} is invalid, max {}, ignoring", brid + numinfo, MAX_BRIDGES);
2198 return CIR_INVALID_ID;
2199 }
2200
2201 for (int i = 0; i < numinfo; i++) {
2202 BridgeSpec *bridge = &_bridge[brid + i];
2203
2204 switch (prop) {
2205 case 0x08: { // Year of availability
2206 /* We treat '0' as always available */
2207 byte year = buf->ReadByte();
2208 bridge->avail_year = (year > 0 ? CalendarTime::ORIGINAL_BASE_YEAR + year : 0);
2209 break;
2210 }
2211
2212 case 0x09: // Minimum length
2213 bridge->min_length = buf->ReadByte();
2214 break;
2215
2216 case 0x0A: // Maximum length
2217 bridge->max_length = buf->ReadByte();
2218 if (bridge->max_length > 16) bridge->max_length = UINT16_MAX;
2219 break;
2220
2221 case 0x0B: // Cost factor
2222 bridge->price = buf->ReadByte();
2223 break;
2224
2225 case 0x0C: // Maximum speed
2226 bridge->speed = buf->ReadWord();
2227 if (bridge->speed == 0) bridge->speed = UINT16_MAX;
2228 break;
2229
2230 case 0x0D: { // Bridge sprite tables
2231 byte tableid = buf->ReadByte();
2232 byte numtables = buf->ReadByte();
2233
2234 if (bridge->sprite_table == nullptr) {
2235 /* Allocate memory for sprite table pointers and zero out */
2236 bridge->sprite_table = CallocT<PalSpriteID*>(7);
2237 }
2238
2239 for (; numtables-- != 0; tableid++) {
2240 if (tableid >= 7) { // skip invalid data
2241 GrfMsg(1, "BridgeChangeInfo: Table {} >= 7, skipping", tableid);
2242 for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
2243 continue;
2244 }
2245
2246 if (bridge->sprite_table[tableid] == nullptr) {
2247 bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2248 }
2249
2250 for (byte sprite = 0; sprite < 32; sprite++) {
2251 SpriteID image = buf->ReadWord();
2252 PaletteID pal = buf->ReadWord();
2253
2254 bridge->sprite_table[tableid][sprite].sprite = image;
2255 bridge->sprite_table[tableid][sprite].pal = pal;
2256
2257 MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2258 }
2259 }
2260 break;
2261 }
2262
2263 case 0x0E: // Flags; bit 0 - disable far pillars
2264 bridge->flags = buf->ReadByte();
2265 break;
2266
2267 case 0x0F: // Long format year of availability (year since year 0)
2268 bridge->avail_year = Clamp(TimerGameCalendar::Year(buf->ReadDWord()), CalendarTime::MIN_YEAR, CalendarTime::MAX_YEAR);
2269 break;
2270
2271 case 0x10: { // purchase string
2272 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2273 if (newone != STR_UNDEFINED) bridge->material = newone;
2274 break;
2275 }
2276
2277 case 0x11: // description of bridge with rails or roads
2278 case 0x12: {
2279 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2280 if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2281 break;
2282 }
2283
2284 case 0x13: // 16 bits cost multiplier
2285 bridge->price = buf->ReadWord();
2286 break;
2287
2288 default:
2289 ret = CIR_UNKNOWN;
2290 break;
2291 }
2292 }
2293
2294 return ret;
2295 }
2296
2303 static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
2304 {
2305 ChangeInfoResult ret = CIR_SUCCESS;
2306
2307 switch (prop) {
2308 case 0x09:
2309 case 0x0B:
2310 case 0x0C:
2311 case 0x0D:
2312 case 0x0E:
2313 case 0x0F:
2314 case 0x11:
2315 case 0x14:
2316 case 0x15:
2317 case 0x16:
2318 case 0x18:
2319 case 0x19:
2320 case 0x1A:
2321 case 0x1B:
2322 case 0x1C:
2323 case 0x1D:
2324 case 0x1F:
2325 buf->ReadByte();
2326 break;
2327
2328 case 0x0A:
2329 case 0x10:
2330 case 0x12:
2331 case 0x13:
2332 case 0x21:
2333 case 0x22:
2334 buf->ReadWord();
2335 break;
2336
2337 case 0x1E:
2338 buf->ReadDWord();
2339 break;
2340
2341 case 0x17:
2342 for (uint j = 0; j < 4; j++) buf->ReadByte();
2343 break;
2344
2345 case 0x20: {
2346 byte count = buf->ReadByte();
2347 for (byte j = 0; j < count; j++) buf->ReadByte();
2348 break;
2349 }
2350
2351 case 0x23:
2352 buf->Skip(buf->ReadByte() * 2);
2353 break;
2354
2355 default:
2356 ret = CIR_UNKNOWN;
2357 break;
2358 }
2359 return ret;
2360 }
2361
2370 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
2371 {
2372 ChangeInfoResult ret = CIR_SUCCESS;
2373
2374 if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2375 GrfMsg(1, "TownHouseChangeInfo: Too many houses loaded ({}), max ({}). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2376 return CIR_INVALID_ID;
2377 }
2378
2379 /* Allocate house specs if they haven't been allocated already. */
2380 if (_cur.grffile->housespec.size() < hid + numinfo) _cur.grffile->housespec.resize(hid + numinfo);
2381
2382 for (int i = 0; i < numinfo; i++) {
2383 HouseSpec *housespec = _cur.grffile->housespec[hid + i].get();
2384
2385 if (prop != 0x08 && housespec == nullptr) {
2386 /* If the house property 08 is not yet set, ignore this property */
2387 ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2388 if (cir > ret) ret = cir;
2389 continue;
2390 }
2391
2392 switch (prop) {
2393 case 0x08: { // Substitute building type, and definition of a new house
2394 byte subs_id = buf->ReadByte();
2395 if (subs_id == 0xFF) {
2396 /* Instead of defining a new house, a substitute house id
2397 * of 0xFF disables the old house with the current id. */
2398 if (hid + i < NEW_HOUSE_OFFSET) HouseSpec::Get(hid + i)->enabled = false;
2399 continue;
2400 } else if (subs_id >= NEW_HOUSE_OFFSET) {
2401 /* The substitute id must be one of the original houses. */
2402 GrfMsg(2, "TownHouseChangeInfo: Attempt to use new house {} as substitute house for {}. Ignoring.", subs_id, hid + i);
2403 continue;
2404 }
2405
2406 /* Allocate space for this house. */
2407 if (housespec == nullptr) {
2408 /* Only the first property 08 setting copies properties; if you later change it, properties will stay. */
2409 _cur.grffile->housespec[hid + i] = std::make_unique<HouseSpec>(*HouseSpec::Get(subs_id));
2410 housespec = _cur.grffile->housespec[hid + i].get();
2411
2412 housespec->enabled = true;
2413 housespec->grf_prop.local_id = hid + i;
2414 housespec->grf_prop.subst_id = subs_id;
2415 housespec->grf_prop.grffile = _cur.grffile;
2416 /* Set default colours for randomization, used if not overridden. */
2417 housespec->random_colour[0] = COLOUR_RED;
2418 housespec->random_colour[1] = COLOUR_BLUE;
2419 housespec->random_colour[2] = COLOUR_ORANGE;
2420 housespec->random_colour[3] = COLOUR_GREEN;
2421
2422 /* House flags 40 and 80 are exceptions; these flags are never set automatically. */
2423 housespec->building_flags &= ~(BUILDING_IS_CHURCH | BUILDING_IS_STADIUM);
2424
2425 /* Make sure that the third cargo type is valid in this
2426 * climate. This can cause problems when copying the properties
2427 * of a house that accepts food, where the new house is valid
2428 * in the temperate climate. */
2429 if (!CargoSpec::Get(housespec->accepts_cargo[2])->IsValid()) {
2430 housespec->cargo_acceptance[2] = 0;
2431 }
2432 }
2433 break;
2434 }
2435
2436 case 0x09: // Building flags
2437 housespec->building_flags = (BuildingFlags)buf->ReadByte();
2438 break;
2439
2440 case 0x0A: { // Availability years
2441 uint16_t years = buf->ReadWord();
2442 housespec->min_year = GB(years, 0, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2443 housespec->max_year = GB(years, 8, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2444 break;
2445 }
2446
2447 case 0x0B: // Population
2448 housespec->population = buf->ReadByte();
2449 break;
2450
2451 case 0x0C: // Mail generation multiplier
2452 housespec->mail_generation = buf->ReadByte();
2453 break;
2454
2455 case 0x0D: // Passenger acceptance
2456 case 0x0E: // Mail acceptance
2457 housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
2458 break;
2459
2460 case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2461 int8_t goods = buf->ReadByte();
2462
2463 /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2464 * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2465 CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_CANDY : CT_GOODS) :
2466 ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_FIZZY_DRINKS : CT_FOOD);
2467
2468 /* Make sure the cargo type is valid in this climate. */
2469 if (!CargoSpec::Get(cid)->IsValid()) goods = 0;
2470
2471 housespec->accepts_cargo[2] = cid;
2472 housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2473 break;
2474 }
2475
2476 case 0x10: // Local authority rating decrease on removal
2477 housespec->remove_rating_decrease = buf->ReadWord();
2478 break;
2479
2480 case 0x11: // Removal cost multiplier
2481 housespec->removal_cost = buf->ReadByte();
2482 break;
2483
2484 case 0x12: // Building name ID
2485 AddStringForMapping(buf->ReadWord(), &housespec->building_name);
2486 break;
2487
2488 case 0x13: // Building availability mask
2489 housespec->building_availability = (HouseZones)buf->ReadWord();
2490 break;
2491
2492 case 0x14: // House callback mask
2493 housespec->callback_mask |= buf->ReadByte();
2494 break;
2495
2496 case 0x15: { // House override byte
2497 byte override = buf->ReadByte();
2498
2499 /* The house being overridden must be an original house. */
2500 if (override >= NEW_HOUSE_OFFSET) {
2501 GrfMsg(2, "TownHouseChangeInfo: Attempt to override new house {} with house id {}. Ignoring.", override, hid + i);
2502 continue;
2503 }
2504
2505 _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2506 break;
2507 }
2508
2509 case 0x16: // Periodic refresh multiplier
2510 housespec->processing_time = std::min<byte>(buf->ReadByte(), 63u);
2511 break;
2512
2513 case 0x17: // Four random colours to use
2514 for (uint j = 0; j < 4; j++) housespec->random_colour[j] = static_cast<Colours>(GB(buf->ReadByte(), 0, 4));
2515 break;
2516
2517 case 0x18: // Relative probability of appearing
2518 housespec->probability = buf->ReadByte();
2519 break;
2520
2521 case 0x19: // Extra flags
2522 housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
2523 break;
2524
2525 case 0x1A: // Animation frames
2526 housespec->animation.frames = buf->ReadByte();
2527 housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2528 SB(housespec->animation.frames, 7, 1, 0);
2529 break;
2530
2531 case 0x1B: // Animation speed
2532 housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
2533 break;
2534
2535 case 0x1C: // Class of the building type
2536 housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
2537 break;
2538
2539 case 0x1D: // Callback mask part 2
2540 housespec->callback_mask |= (buf->ReadByte() << 8);
2541 break;
2542
2543 case 0x1E: { // Accepted cargo types
2544 uint32_t cargotypes = buf->ReadDWord();
2545
2546 /* Check if the cargo types should not be changed */
2547 if (cargotypes == 0xFFFFFFFF) break;
2548
2549 for (uint j = 0; j < 3; j++) {
2550 /* Get the cargo number from the 'list' */
2551 uint8_t cargo_part = GB(cargotypes, 8 * j, 8);
2552 CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2553
2554 if (!IsValidCargoID(cargo)) {
2555 /* Disable acceptance of invalid cargo type */
2556 housespec->cargo_acceptance[j] = 0;
2557 } else {
2558 housespec->accepts_cargo[j] = cargo;
2559 }
2560 }
2561 break;
2562 }
2563
2564 case 0x1F: // Minimum life span
2565 housespec->minimum_life = buf->ReadByte();
2566 break;
2567
2568 case 0x20: { // Cargo acceptance watch list
2569 byte count = buf->ReadByte();
2570 for (byte j = 0; j < count; j++) {
2571 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2572 if (IsValidCargoID(cargo)) SetBit(housespec->watched_cargoes, cargo);
2573 }
2574 break;
2575 }
2576
2577 case 0x21: // long introduction year
2578 housespec->min_year = buf->ReadWord();
2579 break;
2580
2581 case 0x22: // long maximum year
2582 housespec->max_year = buf->ReadWord();
2583 break;
2584
2585 case 0x23: { // variable length cargo types accepted
2586 uint count = buf->ReadByte();
2587 if (count > lengthof(housespec->accepts_cargo)) {
2588 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2589 error->param_value[1] = prop;
2590 return CIR_DISABLED;
2591 }
2592 /* Always write the full accepts_cargo array, and check each index for being inside the
2593 * provided data. This ensures all values are properly initialized, and also avoids
2594 * any risks of array overrun. */
2595 for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2596 if (i < count) {
2597 housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2598 housespec->cargo_acceptance[i] = buf->ReadByte();
2599 } else {
2600 housespec->accepts_cargo[i] = INVALID_CARGO;
2601 housespec->cargo_acceptance[i] = 0;
2602 }
2603 }
2604 break;
2605 }
2606
2607 default:
2608 ret = CIR_UNKNOWN;
2609 break;
2610 }
2611 }
2612
2613 return ret;
2614 }
2615
2622 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32_t grfid, uint8_t language_id)
2623 {
2624 /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2625 const GRFFile *grffile = GetFileByGRFID(grfid);
2626 return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
2627 }
2628
2638 template <typename T>
2639 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
2640 {
2641 if (gvid != 0) {
2642 GrfMsg(1, "LoadTranslationTable: {} translation table must start at zero", name);
2643 return CIR_INVALID_ID;
2644 }
2645
2646 translation_table.clear();
2647 for (int i = 0; i < numinfo; i++) {
2648 uint32_t item = buf->ReadDWord();
2649 translation_table.push_back(BSWAP32(item));
2650 }
2651
2652 return CIR_SUCCESS;
2653 }
2654
2661 static std::string ReadDWordAsString(ByteReader *reader)
2662 {
2663 std::string output;
2664 for (int i = 0; i < 4; i++) output.push_back(reader->ReadByte());
2665 return StrMakeValid(output);
2666 }
2667
2676 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2677 {
2678 /* Properties which are handled as a whole */
2679 switch (prop) {
2680 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2681 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2682
2683 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2684 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2685
2686 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2687 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2688
2689 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2690 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2691
2692 default:
2693 break;
2694 }
2695
2696 /* Properties which are handled per item */
2697 ChangeInfoResult ret = CIR_SUCCESS;
2698 for (int i = 0; i < numinfo; i++) {
2699 switch (prop) {
2700 case 0x08: { // Cost base factor
2701 int factor = buf->ReadByte();
2702 uint price = gvid + i;
2703
2704 if (price < PR_END) {
2705 _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2706 } else {
2707 GrfMsg(1, "GlobalVarChangeInfo: Price {} out of range, ignoring", price);
2708 }
2709 break;
2710 }
2711
2712 case 0x0A: { // Currency display names
2713 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2714 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2715
2716 if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2717 _currency_specs[curidx].name = newone;
2718 _currency_specs[curidx].code.clear();
2719 }
2720 break;
2721 }
2722
2723 case 0x0B: { // Currency multipliers
2724 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2725 uint32_t rate = buf->ReadDWord();
2726
2727 if (curidx < CURRENCY_END) {
2728 /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2729 * which OTTD does not. For this reason, divide grf value by 1000,
2730 * to be compatible */
2731 _currency_specs[curidx].rate = rate / 1000;
2732 } else {
2733 GrfMsg(1, "GlobalVarChangeInfo: Currency multipliers {} out of range, ignoring", curidx);
2734 }
2735 break;
2736 }
2737
2738 case 0x0C: { // Currency options
2739 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2740 uint16_t options = buf->ReadWord();
2741
2742 if (curidx < CURRENCY_END) {
2743 _currency_specs[curidx].separator.clear();
2744 _currency_specs[curidx].separator.push_back(GB(options, 0, 8));
2745 /* By specifying only one bit, we prevent errors,
2746 * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2747 _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2748 } else {
2749 GrfMsg(1, "GlobalVarChangeInfo: Currency option {} out of range, ignoring", curidx);
2750 }
2751 break;
2752 }
2753
2754 case 0x0D: { // Currency prefix symbol
2755 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2756 std::string prefix = ReadDWordAsString(buf);
2757
2758 if (curidx < CURRENCY_END) {
2759 _currency_specs[curidx].prefix = prefix;
2760 } else {
2761 GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2762 }
2763 break;
2764 }
2765
2766 case 0x0E: { // Currency suffix symbol
2767 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2768 std::string suffix = ReadDWordAsString(buf);
2769
2770 if (curidx < CURRENCY_END) {
2771 _currency_specs[curidx].suffix = suffix;
2772 } else {
2773 GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2774 }
2775 break;
2776 }
2777
2778 case 0x0F: { // Euro introduction dates
2779 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2780 TimerGameCalendar::Year year_euro = buf->ReadWord();
2781
2782 if (curidx < CURRENCY_END) {
2783 _currency_specs[curidx].to_euro = year_euro;
2784 } else {
2785 GrfMsg(1, "GlobalVarChangeInfo: Euro intro date {} out of range, ignoring", curidx);
2786 }
2787 break;
2788 }
2789
2790 case 0x10: // Snow line height table
2791 if (numinfo > 1 || IsSnowLineSet()) {
2792 GrfMsg(1, "GlobalVarChangeInfo: The snowline can only be set once ({})", numinfo);
2793 } else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2794 GrfMsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table ({})", buf->Remaining());
2795 } else {
2796 byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2797
2798 for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2799 for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2800 table[i][j] = buf->ReadByte();
2801 if (_cur.grffile->grf_version >= 8) {
2802 if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2803 } else {
2804 if (table[i][j] >= 128) {
2805 /* no snow */
2806 table[i][j] = 0xFF;
2807 } else {
2808 table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2809 }
2810 }
2811 }
2812 }
2813 SetSnowLine(table);
2814 }
2815 break;
2816
2817 case 0x11: // GRF match for engine allocation
2818 /* This is loaded during the reservation stage, so just skip it here. */
2819 /* Each entry is 8 bytes. */
2820 buf->Skip(8);
2821 break;
2822
2823 case 0x13: // Gender translation table
2824 case 0x14: // Case translation table
2825 case 0x15: { // Plural form translation
2826 uint curidx = gvid + i; // The current index, i.e. language.
2827 const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2828 if (lang == nullptr) {
2829 GrfMsg(1, "GlobalVarChangeInfo: Language {} is not known, ignoring", curidx);
2830 /* Skip over the data. */
2831 if (prop == 0x15) {
2832 buf->ReadByte();
2833 } else {
2834 while (buf->ReadByte() != 0) {
2835 buf->ReadString();
2836 }
2837 }
2838 break;
2839 }
2840
2841 if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
2842
2843 if (prop == 0x15) {
2844 uint plural_form = buf->ReadByte();
2845 if (plural_form >= LANGUAGE_MAX_PLURAL) {
2846 GrfMsg(1, "GlobalVarChanceInfo: Plural form {} is out of range, ignoring", plural_form);
2847 } else {
2848 _cur.grffile->language_map[curidx].plural_form = plural_form;
2849 }
2850 break;
2851 }
2852
2853 byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
2854 while (newgrf_id != 0) {
2855 const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
2856
2857 /* We'll just ignore the UTF8 identifier character. This is (fairly)
2858 * safe as OpenTTD's strings gender/cases are usually in ASCII which
2859 * is just a subset of UTF8, or they need the bigger UTF8 characters
2860 * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2861 char32_t c;
2862 size_t len = Utf8Decode(&c, name);
2863 if (c == NFO_UTF8_IDENTIFIER) name += len;
2864
2865 LanguageMap::Mapping map;
2866 map.newgrf_id = newgrf_id;
2867 if (prop == 0x13) {
2868 map.openttd_id = lang->GetGenderIndex(name);
2869 if (map.openttd_id >= MAX_NUM_GENDERS) {
2870 GrfMsg(1, "GlobalVarChangeInfo: Gender name {} is not known, ignoring", name);
2871 } else {
2872 _cur.grffile->language_map[curidx].gender_map.push_back(map);
2873 }
2874 } else {
2875 map.openttd_id = lang->GetCaseIndex(name);
2876 if (map.openttd_id >= MAX_NUM_CASES) {
2877 GrfMsg(1, "GlobalVarChangeInfo: Case name {} is not known, ignoring", name);
2878 } else {
2879 _cur.grffile->language_map[curidx].case_map.push_back(map);
2880 }
2881 }
2882 newgrf_id = buf->ReadByte();
2883 }
2884 break;
2885 }
2886
2887 default:
2888 ret = CIR_UNKNOWN;
2889 break;
2890 }
2891 }
2892
2893 return ret;
2894 }
2895
2896 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2897 {
2898 /* Properties which are handled as a whole */
2899 switch (prop) {
2900 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2901 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2902
2903 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2904 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2905
2906 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2907 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2908
2909 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2910 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2911
2912 default:
2913 break;
2914 }
2915
2916 /* Properties which are handled per item */
2917 ChangeInfoResult ret = CIR_SUCCESS;
2918 for (int i = 0; i < numinfo; i++) {
2919 switch (prop) {
2920 case 0x08: // Cost base factor
2921 case 0x15: // Plural form translation
2922 buf->ReadByte();
2923 break;
2924
2925 case 0x0A: // Currency display names
2926 case 0x0C: // Currency options
2927 case 0x0F: // Euro introduction dates
2928 buf->ReadWord();
2929 break;
2930
2931 case 0x0B: // Currency multipliers
2932 case 0x0D: // Currency prefix symbol
2933 case 0x0E: // Currency suffix symbol
2934 buf->ReadDWord();
2935 break;
2936
2937 case 0x10: // Snow line height table
2938 buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2939 break;
2940
2941 case 0x11: { // GRF match for engine allocation
2942 uint32_t s = buf->ReadDWord();
2943 uint32_t t = buf->ReadDWord();
2944 SetNewGRFOverride(s, t);
2945 break;
2946 }
2947
2948 case 0x13: // Gender translation table
2949 case 0x14: // Case translation table
2950 while (buf->ReadByte() != 0) {
2951 buf->ReadString();
2952 }
2953 break;
2954
2955 default:
2956 ret = CIR_UNKNOWN;
2957 break;
2958 }
2959 }
2960
2961 return ret;
2962 }
2963
2964
2973 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
2974 {
2975 ChangeInfoResult ret = CIR_SUCCESS;
2976
2977 if (cid + numinfo > NUM_CARGO) {
2978 GrfMsg(2, "CargoChangeInfo: Cargo type {} out of range (max {})", cid + numinfo, NUM_CARGO - 1);
2979 return CIR_INVALID_ID;
2980 }
2981
2982 for (int i = 0; i < numinfo; i++) {
2983 CargoSpec *cs = CargoSpec::Get(cid + i);
2984
2985 switch (prop) {
2986 case 0x08: // Bit number of cargo
2987 cs->bitnum = buf->ReadByte();
2988 if (cs->IsValid()) {
2989 cs->grffile = _cur.grffile;
2990 SetBit(_cargo_mask, cid + i);
2991 } else {
2992 ClrBit(_cargo_mask, cid + i);
2993 }
2994 break;
2995
2996 case 0x09: // String ID for cargo type name
2997 AddStringForMapping(buf->ReadWord(), &cs->name);
2998 break;
2999
3000 case 0x0A: // String for 1 unit of cargo
3001 AddStringForMapping(buf->ReadWord(), &cs->name_single);
3002 break;
3003
3004 case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
3005 case 0x1B: // String for cargo units
3006 /* String for units of cargo. This is different in OpenTTD
3007 * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
3008 * Property 1B is used to set OpenTTD's behaviour. */
3009 AddStringForMapping(buf->ReadWord(), &cs->units_volume);
3010 break;
3011
3012 case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
3013 case 0x1C: // String for any amount of cargo
3014 /* Strings for an amount of cargo. This is different in OpenTTD
3015 * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
3016 * Property 1C is used to set OpenTTD's behaviour. */
3017 AddStringForMapping(buf->ReadWord(), &cs->quantifier);
3018 break;
3019
3020 case 0x0D: // String for two letter cargo abbreviation
3021 AddStringForMapping(buf->ReadWord(), &cs->abbrev);
3022 break;
3023
3024 case 0x0E: // Sprite ID for cargo icon
3025 cs->sprite = buf->ReadWord();
3026 break;
3027
3028 case 0x0F: // Weight of one unit of cargo
3029 cs->weight = buf->ReadByte();
3030 break;
3031
3032 case 0x10: // Used for payment calculation
3033 cs->transit_periods[0] = buf->ReadByte();
3034 break;
3035
3036 case 0x11: // Used for payment calculation
3037 cs->transit_periods[1] = buf->ReadByte();
3038 break;
3039
3040 case 0x12: // Base cargo price
3041 cs->initial_payment = buf->ReadDWord();
3042 break;
3043
3044 case 0x13: // Colour for station rating bars
3045 cs->rating_colour = buf->ReadByte();
3046 break;
3047
3048 case 0x14: // Colour for cargo graph
3049 cs->legend_colour = buf->ReadByte();
3050 break;
3051
3052 case 0x15: // Freight status
3053 cs->is_freight = (buf->ReadByte() != 0);
3054 break;
3055
3056 case 0x16: // Cargo classes
3057 cs->classes = buf->ReadWord();
3058 break;
3059
3060 case 0x17: // Cargo label
3061 cs->label = buf->ReadDWord();
3062 cs->label = BSWAP32(cs->label);
3063 break;
3064
3065 case 0x18: { // Town growth substitute type
3066 uint8_t substitute_type = buf->ReadByte();
3067
3068 switch (substitute_type) {
3069 case 0x00: cs->town_acceptance_effect = TAE_PASSENGERS; break;
3070 case 0x02: cs->town_acceptance_effect = TAE_MAIL; break;
3071 case 0x05: cs->town_acceptance_effect = TAE_GOODS; break;
3072 case 0x09: cs->town_acceptance_effect = TAE_WATER; break;
3073 case 0x0B: cs->town_acceptance_effect = TAE_FOOD; break;
3074 default:
3075 GrfMsg(1, "CargoChangeInfo: Unknown town growth substitute value {}, setting to none.", substitute_type);
3076 [[fallthrough]];
3077 case 0xFF: cs->town_acceptance_effect = TAE_NONE; break;
3078 }
3079 break;
3080 }
3081
3082 case 0x19: // Town growth coefficient
3083 buf->ReadWord();
3084 break;
3085
3086 case 0x1A: // Bitmask of callbacks to use
3087 cs->callback_mask = buf->ReadByte();
3088 break;
3089
3090 case 0x1D: // Vehicle capacity muliplier
3091 cs->multiplier = std::max<uint16_t>(1u, buf->ReadWord());
3092 break;
3093
3094 case 0x1E: { // Town production substitute type
3095 uint8_t substitute_type = buf->ReadByte();
3096
3097 switch (substitute_type) {
3098 case 0x00: cs->town_production_effect = TPE_PASSENGERS; break;
3099 case 0x02: cs->town_production_effect = TPE_MAIL; break;
3100 default:
3101 GrfMsg(1, "CargoChangeInfo: Unknown town production substitute value {}, setting to none.", substitute_type);
3102 [[fallthrough]];
3103 case 0xFF: cs->town_production_effect = TPE_NONE; break;
3104 }
3105 break;
3106 }
3107
3108 case 0x1F: // Town production multiplier
3109 cs->town_production_multiplier = std::max<uint16_t>(1U, buf->ReadWord());
3110 break;
3111
3112 default:
3113 ret = CIR_UNKNOWN;
3114 break;
3115 }
3116 }
3117
3118 return ret;
3119 }
3120
3121
3130 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
3131 {
3132 ChangeInfoResult ret = CIR_SUCCESS;
3133
3134 if (_cur.grffile->sound_offset == 0) {
3135 GrfMsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3136 return CIR_INVALID_ID;
3137 }
3138
3139 if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3140 GrfMsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect ({}), max ({}). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3141 return CIR_INVALID_ID;
3142 }
3143
3144 for (int i = 0; i < numinfo; i++) {
3145 SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3146
3147 switch (prop) {
3148 case 0x08: // Relative volume
3149 sound->volume = buf->ReadByte();
3150 break;
3151
3152 case 0x09: // Priority
3153 sound->priority = buf->ReadByte();
3154 break;
3155
3156 case 0x0A: { // Override old sound
3157 SoundID orig_sound = buf->ReadByte();
3158
3159 if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3160 GrfMsg(1, "SoundEffectChangeInfo: Original sound {} not defined (max {})", orig_sound, ORIGINAL_SAMPLE_COUNT);
3161 } else {
3162 SoundEntry *old_sound = GetSound(orig_sound);
3163
3164 /* Literally copy the data of the new sound over the original */
3165 *old_sound = *sound;
3166 }
3167 break;
3168 }
3169
3170 default:
3171 ret = CIR_UNKNOWN;
3172 break;
3173 }
3174 }
3175
3176 return ret;
3177 }
3178
3185 static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
3186 {
3187 ChangeInfoResult ret = CIR_SUCCESS;
3188
3189 switch (prop) {
3190 case 0x09:
3191 case 0x0D:
3192 case 0x0E:
3193 case 0x10:
3194 case 0x11:
3195 case 0x12:
3196 buf->ReadByte();
3197 break;
3198
3199 case 0x0A:
3200 case 0x0B:
3201 case 0x0C:
3202 case 0x0F:
3203 buf->ReadWord();
3204 break;
3205
3206 case 0x13:
3207 buf->Skip(buf->ReadByte() * 2);
3208 break;
3209
3210 default:
3211 ret = CIR_UNKNOWN;
3212 break;
3213 }
3214 return ret;
3215 }
3216
3225 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
3226 {
3227 ChangeInfoResult ret = CIR_SUCCESS;
3228
3229 if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3230 GrfMsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded ({}), max ({}). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3231 return CIR_INVALID_ID;
3232 }
3233
3234 /* Allocate industry tile specs if they haven't been allocated already. */
3235 if (_cur.grffile->indtspec.size() < indtid + numinfo) _cur.grffile->indtspec.resize(indtid + numinfo);
3236
3237 for (int i = 0; i < numinfo; i++) {
3238 IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i].get();
3239
3240 if (prop != 0x08 && tsp == nullptr) {
3241 ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf);
3242 if (cir > ret) ret = cir;
3243 continue;
3244 }
3245
3246 switch (prop) {
3247 case 0x08: { // Substitute industry tile type
3248 byte subs_id = buf->ReadByte();
3249 if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3250 /* The substitute id must be one of the original industry tile. */
3251 GrfMsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile {} as substitute industry tile for {}. Ignoring.", subs_id, indtid + i);
3252 continue;
3253 }
3254
3255 /* Allocate space for this industry. */
3256 if (tsp == nullptr) {
3257 _cur.grffile->indtspec[indtid + i] = std::make_unique<IndustryTileSpec>(_industry_tile_specs[subs_id]);
3258 tsp = _cur.grffile->indtspec[indtid + i].get();
3259
3260 tsp->enabled = true;
3261
3262 /* A copied tile should not have the animation infos copied too.
3263 * The anim_state should be left untouched, though
3264 * It is up to the author to animate them */
3265 tsp->anim_production = INDUSTRYTILE_NOANIM;
3266 tsp->anim_next = INDUSTRYTILE_NOANIM;
3267
3268 tsp->grf_prop.local_id = indtid + i;
3269 tsp->grf_prop.subst_id = subs_id;
3270 tsp->grf_prop.grffile = _cur.grffile;
3271 _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3272 }
3273 break;
3274 }
3275
3276 case 0x09: { // Industry tile override
3277 byte ovrid = buf->ReadByte();
3278
3279 /* The industry being overridden must be an original industry. */
3280 if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3281 GrfMsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile {} with industry tile id {}. Ignoring.", ovrid, indtid + i);
3282 continue;
3283 }
3284
3285 _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3286 break;
3287 }
3288
3289 case 0x0A: // Tile acceptance
3290 case 0x0B:
3291 case 0x0C: {
3292 uint16_t acctp = buf->ReadWord();
3293 tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3294 tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3295 break;
3296 }
3297
3298 case 0x0D: // Land shape flags
3299 tsp->slopes_refused = (Slope)buf->ReadByte();
3300 break;
3301
3302 case 0x0E: // Callback mask
3303 tsp->callback_mask = buf->ReadByte();
3304 break;
3305
3306 case 0x0F: // Animation information
3307 tsp->animation.frames = buf->ReadByte();
3308 tsp->animation.status = buf->ReadByte();
3309 break;
3310
3311 case 0x10: // Animation speed
3312 tsp->animation.speed = buf->ReadByte();
3313 break;
3314
3315 case 0x11: // Triggers for callback 25
3316 tsp->animation.triggers = buf->ReadByte();
3317 break;
3318
3319 case 0x12: // Special flags
3320 tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
3321 break;
3322
3323 case 0x13: { // variable length cargo acceptance
3324 byte num_cargoes = buf->ReadByte();
3325 if (num_cargoes > std::size(tsp->acceptance)) {
3326 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3327 error->param_value[1] = prop;
3328 return CIR_DISABLED;
3329 }
3330 for (uint i = 0; i < std::size(tsp->acceptance); i++) {
3331 if (i < num_cargoes) {
3332 tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3333 /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3334 tsp->acceptance[i] = (int8_t)buf->ReadByte();
3335 } else {
3336 tsp->accepts_cargo[i] = INVALID_CARGO;
3337 tsp->acceptance[i] = 0;
3338 }
3339 }
3340 break;
3341 }
3342
3343 default:
3344 ret = CIR_UNKNOWN;
3345 break;
3346 }
3347 }
3348
3349 return ret;
3350 }
3351
3358 static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
3359 {
3360 ChangeInfoResult ret = CIR_SUCCESS;
3361
3362 switch (prop) {
3363 case 0x09:
3364 case 0x0B:
3365 case 0x0F:
3366 case 0x12:
3367 case 0x13:
3368 case 0x14:
3369 case 0x17:
3370 case 0x18:
3371 case 0x19:
3372 case 0x21:
3373 case 0x22:
3374 buf->ReadByte();
3375 break;
3376
3377 case 0x0C:
3378 case 0x0D:
3379 case 0x0E:
3380 case 0x10:
3381 case 0x1B:
3382 case 0x1F:
3383 case 0x24:
3384 buf->ReadWord();
3385 break;
3386
3387 case 0x11:
3388 case 0x1A:
3389 case 0x1C:
3390 case 0x1D:
3391 case 0x1E:
3392 case 0x20:
3393 case 0x23:
3394 buf->ReadDWord();
3395 break;
3396
3397 case 0x0A: {
3398 byte num_table = buf->ReadByte();
3399 for (byte j = 0; j < num_table; j++) {
3400 for (uint k = 0;; k++) {
3401 byte x = buf->ReadByte();
3402 if (x == 0xFE && k == 0) {
3403 buf->ReadByte();
3404 buf->ReadByte();
3405 break;
3406 }
3407
3408 byte y = buf->ReadByte();
3409 if (x == 0 && y == 0x80) break;
3410
3411 byte gfx = buf->ReadByte();
3412 if (gfx == 0xFE) buf->ReadWord();
3413 }
3414 }
3415 break;
3416 }
3417
3418 case 0x16:
3419 for (byte j = 0; j < 3; j++) buf->ReadByte();
3420 break;
3421
3422 case 0x15:
3423 case 0x25:
3424 case 0x26:
3425 case 0x27:
3426 buf->Skip(buf->ReadByte());
3427 break;
3428
3429 case 0x28: {
3430 int num_inputs = buf->ReadByte();
3431 int num_outputs = buf->ReadByte();
3432 buf->Skip(num_inputs * num_outputs * 2);
3433 break;
3434 }
3435
3436 default:
3437 ret = CIR_UNKNOWN;
3438 break;
3439 }
3440 return ret;
3441 }
3442
3448 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3449 {
3450 const size_t size = layout.size();
3451 if (size == 0) return false;
3452
3453 for (size_t i = 0; i < size - 1; i++) {
3454 for (size_t j = i + 1; j < size; j++) {
3455 if (layout[i].ti.x == layout[j].ti.x &&
3456 layout[i].ti.y == layout[j].ti.y) {
3457 return false;
3458 }
3459 }
3460 }
3461
3462 bool have_regular_tile = false;
3463 for (const auto &tilelayout : layout) {
3464 if (tilelayout.gfx != GFX_WATERTILE_SPECIALCHECK) {
3465 have_regular_tile = true;
3466 break;
3467 }
3468 }
3469
3470 return have_regular_tile;
3471 }
3472
3481 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
3482 {
3483 ChangeInfoResult ret = CIR_SUCCESS;
3484
3485 if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3486 GrfMsg(1, "IndustriesChangeInfo: Too many industries loaded ({}), max ({}). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3487 return CIR_INVALID_ID;
3488 }
3489
3490 /* Allocate industry specs if they haven't been allocated already. */
3491 if (_cur.grffile->industryspec.size() < indid + numinfo) _cur.grffile->industryspec.resize(indid + numinfo);
3492
3493 for (int i = 0; i < numinfo; i++) {
3494 IndustrySpec *indsp = _cur.grffile->industryspec[indid + i].get();
3495
3496 if (prop != 0x08 && indsp == nullptr) {
3497 ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3498 if (cir > ret) ret = cir;
3499 continue;
3500 }
3501
3502 switch (prop) {
3503 case 0x08: { // Substitute industry type
3504 byte subs_id = buf->ReadByte();
3505 if (subs_id == 0xFF) {
3506 /* Instead of defining a new industry, a substitute industry id
3507 * of 0xFF disables the old industry with the current id. */
3508 _industry_specs[indid + i].enabled = false;
3509 continue;
3510 } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3511 /* The substitute id must be one of the original industry. */
3512 GrfMsg(2, "_industry_specs: Attempt to use new industry {} as substitute industry for {}. Ignoring.", subs_id, indid + i);
3513 continue;
3514 }
3515
3516 /* Allocate space for this industry.
3517 * Only need to do it once. If ever it is called again, it should not
3518 * do anything */
3519 if (indsp == nullptr) {
3520 _cur.grffile->industryspec[indid + i] = std::make_unique<IndustrySpec>(_origin_industry_specs[subs_id]);
3521 indsp = _cur.grffile->industryspec[indid + i].get();
3522
3523 indsp->enabled = true;
3524 indsp->grf_prop.local_id = indid + i;
3525 indsp->grf_prop.subst_id = subs_id;
3526 indsp->grf_prop.grffile = _cur.grffile;
3527 /* If the grf industry needs to check its surrounding upon creation, it should
3528 * rely on callbacks, not on the original placement functions */
3529 indsp->check_proc = CHECK_NOTHING;
3530 }
3531 break;
3532 }
3533
3534 case 0x09: { // Industry type override
3535 byte ovrid = buf->ReadByte();
3536
3537 /* The industry being overridden must be an original industry. */
3538 if (ovrid >= NEW_INDUSTRYOFFSET) {
3539 GrfMsg(2, "IndustriesChangeInfo: Attempt to override new industry {} with industry id {}. Ignoring.", ovrid, indid + i);
3540 continue;
3541 }
3542 indsp->grf_prop.override = ovrid;
3543 _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3544 break;
3545 }
3546
3547 case 0x0A: { // Set industry layout(s)
3548 byte new_num_layouts = buf->ReadByte();
3549 uint32_t definition_size = buf->ReadDWord();
3550 uint32_t bytes_read = 0;
3551 std::vector<IndustryTileLayout> new_layouts;
3552 IndustryTileLayout layout;
3553
3554 for (byte j = 0; j < new_num_layouts; j++) {
3555 layout.clear();
3556
3557 for (uint k = 0;; k++) {
3558 if (bytes_read >= definition_size) {
3559 GrfMsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry {}.", indid);
3560 /* Avoid warning twice */
3561 definition_size = UINT32_MAX;
3562 }
3563
3564 layout.push_back(IndustryTileLayoutTile{});
3565 IndustryTileLayoutTile &it = layout.back();
3566
3567 it.ti.x = buf->ReadByte(); // Offsets from northermost tile
3568 ++bytes_read;
3569
3570 if (it.ti.x == 0xFE && k == 0) {
3571 /* This means we have to borrow the layout from an old industry */
3572 IndustryType type = buf->ReadByte();
3573 byte laynbr = buf->ReadByte();
3574 bytes_read += 2;
3575
3576 if (type >= lengthof(_origin_industry_specs)) {
3577 GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", indid);
3578 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3579 return CIR_DISABLED;
3580 }
3581 if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3582 GrfMsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry {}", indid);
3583 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3584 return CIR_DISABLED;
3585 }
3586 layout = _origin_industry_specs[type].layouts[laynbr];
3587 break;
3588 }
3589
3590 it.ti.y = buf->ReadByte(); // Or table definition finalisation
3591 ++bytes_read;
3592
3593 if (it.ti.x == 0 && it.ti.y == 0x80) {
3594 /* Terminator, remove and finish up */
3595 layout.pop_back();
3596 break;
3597 }
3598
3599 it.gfx = buf->ReadByte();
3600 ++bytes_read;
3601
3602 if (it.gfx == 0xFE) {
3603 /* Use a new tile from this GRF */
3604 int local_tile_id = buf->ReadWord();
3605 bytes_read += 2;
3606
3607 /* Read the ID from the _industile_mngr. */
3608 int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3609
3610 if (tempid == INVALID_INDUSTRYTILE) {
3611 GrfMsg(2, "IndustriesChangeInfo: Attempt to use industry tile {} with industry id {}, not yet defined. Ignoring.", local_tile_id, indid);
3612 } else {
3613 /* Declared as been valid, can be used */
3614 it.gfx = tempid;
3615 }
3616 } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
3617 it.ti.x = (int8_t)GB(it.ti.x, 0, 8);
3618 it.ti.y = (int8_t)GB(it.ti.y, 0, 8);
3619
3620 /* When there were only 256x256 maps, TileIndex was a uint16_t and
3621 * it.ti was just a TileIndexDiff that was added to it.
3622 * As such negative "x" values were shifted into the "y" position.
3623 * x = -1, y = 1 -> x = 255, y = 0
3624 * Since GRF version 8 the position is interpreted as pair of independent int8.
3625 * For GRF version < 8 we need to emulate the old shifting behaviour.
3626 */
3627 if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3628 }
3629 }
3630
3631 if (!ValidateIndustryLayout(layout)) {
3632 /* The industry layout was not valid, so skip this one. */
3633 GrfMsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id {}. Ignoring", indid);
3634 new_num_layouts--;
3635 j--;
3636 } else {
3637 new_layouts.push_back(layout);
3638 }
3639 }
3640
3641 /* Install final layout construction in the industry spec */
3642 indsp->layouts = new_layouts;
3643 break;
3644 }
3645
3646 case 0x0B: // Industry production flags
3647 indsp->life_type = (IndustryLifeType)buf->ReadByte();
3648 break;
3649
3650 case 0x0C: // Industry closure message
3651 AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
3652 break;
3653
3654 case 0x0D: // Production increase message
3655 AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
3656 break;
3657
3658 case 0x0E: // Production decrease message
3659 AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
3660 break;
3661
3662 case 0x0F: // Fund cost multiplier
3663 indsp->cost_multiplier = buf->ReadByte();
3664 break;
3665
3666 case 0x10: // Production cargo types
3667 for (byte j = 0; j < 2; j++) {
3668 indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3669 }
3670 break;
3671
3672 case 0x11: // Acceptance cargo types
3673 for (byte j = 0; j < 3; j++) {
3674 indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3675 }
3676 buf->ReadByte(); // Unnused, eat it up
3677 break;
3678
3679 case 0x12: // Production multipliers
3680 case 0x13:
3681 indsp->production_rate[prop - 0x12] = buf->ReadByte();
3682 break;
3683
3684 case 0x14: // Minimal amount of cargo distributed
3685 indsp->minimal_cargo = buf->ReadByte();
3686 break;
3687
3688 case 0x15: { // Random sound effects
3689 indsp->number_of_sounds = buf->ReadByte();
3690 uint8_t *sounds = MallocT<uint8_t>(indsp->number_of_sounds);
3691
3692 try {
3693 for (uint8_t j = 0; j < indsp->number_of_sounds; j++) {
3694 sounds[j] = buf->ReadByte();
3695 }
3696 } catch (...) {
3697 free(sounds);
3698 throw;
3699 }
3700
3701 if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3702 free(indsp->random_sounds);
3703 }
3704 indsp->random_sounds = sounds;
3705 SetBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS);
3706 break;
3707 }
3708
3709 case 0x16: // Conflicting industry types
3710 for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
3711 break;
3712
3713 case 0x17: // Probability in random game
3714 indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
3715 break;
3716
3717 case 0x18: // Probability during gameplay
3718 indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
3719 break;
3720
3721 case 0x19: // Map colour
3722 indsp->map_colour = buf->ReadByte();
3723 break;
3724
3725 case 0x1A: // Special industry flags to define special behavior
3726 indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
3727 break;
3728
3729 case 0x1B: // New industry text ID
3730 AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
3731 break;
3732
3733 case 0x1C: // Input cargo multipliers for the three input cargo types
3734 case 0x1D:
3735 case 0x1E: {
3736 uint32_t multiples = buf->ReadDWord();
3737 indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3738 indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3739 break;
3740 }
3741
3742 case 0x1F: // Industry name
3743 AddStringForMapping(buf->ReadWord(), &indsp->name);
3744 break;
3745
3746 case 0x20: // Prospecting success chance
3747 indsp->prospecting_chance = buf->ReadDWord();
3748 break;
3749
3750 case 0x21: // Callback mask
3751 case 0x22: { // Callback additional mask
3752 byte aflag = buf->ReadByte();
3753 SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3754 break;
3755 }
3756
3757 case 0x23: // removal cost multiplier
3758 indsp->removal_cost_multiplier = buf->ReadDWord();
3759 break;
3760
3761 case 0x24: { // name for nearby station
3762 uint16_t str = buf->ReadWord();
3763 if (str == 0) {
3764 indsp->station_name = STR_NULL;
3765 } else {
3766 AddStringForMapping(str, &indsp->station_name);
3767 }
3768 break;
3769 }
3770
3771 case 0x25: { // variable length produced cargoes
3772 byte num_cargoes = buf->ReadByte();
3773 if (num_cargoes > lengthof(indsp->produced_cargo)) {
3774 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3775 error->param_value[1] = prop;
3776 return CIR_DISABLED;
3777 }
3778 for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
3779 if (i < num_cargoes) {
3780 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3781 indsp->produced_cargo[i] = cargo;
3782 } else {
3783 indsp->produced_cargo[i] = INVALID_CARGO;
3784 }
3785 }
3786 break;
3787 }
3788
3789 case 0x26: { // variable length accepted cargoes
3790 byte num_cargoes = buf->ReadByte();
3791 if (num_cargoes > lengthof(indsp->accepts_cargo)) {
3792 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3793 error->param_value[1] = prop;
3794 return CIR_DISABLED;
3795 }
3796 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3797 if (i < num_cargoes) {
3798 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3799 indsp->accepts_cargo[i] = cargo;
3800 } else {
3801 indsp->accepts_cargo[i] = INVALID_CARGO;
3802 }
3803 }
3804 break;
3805 }
3806
3807 case 0x27: { // variable length production rates
3808 byte num_cargoes = buf->ReadByte();
3809 if (num_cargoes > lengthof(indsp->production_rate)) {
3810 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3811 error->param_value[1] = prop;
3812 return CIR_DISABLED;
3813 }
3814 for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3815 if (i < num_cargoes) {
3816 indsp->production_rate[i] = buf->ReadByte();
3817 } else {
3818 indsp->production_rate[i] = 0;
3819 }
3820 }
3821 break;
3822 }
3823
3824 case 0x28: { // variable size input/output production multiplier table
3825 byte num_inputs = buf->ReadByte();
3826 byte num_outputs = buf->ReadByte();
3827 if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
3828 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3829 error->param_value[1] = prop;
3830 return CIR_DISABLED;
3831 }
3832 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3833 for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
3834 uint16_t mult = 0;
3835 if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
3836 indsp->input_cargo_multiplier[i][j] = mult;
3837 }
3838 }
3839 break;
3840 }
3841
3842 default:
3843 ret = CIR_UNKNOWN;
3844 break;
3845 }
3846 }
3847
3848 return ret;
3849 }
3850
3856 static void DuplicateTileTable(AirportSpec *as)
3857 {
3858 AirportTileTable **table_list = MallocT<AirportTileTable*>(as->num_table);
3859 for (int i = 0; i < as->num_table; i++) {
3860 uint num_tiles = 1;
3861 const AirportTileTable *it = as->table[0];
3862 do {
3863 num_tiles++;
3864 } while ((++it)->ti.x != -0x80);
3865 table_list[i] = MallocT<AirportTileTable>(num_tiles);
3866 MemCpyT(table_list[i], as->table[i], num_tiles);
3867 }
3868 as->table = table_list;
3869 HangarTileTable *depot_table = MallocT<HangarTileTable>(as->nof_depots);
3870 MemCpyT(depot_table, as->depot_table, as->nof_depots);
3871 as->depot_table = depot_table;
3872 Direction *rotation = MallocT<Direction>(as->num_table);
3873 MemCpyT(rotation, as->rotation, as->num_table);
3874 as->rotation = rotation;
3875 }
3876
3885 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
3886 {
3887 ChangeInfoResult ret = CIR_SUCCESS;
3888
3889 if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3890 GrfMsg(1, "AirportChangeInfo: Too many airports, trying id ({}), max ({}). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3891 return CIR_INVALID_ID;
3892 }
3893
3894 /* Allocate industry specs if they haven't been allocated already. */
3895 if (_cur.grffile->airportspec.size() < airport + numinfo) _cur.grffile->airportspec.resize(airport + numinfo);
3896
3897 for (int i = 0; i < numinfo; i++) {
3898 AirportSpec *as = _cur.grffile->airportspec[airport + i].get();
3899
3900 if (as == nullptr && prop != 0x08 && prop != 0x09) {
3901 GrfMsg(2, "AirportChangeInfo: Attempt to modify undefined airport {}, ignoring", airport + i);
3902 return CIR_INVALID_ID;
3903 }
3904
3905 switch (prop) {
3906 case 0x08: { // Modify original airport
3907 byte subs_id = buf->ReadByte();
3908 if (subs_id == 0xFF) {
3909 /* Instead of defining a new airport, an airport id
3910 * of 0xFF disables the old airport with the current id. */
3911 AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3912 continue;
3913 } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3914 /* The substitute id must be one of the original airports. */
3915 GrfMsg(2, "AirportChangeInfo: Attempt to use new airport {} as substitute airport for {}. Ignoring.", subs_id, airport + i);
3916 continue;
3917 }
3918
3919 /* Allocate space for this airport.
3920 * Only need to do it once. If ever it is called again, it should not
3921 * do anything */
3922 if (as == nullptr) {
3923 _cur.grffile->airportspec[airport + i] = std::make_unique<AirportSpec>(*AirportSpec::GetWithoutOverride(subs_id));
3924 as = _cur.grffile->airportspec[airport + i].get();
3925
3926 as->enabled = true;
3927 as->grf_prop.local_id = airport + i;
3928 as->grf_prop.subst_id = subs_id;
3929 as->grf_prop.grffile = _cur.grffile;
3930 /* override the default airport */
3931 _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3932 /* Create a copy of the original tiletable so it can be freed later. */
3933 DuplicateTileTable(as);
3934 }
3935 break;
3936 }
3937
3938 case 0x0A: { // Set airport layout
3939 byte old_num_table = as->num_table;
3940 free(as->rotation);
3941 as->num_table = buf->ReadByte(); // Number of layaouts
3942 as->rotation = MallocT<Direction>(as->num_table);
3943 uint32_t defsize = buf->ReadDWord(); // Total size of the definition
3944 AirportTileTable **tile_table = CallocT<AirportTileTable*>(as->num_table); // Table with tiles to compose the airport
3945 AirportTileTable *att = CallocT<AirportTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
3946 int size;
3947 const AirportTileTable *copy_from;
3948 try {
3949 for (byte j = 0; j < as->num_table; j++) {
3950 const_cast<Direction&>(as->rotation[j]) = (Direction)buf->ReadByte();
3951 for (int k = 0;; k++) {
3952 att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3953 att[k].ti.y = buf->ReadByte();
3954
3955 if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
3956 /* Not the same terminator. The one we are using is rather
3957 * x = -80, y = 0 . So, adjust it. */
3958 att[k].ti.x = -0x80;
3959 att[k].ti.y = 0;
3960 att[k].gfx = 0;
3961
3962 size = k + 1;
3963 copy_from = att;
3964 break;
3965 }
3966
3967 att[k].gfx = buf->ReadByte();
3968
3969 if (att[k].gfx == 0xFE) {
3970 /* Use a new tile from this GRF */
3971 int local_tile_id = buf->ReadWord();
3972
3973 /* Read the ID from the _airporttile_mngr. */
3974 uint16_t tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3975
3976 if (tempid == INVALID_AIRPORTTILE) {
3977 GrfMsg(2, "AirportChangeInfo: Attempt to use airport tile {} with airport id {}, not yet defined. Ignoring.", local_tile_id, airport + i);
3978 } else {
3979 /* Declared as been valid, can be used */
3980 att[k].gfx = tempid;
3981 }
3982 } else if (att[k].gfx == 0xFF) {
3983 att[k].ti.x = (int8_t)GB(att[k].ti.x, 0, 8);
3984 att[k].ti.y = (int8_t)GB(att[k].ti.y, 0, 8);
3985 }
3986
3987 if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
3988 as->size_x = std::max<byte>(as->size_x, att[k].ti.y + 1);
3989 as->size_y = std::max<byte>(as->size_y, att[k].ti.x + 1);
3990 } else {
3991 as->size_x = std::max<byte>(as->size_x, att[k].ti.x + 1);
3992 as->size_y = std::max<byte>(as->size_y, att[k].ti.y + 1);
3993 }
3994 }
3995 tile_table[j] = CallocT<AirportTileTable>(size);
3996 memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
3997 }
3998 /* Free old layouts in the airport spec */
3999 for (int j = 0; j < old_num_table; j++) {
4000 /* remove the individual layouts */
4001 free(as->table[j]);
4002 }
4003 free(as->table);
4004 /* Install final layout construction in the airport spec */
4005 as->table = tile_table;
4006 free(att);
4007 } catch (...) {
4008 for (int i = 0; i < as->num_table; i++) {
4009 free(tile_table[i]);
4010 }
4011 free(tile_table);
4012 free(att);
4013 throw;
4014 }
4015 break;
4016 }
4017
4018 case 0x0C:
4019 as->min_year = buf->ReadWord();
4020 as->max_year = buf->ReadWord();
4021 if (as->max_year == 0xFFFF) as->max_year = CalendarTime::MAX_YEAR;
4022 break;
4023
4024 case 0x0D:
4025 as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
4026 break;
4027
4028 case 0x0E:
4029 as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
4030 break;
4031
4032 case 0x0F:
4033 as->noise_level = buf->ReadByte();
4034 break;
4035
4036 case 0x10:
4037 AddStringForMapping(buf->ReadWord(), &as->name);
4038 break;
4039
4040 case 0x11: // Maintenance cost factor
4041 as->maintenance_cost = buf->ReadWord();
4042 break;
4043
4044 default:
4045 ret = CIR_UNKNOWN;
4046 break;
4047 }
4048 }
4049
4050 return ret;
4051 }
4052
4059 static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
4060 {
4061 ChangeInfoResult ret = CIR_SUCCESS;
4062
4063 switch (prop) {
4064 case 0x0B:
4065 case 0x0C:
4066 case 0x0D:
4067 case 0x12:
4068 case 0x14:
4069 case 0x16:
4070 case 0x17:
4071 case 0x18:
4072 buf->ReadByte();
4073 break;
4074
4075 case 0x09:
4076 case 0x0A:
4077 case 0x10:
4078 case 0x11:
4079 case 0x13:
4080 case 0x15:
4081 buf->ReadWord();
4082 break;
4083
4084 case 0x08:
4085 case 0x0E:
4086 case 0x0F:
4087 buf->ReadDWord();
4088 break;
4089
4090 default:
4091 ret = CIR_UNKNOWN;
4092 break;
4093 }
4094
4095 return ret;
4096 }
4097
4106 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4107 {
4108 ChangeInfoResult ret = CIR_SUCCESS;
4109
4110 if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4111 GrfMsg(1, "ObjectChangeInfo: Too many objects loaded ({}), max ({}). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4112 return CIR_INVALID_ID;
4113 }
4114
4115 /* Allocate object specs if they haven't been allocated already. */
4116 if (_cur.grffile->objectspec.size() < id + numinfo) _cur.grffile->objectspec.resize(id + numinfo);
4117
4118 for (int i = 0; i < numinfo; i++) {
4119 ObjectSpec *spec = _cur.grffile->objectspec[id + i].get();
4120
4121 if (prop != 0x08 && spec == nullptr) {
4122 /* If the object property 08 is not yet set, ignore this property */
4123 ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4124 if (cir > ret) ret = cir;
4125 continue;
4126 }
4127
4128 switch (prop) {
4129 case 0x08: { // Class ID
4130 /* Allocate space for this object. */
4131 if (spec == nullptr) {
4132 _cur.grffile->objectspec[id + i] = std::make_unique<ObjectSpec>();
4133 spec = _cur.grffile->objectspec[id + i].get();
4134 spec->views = 1; // Default for NewGRFs that don't set it.
4135 spec->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
4136 }
4137
4138 /* Swap classid because we read it in BE. */
4139 uint32_t classid = buf->ReadDWord();
4140 spec->cls_id = ObjectClass::Allocate(BSWAP32(classid));
4141 break;
4142 }
4143
4144 case 0x09: { // Class name
4145 ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
4146 AddStringForMapping(buf->ReadWord(), &objclass->name);
4147 break;
4148 }
4149
4150 case 0x0A: // Object name
4151 AddStringForMapping(buf->ReadWord(), &spec->name);
4152 break;
4153
4154 case 0x0B: // Climate mask
4155 spec->climate = buf->ReadByte();
4156 break;
4157
4158 case 0x0C: // Size
4159 spec->size = buf->ReadByte();
4160 if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4161 GrfMsg(0, "ObjectChangeInfo: Invalid object size requested (0x{:X}) for object id {}. Ignoring.", spec->size, id + i);
4162 spec->size = OBJECT_SIZE_1X1;
4163 }
4164 break;
4165
4166 case 0x0D: // Build cost multipler
4167 spec->build_cost_multiplier = buf->ReadByte();
4168 spec->clear_cost_multiplier = spec->build_cost_multiplier;
4169 break;
4170
4171 case 0x0E: // Introduction date
4172 spec->introduction_date = buf->ReadDWord();
4173 break;
4174
4175 case 0x0F: // End of life
4176 spec->end_of_life_date = buf->ReadDWord();
4177 break;
4178
4179 case 0x10: // Flags
4180 spec->flags = (ObjectFlags)buf->ReadWord();
4181 _loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
4182 break;
4183
4184 case 0x11: // Animation info
4185 spec->animation.frames = buf->ReadByte();
4186 spec->animation.status = buf->ReadByte();
4187 break;
4188
4189 case 0x12: // Animation speed
4190 spec->animation.speed = buf->ReadByte();
4191 break;
4192
4193 case 0x13: // Animation triggers
4194 spec->animation.triggers = buf->ReadWord();
4195 break;
4196
4197 case 0x14: // Removal cost multiplier
4198 spec->clear_cost_multiplier = buf->ReadByte();
4199 break;
4200
4201 case 0x15: // Callback mask
4202 spec->callback_mask = buf->ReadWord();
4203 break;
4204
4205 case 0x16: // Building height
4206 spec->height = buf->ReadByte();
4207 break;
4208
4209 case 0x17: // Views
4210 spec->views = buf->ReadByte();
4211 if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4212 GrfMsg(2, "ObjectChangeInfo: Invalid number of views ({}) for object id {}. Ignoring.", spec->views, id + i);
4213 spec->views = 1;
4214 }
4215 break;
4216
4217 case 0x18: // Amount placed on 256^2 map on map creation
4218 spec->generate_amount = buf->ReadByte();
4219 break;
4220
4221 default:
4222 ret = CIR_UNKNOWN;
4223 break;
4224 }
4225 }
4226
4227 return ret;
4228 }
4229
4238 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4239 {
4240 ChangeInfoResult ret = CIR_SUCCESS;
4241
4242 extern RailTypeInfo _railtypes[RAILTYPE_END];
4243
4244 if (id + numinfo > RAILTYPE_END) {
4245 GrfMsg(1, "RailTypeChangeInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4246 return CIR_INVALID_ID;
4247 }
4248
4249 for (int i = 0; i < numinfo; i++) {
4250 RailType rt = _cur.grffile->railtype_map[id + i];
4251 if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4252
4253 RailTypeInfo *rti = &_railtypes[rt];
4254
4255 switch (prop) {
4256 case 0x08: // Label of rail type
4257 /* Skipped here as this is loaded during reservation stage. */
4258 buf->ReadDWord();
4259 break;
4260
4261 case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4262 uint16_t str = buf->ReadWord();
4263 AddStringForMapping(str, &rti->strings.toolbar_caption);
4264 if (_cur.grffile->grf_version < 8) {
4265 AddStringForMapping(str, &rti->strings.name);
4266 }
4267 break;
4268 }
4269
4270 case 0x0A: // Menu text of railtype
4271 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4272 break;
4273
4274 case 0x0B: // Build window caption
4275 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4276 break;
4277
4278 case 0x0C: // Autoreplace text
4279 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4280 break;
4281
4282 case 0x0D: // New locomotive text
4283 AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
4284 break;
4285
4286 case 0x0E: // Compatible railtype list
4287 case 0x0F: // Powered railtype list
4288 case 0x18: // Railtype list required for date introduction
4289 case 0x19: // Introduced railtype list
4290 {
4291 /* Rail type compatibility bits are added to the existing bits
4292 * to allow multiple GRFs to modify compatibility with the
4293 * default rail types. */
4294 int n = buf->ReadByte();
4295 for (int j = 0; j != n; j++) {
4296 RailTypeLabel label = buf->ReadDWord();
4297 RailType resolved_rt = GetRailTypeByLabel(BSWAP32(label), false);
4298 if (resolved_rt != INVALID_RAILTYPE) {
4299 switch (prop) {
4300 case 0x0F: SetBit(rti->powered_railtypes, resolved_rt); [[fallthrough]]; // Powered implies compatible.
4301 case 0x0E: SetBit(rti->compatible_railtypes, resolved_rt); break;
4302 case 0x18: SetBit(rti->introduction_required_railtypes, resolved_rt); break;
4303 case 0x19: SetBit(rti->introduces_railtypes, resolved_rt); break;
4304 }
4305 }
4306 }
4307 break;
4308 }
4309
4310 case 0x10: // Rail Type flags
4311 rti->flags = (RailTypeFlags)buf->ReadByte();
4312 break;
4313
4314 case 0x11: // Curve speed advantage
4315 rti->curve_speed = buf->ReadByte();
4316 break;
4317
4318 case 0x12: // Station graphic
4319 rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
4320 break;
4321
4322 case 0x13: // Construction cost factor
4323 rti->cost_multiplier = buf->ReadWord();
4324 break;
4325
4326 case 0x14: // Speed limit
4327 rti->max_speed = buf->ReadWord();
4328 break;
4329
4330 case 0x15: // Acceleration model
4331 rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
4332 break;
4333
4334 case 0x16: // Map colour
4335 rti->map_colour = buf->ReadByte();
4336 break;
4337
4338 case 0x17: // Introduction date
4339 rti->introduction_date = buf->ReadDWord();
4340 break;
4341
4342 case 0x1A: // Sort order
4343 rti->sorting_order = buf->ReadByte();
4344 break;
4345
4346 case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4347 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4348 break;
4349
4350 case 0x1C: // Maintenance cost factor
4351 rti->maintenance_multiplier = buf->ReadWord();
4352 break;
4353
4354 case 0x1D: // Alternate rail type label list
4355 /* Skipped here as this is loaded during reservation stage. */
4356 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4357 break;
4358
4359 default:
4360 ret = CIR_UNKNOWN;
4361 break;
4362 }
4363 }
4364
4365 return ret;
4366 }
4367
4368 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4369 {
4370 ChangeInfoResult ret = CIR_SUCCESS;
4371
4372 extern RailTypeInfo _railtypes[RAILTYPE_END];
4373
4374 if (id + numinfo > RAILTYPE_END) {
4375 GrfMsg(1, "RailTypeReserveInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4376 return CIR_INVALID_ID;
4377 }
4378
4379 for (int i = 0; i < numinfo; i++) {
4380 switch (prop) {
4381 case 0x08: // Label of rail type
4382 {
4383 RailTypeLabel rtl = buf->ReadDWord();
4384 rtl = BSWAP32(rtl);
4385
4386 RailType rt = GetRailTypeByLabel(rtl, false);
4387 if (rt == INVALID_RAILTYPE) {
4388 /* Set up new rail type */
4389 rt = AllocateRailType(rtl);
4390 }
4391
4392 _cur.grffile->railtype_map[id + i] = rt;
4393 break;
4394 }
4395
4396 case 0x09: // Toolbar caption of railtype
4397 case 0x0A: // Menu text
4398 case 0x0B: // Build window caption
4399 case 0x0C: // Autoreplace text
4400 case 0x0D: // New loco
4401 case 0x13: // Construction cost
4402 case 0x14: // Speed limit
4403 case 0x1B: // Name of railtype
4404 case 0x1C: // Maintenance cost factor
4405 buf->ReadWord();
4406 break;
4407
4408 case 0x1D: // Alternate rail type label list
4409 if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4410 int n = buf->ReadByte();
4411 for (int j = 0; j != n; j++) {
4412 _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4413 }
4414 break;
4415 }
4416 GrfMsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type {} because no label was set", id + i);
4417 [[fallthrough]];
4418
4419 case 0x0E: // Compatible railtype list
4420 case 0x0F: // Powered railtype list
4421 case 0x18: // Railtype list required for date introduction
4422 case 0x19: // Introduced railtype list
4423 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4424 break;
4425
4426 case 0x10: // Rail Type flags
4427 case 0x11: // Curve speed advantage
4428 case 0x12: // Station graphic
4429 case 0x15: // Acceleration model
4430 case 0x16: // Map colour
4431 case 0x1A: // Sort order
4432 buf->ReadByte();
4433 break;
4434
4435 case 0x17: // Introduction date
4436 buf->ReadDWord();
4437 break;
4438
4439 default:
4440 ret = CIR_UNKNOWN;
4441 break;
4442 }
4443 }
4444
4445 return ret;
4446 }
4447
4456 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4457 {
4458 ChangeInfoResult ret = CIR_SUCCESS;
4459
4460 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4461 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4462
4463 if (id + numinfo > ROADTYPE_END) {
4464 GrfMsg(1, "RoadTypeChangeInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4465 return CIR_INVALID_ID;
4466 }
4467
4468 for (int i = 0; i < numinfo; i++) {
4469 RoadType rt = type_map[id + i];
4470 if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4471
4472 RoadTypeInfo *rti = &_roadtypes[rt];
4473
4474 switch (prop) {
4475 case 0x08: // Label of road type
4476 /* Skipped here as this is loaded during reservation stage. */
4477 buf->ReadDWord();
4478 break;
4479
4480 case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4481 uint16_t str = buf->ReadWord();
4482 AddStringForMapping(str, &rti->strings.toolbar_caption);
4483 break;
4484 }
4485
4486 case 0x0A: // Menu text of roadtype
4487 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4488 break;
4489
4490 case 0x0B: // Build window caption
4491 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4492 break;
4493
4494 case 0x0C: // Autoreplace text
4495 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4496 break;
4497
4498 case 0x0D: // New engine text
4499 AddStringForMapping(buf->ReadWord(), &rti->strings.new_engine);
4500 break;
4501
4502 case 0x0F: // Powered roadtype list
4503 case 0x18: // Roadtype list required for date introduction
4504 case 0x19: { // Introduced roadtype list
4505 /* Road type compatibility bits are added to the existing bits
4506 * to allow multiple GRFs to modify compatibility with the
4507 * default road types. */
4508 int n = buf->ReadByte();
4509 for (int j = 0; j != n; j++) {
4510 RoadTypeLabel label = buf->ReadDWord();
4511 RoadType resolved_rt = GetRoadTypeByLabel(BSWAP32(label), false);
4512 if (resolved_rt != INVALID_ROADTYPE) {
4513 switch (prop) {
4514 case 0x0F:
4515 if (GetRoadTramType(resolved_rt) == rtt) {
4516 SetBit(rti->powered_roadtypes, resolved_rt);
4517 } else {
4518 GrfMsg(1, "RoadTypeChangeInfo: Powered road type list: Road type {} road/tram type does not match road type {}, ignoring", resolved_rt, rt);
4519 }
4520 break;
4521 case 0x18: SetBit(rti->introduction_required_roadtypes, resolved_rt); break;
4522 case 0x19: SetBit(rti->introduces_roadtypes, resolved_rt); break;
4523 }
4524 }
4525 }
4526 break;
4527 }
4528
4529 case 0x10: // Road Type flags
4530 rti->flags = (RoadTypeFlags)buf->ReadByte();
4531 break;
4532
4533 case 0x13: // Construction cost factor
4534 rti->cost_multiplier = buf->ReadWord();
4535 break;
4536
4537 case 0x14: // Speed limit
4538 rti->max_speed = buf->ReadWord();
4539 break;
4540
4541 case 0x16: // Map colour
4542 rti->map_colour = buf->ReadByte();
4543 break;
4544
4545 case 0x17: // Introduction date
4546 rti->introduction_date = buf->ReadDWord();
4547 break;
4548
4549 case 0x1A: // Sort order
4550 rti->sorting_order = buf->ReadByte();
4551 break;
4552
4553 case 0x1B: // Name of roadtype
4554 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4555 break;
4556
4557 case 0x1C: // Maintenance cost factor
4558 rti->maintenance_multiplier = buf->ReadWord();
4559 break;
4560
4561 case 0x1D: // Alternate road type label list
4562 /* Skipped here as this is loaded during reservation stage. */
4563 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4564 break;
4565
4566 default:
4567 ret = CIR_UNKNOWN;
4568 break;
4569 }
4570 }
4571
4572 return ret;
4573 }
4574
4575 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4576 {
4577 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4578 }
4579
4580 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4581 {
4582 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4583 }
4584
4585
4586 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4587 {
4588 ChangeInfoResult ret = CIR_SUCCESS;
4589
4590 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4591 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4592
4593 if (id + numinfo > ROADTYPE_END) {
4594 GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4595 return CIR_INVALID_ID;
4596 }
4597
4598 for (int i = 0; i < numinfo; i++) {
4599 switch (prop) {
4600 case 0x08: { // Label of road type
4601 RoadTypeLabel rtl = buf->ReadDWord();
4602 rtl = BSWAP32(rtl);
4603
4604 RoadType rt = GetRoadTypeByLabel(rtl, false);
4605 if (rt == INVALID_ROADTYPE) {
4606 /* Set up new road type */
4607 rt = AllocateRoadType(rtl, rtt);
4608 } else if (GetRoadTramType(rt) != rtt) {
4609 GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid type (road/tram), ignoring", id + numinfo);
4610 return CIR_INVALID_ID;
4611 }
4612
4613 type_map[id + i] = rt;
4614 break;
4615 }
4616 case 0x09: // Toolbar caption of roadtype
4617 case 0x0A: // Menu text
4618 case 0x0B: // Build window caption
4619 case 0x0C: // Autoreplace text
4620 case 0x0D: // New loco
4621 case 0x13: // Construction cost
4622 case 0x14: // Speed limit
4623 case 0x1B: // Name of roadtype
4624 case 0x1C: // Maintenance cost factor
4625 buf->ReadWord();
4626 break;
4627
4628 case 0x1D: // Alternate road type label list
4629 if (type_map[id + i] != INVALID_ROADTYPE) {
4630 int n = buf->ReadByte();
4631 for (int j = 0; j != n; j++) {
4632 _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4633 }
4634 break;
4635 }
4636 GrfMsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type {} because no label was set", id + i);
4637 /* FALL THROUGH */
4638
4639 case 0x0F: // Powered roadtype list
4640 case 0x18: // Roadtype list required for date introduction
4641 case 0x19: // Introduced roadtype list
4642 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4643 break;
4644
4645 case 0x10: // Road Type flags
4646 case 0x16: // Map colour
4647 case 0x1A: // Sort order
4648 buf->ReadByte();
4649 break;
4650
4651 case 0x17: // Introduction date
4652 buf->ReadDWord();
4653 break;
4654
4655 default:
4656 ret = CIR_UNKNOWN;
4657 break;
4658 }
4659 }
4660
4661 return ret;
4662 }
4663
4664 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4665 {
4666 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4667 }
4668
4669 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4670 {
4671 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4672 }
4673
4674 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader *buf)
4675 {
4676 ChangeInfoResult ret = CIR_SUCCESS;
4677
4678 if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4679 GrfMsg(1, "AirportTileChangeInfo: Too many airport tiles loaded ({}), max ({}). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4680 return CIR_INVALID_ID;
4681 }
4682
4683 /* Allocate airport tile specs if they haven't been allocated already. */
4684 if (_cur.grffile->airtspec.size() < airtid + numinfo) _cur.grffile->airtspec.resize(airtid + numinfo);
4685
4686 for (int i = 0; i < numinfo; i++) {
4687 AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i].get();
4688
4689 if (prop != 0x08 && tsp == nullptr) {
4690 GrfMsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile {}. Ignoring.", airtid + i);
4691 return CIR_INVALID_ID;
4692 }
4693
4694 switch (prop) {
4695 case 0x08: { // Substitute airport tile type
4696 byte subs_id = buf->ReadByte();
4697 if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4698 /* The substitute id must be one of the original airport tiles. */
4699 GrfMsg(2, "AirportTileChangeInfo: Attempt to use new airport tile {} as substitute airport tile for {}. Ignoring.", subs_id, airtid + i);
4700 continue;
4701 }
4702
4703 /* Allocate space for this airport tile. */
4704 if (tsp == nullptr) {
4705 _cur.grffile->airtspec[airtid + i] = std::make_unique<AirportTileSpec>(*AirportTileSpec::Get(subs_id));
4706 tsp = _cur.grffile->airtspec[airtid + i].get();
4707
4708 tsp->enabled = true;
4709
4710 tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
4711
4712 tsp->grf_prop.local_id = airtid + i;
4713 tsp->grf_prop.subst_id = subs_id;
4714 tsp->grf_prop.grffile = _cur.grffile;
4715 _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4716 }
4717 break;
4718 }
4719
4720 case 0x09: { // Airport tile override
4721 byte override = buf->ReadByte();
4722
4723 /* The airport tile being overridden must be an original airport tile. */
4724 if (override >= NEW_AIRPORTTILE_OFFSET) {
4725 GrfMsg(2, "AirportTileChangeInfo: Attempt to override new airport tile {} with airport tile id {}. Ignoring.", override, airtid + i);
4726 continue;
4727 }
4728
4729 _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4730 break;
4731 }
4732
4733 case 0x0E: // Callback mask
4734 tsp->callback_mask = buf->ReadByte();
4735 break;
4736
4737 case 0x0F: // Animation information
4738 tsp->animation.frames = buf->ReadByte();
4739 tsp->animation.status = buf->ReadByte();
4740 break;
4741
4742 case 0x10: // Animation speed
4743 tsp->animation.speed = buf->ReadByte();
4744 break;
4745
4746 case 0x11: // Animation triggers
4747 tsp->animation.triggers = buf->ReadByte();
4748 break;
4749
4750 default:
4751 ret = CIR_UNKNOWN;
4752 break;
4753 }
4754 }
4755
4756 return ret;
4757 }
4758
4765 static ChangeInfoResult IgnoreRoadStopProperty(uint prop, ByteReader *buf)
4766 {
4767 ChangeInfoResult ret = CIR_SUCCESS;
4768
4769 switch (prop) {
4770 case 0x09:
4771 case 0x0C:
4772 case 0x0F:
4773 case 0x11:
4774 buf->ReadByte();
4775 break;
4776
4777 case 0x0A:
4778 case 0x0B:
4779 case 0x0E:
4780 case 0x10:
4781 case 0x15:
4782 buf->ReadWord();
4783 break;
4784
4785 case 0x08:
4786 case 0x0D:
4787 case 0x12:
4788 buf->ReadDWord();
4789 break;
4790
4791 default:
4792 ret = CIR_UNKNOWN;
4793 break;
4794 }
4795
4796 return ret;
4797 }
4798
4799 static ChangeInfoResult RoadStopChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4800 {
4801 ChangeInfoResult ret = CIR_SUCCESS;
4802
4803 if (id + numinfo > NUM_ROADSTOPS_PER_GRF) {
4804 GrfMsg(1, "RoadStopChangeInfo: RoadStop {} is invalid, max {}, ignoring", id + numinfo, NUM_ROADSTOPS_PER_GRF);
4805 return CIR_INVALID_ID;
4806 }
4807
4808 if (_cur.grffile->roadstops.size() < id + numinfo) _cur.grffile->roadstops.resize(id + numinfo);
4809
4810 for (int i = 0; i < numinfo; i++) {
4811 RoadStopSpec *rs = _cur.grffile->roadstops[id + i].get();
4812
4813 if (rs == nullptr && prop != 0x08) {
4814 GrfMsg(1, "RoadStopChangeInfo: Attempt to modify undefined road stop {}, ignoring", id + i);
4815 ChangeInfoResult cir = IgnoreRoadStopProperty(prop, buf);
4816 if (cir > ret) ret = cir;
4817 continue;
4818 }
4819
4820 switch (prop) {
4821 case 0x08: { // Road Stop Class ID
4822 if (rs == nullptr) {
4823 _cur.grffile->roadstops[id + i] = std::make_unique<RoadStopSpec>();
4824 rs = _cur.grffile->roadstops[id + i].get();
4825 }
4826
4827 uint32_t classid = buf->ReadDWord();
4828 rs->cls_id = RoadStopClass::Allocate(BSWAP32(classid));
4829 rs->spec_id = id + i;
4830 break;
4831 }
4832
4833 case 0x09: // Road stop type
4834 rs->stop_type = (RoadStopAvailabilityType)buf->ReadByte();
4835 break;
4836
4837 case 0x0A: // Road Stop Name
4838 AddStringForMapping(buf->ReadWord(), &rs->name);
4839 break;
4840
4841 case 0x0B: // Road Stop Class name
4842 AddStringForMapping(buf->ReadWord(), &RoadStopClass::Get(rs->cls_id)->name);
4843 break;
4844
4845 case 0x0C: // The draw mode
4846 rs->draw_mode = (RoadStopDrawMode)buf->ReadByte();
4847 break;
4848
4849 case 0x0D: // Cargo types for random triggers
4850 rs->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
4851 break;
4852
4853 case 0x0E: // Animation info
4854 rs->animation.frames = buf->ReadByte();
4855 rs->animation.status = buf->ReadByte();
4856 break;
4857
4858 case 0x0F: // Animation speed
4859 rs->animation.speed = buf->ReadByte();
4860 break;
4861
4862 case 0x10: // Animation triggers
4863 rs->animation.triggers = buf->ReadWord();
4864 break;
4865
4866 case 0x11: // Callback mask
4867 rs->callback_mask = buf->ReadByte();
4868 break;
4869
4870 case 0x12: // General flags
4871 rs->flags = (uint8_t)buf->ReadDWord(); // Future-proofing, size this as 4 bytes, but we only need one byte's worth of flags at present
4872 break;
4873
4874 case 0x15: // Cost multipliers
4875 rs->build_cost_multiplier = buf->ReadByte();
4876 rs->clear_cost_multiplier = buf->ReadByte();
4877 break;
4878
4879 default:
4880 ret = CIR_UNKNOWN;
4881 break;
4882 }
4883 }
4884
4885 return ret;
4886 }
4887
4888 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8_t feature, uint8_t property)
4889 {
4890 switch (cir) {
4891 default: NOT_REACHED();
4892
4893 case CIR_DISABLED:
4894 /* Error has already been printed; just stop parsing */
4895 return true;
4896
4897 case CIR_SUCCESS:
4898 return false;
4899
4900 case CIR_UNHANDLED:
4901 GrfMsg(1, "{}: Ignoring property 0x{:02X} of feature 0x{:02X} (not implemented)", caller, property, feature);
4902 return false;
4903
4904 case CIR_UNKNOWN:
4905 GrfMsg(0, "{}: Unknown property 0x{:02X} of feature 0x{:02X}, disabling", caller, property, feature);
4906 [[fallthrough]];
4907
4908 case CIR_INVALID_ID: {
4909 /* No debug message for an invalid ID, as it has already been output */
4910 GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4911 if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4912 return true;
4913 }
4914 }
4915 }
4916
4917 /* Action 0x00 */
4918 static void FeatureChangeInfo(ByteReader *buf)
4919 {
4920 /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4921 *
4922 * B feature
4923 * B num-props how many properties to change per vehicle/station
4924 * B num-info how many vehicles/stations to change
4925 * E id ID of first vehicle/station to change, if num-info is
4926 * greater than one, this one and the following
4927 * vehicles/stations will be changed
4928 * B property what property to change, depends on the feature
4929 * V new-info new bytes of info (variable size; depends on properties) */
4930
4931 static const VCI_Handler handler[] = {
4932 /* GSF_TRAINS */ RailVehicleChangeInfo,
4933 /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4934 /* GSF_SHIPS */ ShipVehicleChangeInfo,
4935 /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4936 /* GSF_STATIONS */ StationChangeInfo,
4937 /* GSF_CANALS */ CanalChangeInfo,
4938 /* GSF_BRIDGES */ BridgeChangeInfo,
4939 /* GSF_HOUSES */ TownHouseChangeInfo,
4940 /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4941 /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4942 /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4943 /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4944 /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4945 /* GSF_AIRPORTS */ AirportChangeInfo,
4946 /* GSF_SIGNALS */ nullptr,
4947 /* GSF_OBJECTS */ ObjectChangeInfo,
4948 /* GSF_RAILTYPES */ RailTypeChangeInfo,
4949 /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4950 /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4951 /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4952 /* GSF_ROADSTOPS */ RoadStopChangeInfo,
4953 };
4954 static_assert(GSF_END == lengthof(handler));
4955
4956 uint8_t feature = buf->ReadByte();
4957 uint8_t numprops = buf->ReadByte();
4958 uint numinfo = buf->ReadByte();
4959 uint engine = buf->ReadExtendedByte();
4960
4961 if (feature >= GSF_END) {
4962 GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4963 return;
4964 }
4965
4966 GrfMsg(6, "FeatureChangeInfo: Feature 0x{:02X}, {} properties, to apply to {}+{}",
4967 feature, numprops, engine, numinfo);
4968
4969 if (handler[feature] == nullptr) {
4970 if (feature != GSF_CARGOES) GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4971 return;
4972 }
4973
4974 /* Mark the feature as used by the grf */
4975 SetBit(_cur.grffile->grf_features, feature);
4976
4977 while (numprops-- && buf->HasData()) {
4978 uint8_t prop = buf->ReadByte();
4979
4980 ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4981 if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4982 }
4983 }
4984
4985 /* Action 0x00 (GLS_SAFETYSCAN) */
4986 static void SafeChangeInfo(ByteReader *buf)
4987 {
4988 uint8_t feature = buf->ReadByte();
4989 uint8_t numprops = buf->ReadByte();
4990 uint numinfo = buf->ReadByte();
4991 buf->ReadExtendedByte(); // id
4992
4993 if (feature == GSF_BRIDGES && numprops == 1) {
4994 uint8_t prop = buf->ReadByte();
4995 /* Bridge property 0x0D is redefinition of sprite layout tables, which
4996 * is considered safe. */
4997 if (prop == 0x0D) return;
4998 } else if (feature == GSF_GLOBALVAR && numprops == 1) {
4999 uint8_t prop = buf->ReadByte();
5000 /* Engine ID Mappings are safe, if the source is static */
5001 if (prop == 0x11) {
5002 bool is_safe = true;
5003 for (uint i = 0; i < numinfo; i++) {
5004 uint32_t s = buf->ReadDWord();
5005 buf->ReadDWord(); // dest
5006 const GRFConfig *grfconfig = GetGRFConfig(s);
5007 if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
5008 is_safe = false;
5009 break;
5010 }
5011 }
5012 if (is_safe) return;
5013 }
5014 }
5015
5016 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
5017
5018 /* Skip remainder of GRF */
5019 _cur.skip_sprites = -1;
5020 }
5021
5022 /* Action 0x00 (GLS_RESERVE) */
5023 static void ReserveChangeInfo(ByteReader *buf)
5024 {
5025 uint8_t feature = buf->ReadByte();
5026
5027 if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
5028
5029 uint8_t numprops = buf->ReadByte();
5030 uint8_t numinfo = buf->ReadByte();
5031 uint8_t index = buf->ReadExtendedByte();
5032
5033 while (numprops-- && buf->HasData()) {
5034 uint8_t prop = buf->ReadByte();
5035 ChangeInfoResult cir = CIR_SUCCESS;
5036
5037 switch (feature) {
5038 default: NOT_REACHED();
5039 case GSF_CARGOES:
5040 cir = CargoChangeInfo(index, numinfo, prop, buf);
5041 break;
5042
5043 case GSF_GLOBALVAR:
5044 cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
5045 break;
5046
5047 case GSF_RAILTYPES:
5048 cir = RailTypeReserveInfo(index, numinfo, prop, buf);
5049 break;
5050
5051 case GSF_ROADTYPES:
5052 cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
5053 break;
5054
5055 case GSF_TRAMTYPES:
5056 cir = TramTypeReserveInfo(index, numinfo, prop, buf);
5057 break;
5058 }
5059
5060 if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
5061 }
5062 }
5063
5064 /* Action 0x01 */
5065 static void NewSpriteSet(ByteReader *buf)
5066 {
5067 /* Basic format: <01> <feature> <num-sets> <num-ent>
5068 * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
5069 *
5070 * B feature feature to define sprites for
5071 * 0, 1, 2, 3: veh-type, 4: train stations
5072 * E first-set first sprite set to define
5073 * B num-sets number of sprite sets (extended byte in extended format)
5074 * E num-ent how many entries per sprite set
5075 * For vehicles, this is the number of different
5076 * vehicle directions in each sprite set
5077 * Set num-dirs=8, unless your sprites are symmetric.
5078 * In that case, use num-dirs=4.
5079 */
5080
5081 uint8_t feature = buf->ReadByte();
5082 uint16_t num_sets = buf->ReadByte();
5083 uint16_t first_set = 0;
5084
5085 if (num_sets == 0 && buf->HasData(3)) {
5086 /* Extended Action1 format.
5087 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5088 first_set = buf->ReadExtendedByte();
5089 num_sets = buf->ReadExtendedByte();
5090 }
5091 uint16_t num_ents = buf->ReadExtendedByte();
5092
5093 if (feature >= GSF_END) {
5094 _cur.skip_sprites = num_sets * num_ents;
5095 GrfMsg(1, "NewSpriteSet: Unsupported feature 0x{:02X}, skipping {} sprites", feature, _cur.skip_sprites);
5096 return;
5097 }
5098
5099 _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
5100
5101 GrfMsg(7, "New sprite set at {} of feature 0x{:02X}, consisting of {} sets with {} views each (total {})",
5102 _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
5103 );
5104
5105 for (int i = 0; i < num_sets * num_ents; i++) {
5106 _cur.nfo_line++;
5107 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
5108 }
5109 }
5110
5111 /* Action 0x01 (SKIP) */
5112 static void SkipAct1(ByteReader *buf)
5113 {
5114 buf->ReadByte();
5115 uint16_t num_sets = buf->ReadByte();
5116
5117 if (num_sets == 0 && buf->HasData(3)) {
5118 /* Extended Action1 format.
5119 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5120 buf->ReadExtendedByte(); // first_set
5121 num_sets = buf->ReadExtendedByte();
5122 }
5123 uint16_t num_ents = buf->ReadExtendedByte();
5124
5125 _cur.skip_sprites = num_sets * num_ents;
5126
5127 GrfMsg(3, "SkipAct1: Skipping {} sprites", _cur.skip_sprites);
5128 }
5129
5130 /* Helper function to either create a callback or link to a previously
5131 * defined spritegroup. */
5132 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16_t groupid)
5133 {
5134 if (HasBit(groupid, 15)) {
5135 assert(CallbackResultSpriteGroup::CanAllocateItem());
5136 return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
5137 }
5138
5139 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5140 GrfMsg(1, "GetGroupFromGroupID(0x{:02X}:0x{:02X}): Groupid 0x{:04X} does not exist, leaving empty", setid, type, groupid);
5141 return nullptr;
5142 }
5143
5144 return _cur.spritegroups[groupid];
5145 }
5146
5155 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16_t spriteid)
5156 {
5157 if (HasBit(spriteid, 15)) {
5158 assert(CallbackResultSpriteGroup::CanAllocateItem());
5159 return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
5160 }
5161
5162 if (!_cur.IsValidSpriteSet(feature, spriteid)) {
5163 GrfMsg(1, "CreateGroupFromGroupID(0x{:02X}:0x{:02X}): Sprite set {} invalid", setid, type, spriteid);
5164 return nullptr;
5165 }
5166
5167 SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
5168 uint num_sprites = _cur.GetNumEnts(feature, spriteid);
5169
5170 /* Ensure that the sprites are loeded */
5171 assert(spriteset_start + num_sprites <= _cur.spriteid);
5172
5173 assert(ResultSpriteGroup::CanAllocateItem());
5174 return new ResultSpriteGroup(spriteset_start, num_sprites);
5175 }
5176
5177 /* Action 0x02 */
5178 static void NewSpriteGroup(ByteReader *buf)
5179 {
5180 /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5181 *
5182 * B feature see action 1
5183 * B set-id ID of this particular definition
5184 * B type/num-entries
5185 * if 80 or greater, this is a randomized or variational
5186 * list definition, see below
5187 * otherwise it specifies a number of entries, the exact
5188 * meaning depends on the feature
5189 * V feature-specific-data (huge mess, don't even look it up --pasky) */
5190 const SpriteGroup *act_group = nullptr;
5191
5192 uint8_t feature = buf->ReadByte();
5193 if (feature >= GSF_END) {
5194 GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5195 return;
5196 }
5197
5198 uint8_t setid = buf->ReadByte();
5199 uint8_t type = buf->ReadByte();
5200
5201 /* Sprite Groups are created here but they are allocated from a pool, so
5202 * we do not need to delete anything if there is an exception from the
5203 * ByteReader. */
5204
5205 switch (type) {
5206 /* Deterministic Sprite Group */
5207 case 0x81: // Self scope, byte
5208 case 0x82: // Parent scope, byte
5209 case 0x85: // Self scope, word
5210 case 0x86: // Parent scope, word
5211 case 0x89: // Self scope, dword
5212 case 0x8A: // Parent scope, dword
5213 {
5214 byte varadjust;
5215 byte varsize;
5216
5217 assert(DeterministicSpriteGroup::CanAllocateItem());
5218 DeterministicSpriteGroup *group = new DeterministicSpriteGroup();
5219 group->nfo_line = _cur.nfo_line;
5220 act_group = group;
5221 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5222
5223 switch (GB(type, 2, 2)) {
5224 default: NOT_REACHED();
5225 case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5226 case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5227 case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5228 }
5229
5230 /* Loop through the var adjusts. Unfortunately we don't know how many we have
5231 * from the outset, so we shall have to keep reallocing. */
5232 do {
5233 DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5234
5235 /* The first var adjust doesn't have an operation specified, so we set it to add. */
5236 adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
5237 adjust.variable = buf->ReadByte();
5238 if (adjust.variable == 0x7E) {
5239 /* Link subroutine group */
5240 adjust.subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
5241 } else {
5242 adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf->ReadByte() : 0;
5243 }
5244
5245 varadjust = buf->ReadByte();
5246 adjust.shift_num = GB(varadjust, 0, 5);
5247 adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5248 adjust.and_mask = buf->ReadVarSize(varsize);
5249
5250 if (adjust.type != DSGA_TYPE_NONE) {
5251 adjust.add_val = buf->ReadVarSize(varsize);
5252 adjust.divmod_val = buf->ReadVarSize(varsize);
5253 } else {
5254 adjust.add_val = 0;
5255 adjust.divmod_val = 0;
5256 }
5257
5258 /* Continue reading var adjusts while bit 5 is set. */
5259 } while (HasBit(varadjust, 5));
5260
5261 std::vector<DeterministicSpriteGroupRange> ranges;
5262 ranges.resize(buf->ReadByte());
5263 for (uint i = 0; i < ranges.size(); i++) {
5264 ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5265 ranges[i].low = buf->ReadVarSize(varsize);
5266 ranges[i].high = buf->ReadVarSize(varsize);
5267 }
5268
5269 group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5270 group->error_group = ranges.empty() ? group->default_group : ranges[0].group;
5271 /* nvar == 0 is a special case -- we turn our value into a callback result */
5272 group->calculated_result = ranges.empty();
5273
5274 /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5275 std::vector<uint32_t> bounds;
5276 for (uint i = 0; i < ranges.size(); i++) {
5277 bounds.push_back(ranges[i].low);
5278 if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
5279 }
5280 std::sort(bounds.begin(), bounds.end());
5281 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5282
5283 std::vector<const SpriteGroup *> target;
5284 for (uint j = 0; j < bounds.size(); ++j) {
5285 uint32_t v = bounds[j];
5286 const SpriteGroup *t = group->default_group;
5287 for (uint i = 0; i < ranges.size(); i++) {
5288 if (ranges[i].low <= v && v <= ranges[i].high) {
5289 t = ranges[i].group;
5290 break;
5291 }
5292 }
5293 target.push_back(t);
5294 }
5295 assert(target.size() == bounds.size());
5296
5297 for (uint j = 0; j < bounds.size(); ) {
5298 if (target[j] != group->default_group) {
5299 DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5300 r.group = target[j];
5301 r.low = bounds[j];
5302 while (j < bounds.size() && target[j] == r.group) {
5303 j++;
5304 }
5305 r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5306 } else {
5307 j++;
5308 }
5309 }
5310
5311 break;
5312 }
5313
5314 /* Randomized Sprite Group */
5315 case 0x80: // Self scope
5316 case 0x83: // Parent scope
5317 case 0x84: // Relative scope
5318 {
5319 assert(RandomizedSpriteGroup::CanAllocateItem());
5320 RandomizedSpriteGroup *group = new RandomizedSpriteGroup();
5321 group->nfo_line = _cur.nfo_line;
5322 act_group = group;
5323 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5324
5325 if (HasBit(type, 2)) {
5326 if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5327 group->count = buf->ReadByte();
5328 }
5329
5330 uint8_t triggers = buf->ReadByte();
5331 group->triggers = GB(triggers, 0, 7);
5332 group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5333 group->lowest_randbit = buf->ReadByte();
5334
5335 byte num_groups = buf->ReadByte();
5336 if (!HasExactlyOneBit(num_groups)) {
5337 GrfMsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5338 }
5339
5340 for (uint i = 0; i < num_groups; i++) {
5341 group->groups.push_back(GetGroupFromGroupID(setid, type, buf->ReadWord()));
5342 }
5343
5344 break;
5345 }
5346
5347 /* Neither a variable or randomized sprite group... must be a real group */
5348 default:
5349 {
5350 switch (feature) {
5351 case GSF_TRAINS:
5352 case GSF_ROADVEHICLES:
5353 case GSF_SHIPS:
5354 case GSF_AIRCRAFT:
5355 case GSF_STATIONS:
5356 case GSF_CANALS:
5357 case GSF_CARGOES:
5358 case GSF_AIRPORTS:
5359 case GSF_RAILTYPES:
5360 case GSF_ROADTYPES:
5361 case GSF_TRAMTYPES:
5362 {
5363 byte num_loaded = type;
5364 byte num_loading = buf->ReadByte();
5365
5366 if (!_cur.HasValidSpriteSets(feature)) {
5367 GrfMsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5368 return;
5369 }
5370
5371 GrfMsg(6, "NewSpriteGroup: New SpriteGroup 0x{:02X}, {} loaded, {} loading",
5372 setid, num_loaded, num_loading);
5373
5374 if (num_loaded + num_loading == 0) {
5375 GrfMsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5376 break;
5377 }
5378
5379 if (num_loaded + num_loading == 1) {
5380 /* Avoid creating 'Real' sprite group if only one option. */
5381 uint16_t spriteid = buf->ReadWord();
5382 act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5383 GrfMsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset {}", spriteid);
5384 break;
5385 }
5386
5387 std::vector<uint16_t> loaded;
5388 std::vector<uint16_t> loading;
5389
5390 for (uint i = 0; i < num_loaded; i++) {
5391 loaded.push_back(buf->ReadWord());
5392 GrfMsg(8, "NewSpriteGroup: + rg->loaded[{}] = subset {}", i, loaded[i]);
5393 }
5394
5395 for (uint i = 0; i < num_loading; i++) {
5396 loading.push_back(buf->ReadWord());
5397 GrfMsg(8, "NewSpriteGroup: + rg->loading[{}] = subset {}", i, loading[i]);
5398 }
5399
5400 if (std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end() &&
5401 std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end() &&
5402 loaded[0] == loading[0])
5403 {
5404 /* Both lists only contain the same value, so don't create 'Real' sprite group */
5405 act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5406 GrfMsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset {}", loaded[0]);
5407 break;
5408 }
5409
5410 assert(RealSpriteGroup::CanAllocateItem());
5411 RealSpriteGroup *group = new RealSpriteGroup();
5412 group->nfo_line = _cur.nfo_line;
5413 act_group = group;
5414
5415 for (uint16_t spriteid : loaded) {
5416 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5417 group->loaded.push_back(t);
5418 }
5419
5420 for (uint16_t spriteid : loading) {
5421 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5422 group->loading.push_back(t);
5423 }
5424
5425 break;
5426 }
5427
5428 case GSF_HOUSES:
5429 case GSF_AIRPORTTILES:
5430 case GSF_OBJECTS:
5431 case GSF_INDUSTRYTILES:
5432 case GSF_ROADSTOPS: {
5433 byte num_building_sprites = std::max((uint8_t)1, type);
5434
5435 assert(TileLayoutSpriteGroup::CanAllocateItem());
5436 TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup();
5437 group->nfo_line = _cur.nfo_line;
5438 act_group = group;
5439
5440 /* On error, bail out immediately. Temporary GRF data was already freed */
5441 if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5442 break;
5443 }
5444
5445 case GSF_INDUSTRIES: {
5446 if (type > 2) {
5447 GrfMsg(1, "NewSpriteGroup: Unsupported industry production version {}, skipping", type);
5448 break;
5449 }
5450
5451 assert(IndustryProductionSpriteGroup::CanAllocateItem());
5452 IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup();
5453 group->nfo_line = _cur.nfo_line;
5454 act_group = group;
5455 group->version = type;
5456 if (type == 0) {
5457 group->num_input = 3;
5458 for (uint i = 0; i < 3; i++) {
5459 group->subtract_input[i] = (int16_t)buf->ReadWord(); // signed
5460 }
5461 group->num_output = 2;
5462 for (uint i = 0; i < 2; i++) {
5463 group->add_output[i] = buf->ReadWord(); // unsigned
5464 }
5465 group->again = buf->ReadByte();
5466 } else if (type == 1) {
5467 group->num_input = 3;
5468 for (uint i = 0; i < 3; i++) {
5469 group->subtract_input[i] = buf->ReadByte();
5470 }
5471 group->num_output = 2;
5472 for (uint i = 0; i < 2; i++) {
5473 group->add_output[i] = buf->ReadByte();
5474 }
5475 group->again = buf->ReadByte();
5476 } else if (type == 2) {
5477 group->num_input = buf->ReadByte();
5478 if (group->num_input > lengthof(group->subtract_input)) {
5479 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5480 error->data = "too many inputs (max 16)";
5481 return;
5482 }
5483 for (uint i = 0; i < group->num_input; i++) {
5484 byte rawcargo = buf->ReadByte();
5485 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5486 if (!IsValidCargoID(cargo)) {
5487 /* The mapped cargo is invalid. This is permitted at this point,
5488 * as long as the result is not used. Mark it invalid so this
5489 * can be tested later. */
5490 group->version = 0xFF;
5491 } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5492 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5493 error->data = "duplicate input cargo";
5494 return;
5495 }
5496 group->cargo_input[i] = cargo;
5497 group->subtract_input[i] = buf->ReadByte();
5498 }
5499 group->num_output = buf->ReadByte();
5500 if (group->num_output > lengthof(group->add_output)) {
5501 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5502 error->data = "too many outputs (max 16)";
5503 return;
5504 }
5505 for (uint i = 0; i < group->num_output; i++) {
5506 byte rawcargo = buf->ReadByte();
5507 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5508 if (!IsValidCargoID(cargo)) {
5509 /* Mark this result as invalid to use */
5510 group->version = 0xFF;
5511 } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5512 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5513 error->data = "duplicate output cargo";
5514 return;
5515 }
5516 group->cargo_output[i] = cargo;
5517 group->add_output[i] = buf->ReadByte();
5518 }
5519 group->again = buf->ReadByte();
5520 } else {
5521 NOT_REACHED();
5522 }
5523 break;
5524 }
5525
5526 /* Loading of Tile Layout and Production Callback groups would happen here */
5527 default: GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5528 }
5529 }
5530 }
5531
5532 _cur.spritegroups[setid] = act_group;
5533 }
5534
5535 static CargoID TranslateCargo(uint8_t feature, uint8_t ctype)
5536 {
5537 /* Special cargo types for purchase list and stations */
5538 if ((feature == GSF_STATIONS || feature == GSF_ROADSTOPS) && ctype == 0xFE) return SpriteGroupCargo::SG_DEFAULT_NA;
5539 if (ctype == 0xFF) return SpriteGroupCargo::SG_PURCHASE;
5540
5541 if (_cur.grffile->cargo_list.empty()) {
5542 /* No cargo table, so use bitnum values */
5543 if (ctype >= 32) {
5544 GrfMsg(1, "TranslateCargo: Cargo bitnum {} out of range (max 31), skipping.", ctype);
5545 return INVALID_CARGO;
5546 }
5547
5548 for (const CargoSpec *cs : CargoSpec::Iterate()) {
5549 if (cs->bitnum == ctype) {
5550 GrfMsg(6, "TranslateCargo: Cargo bitnum {} mapped to cargo type {}.", ctype, cs->Index());
5551 return cs->Index();
5552 }
5553 }
5554
5555 GrfMsg(5, "TranslateCargo: Cargo bitnum {} not available in this climate, skipping.", ctype);
5556 return INVALID_CARGO;
5557 }
5558
5559 /* Check if the cargo type is out of bounds of the cargo translation table */
5560 if (ctype >= _cur.grffile->cargo_list.size()) {
5561 GrfMsg(1, "TranslateCargo: Cargo type {} out of range (max {}), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5562 return INVALID_CARGO;
5563 }
5564
5565 /* Look up the cargo label from the translation table */
5566 CargoLabel cl = _cur.grffile->cargo_list[ctype];
5567 if (cl == 0) {
5568 GrfMsg(5, "TranslateCargo: Cargo type {} not available in this climate, skipping.", ctype);
5569 return INVALID_CARGO;
5570 }
5571
5572 CargoID cid = GetCargoIDByLabel(cl);
5573 if (!IsValidCargoID(cid)) {
5574 GrfMsg(5, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' unsupported, skipping.", GB(cl, 24, 8), GB(cl, 16, 8), GB(cl, 8, 8), GB(cl, 0, 8));
5575 return INVALID_CARGO;
5576 }
5577
5578 GrfMsg(6, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' mapped to cargo type {}.", GB(cl, 24, 8), GB(cl, 16, 8), GB(cl, 8, 8), GB(cl, 0, 8), cid);
5579 return cid;
5580 }
5581
5582
5583 static bool IsValidGroupID(uint16_t groupid, const char *function)
5584 {
5585 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5586 GrfMsg(1, "{}: Spritegroup 0x{:04X} out of range or empty, skipping.", function, groupid);
5587 return false;
5588 }
5589
5590 return true;
5591 }
5592
5593 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8_t idcount)
5594 {
5595 static EngineID *last_engines;
5596 static uint last_engines_count;
5597 bool wagover = false;
5598
5599 /* Test for 'wagon override' flag */
5600 if (HasBit(idcount, 7)) {
5601 wagover = true;
5602 /* Strip off the flag */
5603 idcount = GB(idcount, 0, 7);
5604
5605 if (last_engines_count == 0) {
5606 GrfMsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5607 return;
5608 }
5609
5610 GrfMsg(6, "VehicleMapSpriteGroup: WagonOverride: {} engines, {} wagons",
5611 last_engines_count, idcount);
5612 } else {
5613 if (last_engines_count != idcount) {
5614 last_engines = ReallocT(last_engines, idcount);
5615 last_engines_count = idcount;
5616 }
5617 }
5618
5619 std::vector<EngineID> engines;
5620 for (uint i = 0; i < idcount; i++) {
5621 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5622 if (e == nullptr) {
5623 /* No engine could be allocated?!? Deal with it. Okay,
5624 * this might look bad. Also make sure this NewGRF
5625 * gets disabled, as a half loaded one is bad. */
5626 HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5627 return;
5628 }
5629
5630 engines.push_back(e->index);
5631 if (!wagover) last_engines[i] = engines[i];
5632 }
5633
5634 uint8_t cidcount = buf->ReadByte();
5635 for (uint c = 0; c < cidcount; c++) {
5636 uint8_t ctype = buf->ReadByte();
5637 uint16_t groupid = buf->ReadWord();
5638 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5639
5640 GrfMsg(8, "VehicleMapSpriteGroup: * [{}] Cargo type 0x{:X}, group id 0x{:02X}", c, ctype, groupid);
5641
5642 CargoID cid = TranslateCargo(feature, ctype);
5643 if (!IsValidCargoID(cid)) continue;
5644
5645 for (uint i = 0; i < idcount; i++) {
5646 EngineID engine = engines[i];
5647
5648 GrfMsg(7, "VehicleMapSpriteGroup: [{}] Engine {}...", i, engine);
5649
5650 if (wagover) {
5651 SetWagonOverrideSprites(engine, cid, _cur.spritegroups[groupid], last_engines, last_engines_count);
5652 } else {
5653 SetCustomEngineSprites(engine, cid, _cur.spritegroups[groupid]);
5654 }
5655 }
5656 }
5657
5658 uint16_t groupid = buf->ReadWord();
5659 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5660
5661 GrfMsg(8, "-- Default group id 0x{:04X}", groupid);
5662
5663 for (uint i = 0; i < idcount; i++) {
5664 EngineID engine = engines[i];
5665
5666 if (wagover) {
5667 SetWagonOverrideSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5668 } else {
5669 SetCustomEngineSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid]);
5670 SetEngineGRF(engine, _cur.grffile);
5671 }
5672 }
5673 }
5674
5675
5676 static void CanalMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5677 {
5678 std::vector<uint16_t> cfs;
5679 cfs.reserve(idcount);
5680 for (uint i = 0; i < idcount; i++) {
5681 cfs.push_back(buf->ReadExtendedByte());
5682 }
5683
5684 uint8_t cidcount = buf->ReadByte();
5685 buf->Skip(cidcount * 3);
5686
5687 uint16_t groupid = buf->ReadWord();
5688 if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5689
5690 for (auto &cf : cfs) {
5691 if (cf >= CF_END) {
5692 GrfMsg(1, "CanalMapSpriteGroup: Canal subset {} out of range, skipping", cf);
5693 continue;
5694 }
5695
5696 _water_feature[cf].grffile = _cur.grffile;
5697 _water_feature[cf].group = _cur.spritegroups[groupid];
5698 }
5699 }
5700
5701
5702 static void StationMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5703 {
5704 if (_cur.grffile->stations.empty()) {
5705 GrfMsg(1, "StationMapSpriteGroup: No stations defined, skipping");
5706 return;
5707 }
5708
5709 std::vector<uint16_t> stations;
5710 stations.reserve(idcount);
5711 for (uint i = 0; i < idcount; i++) {
5712 stations.push_back(buf->ReadExtendedByte());
5713 }
5714
5715 uint8_t cidcount = buf->ReadByte();
5716 for (uint c = 0; c < cidcount; c++) {
5717 uint8_t ctype = buf->ReadByte();
5718 uint16_t groupid = buf->ReadWord();
5719 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5720
5721 ctype = TranslateCargo(GSF_STATIONS, ctype);
5722 if (!IsValidCargoID(ctype)) continue;
5723
5724 for (auto &station : stations) {
5725 StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5726
5727 if (statspec == nullptr) {
5728 GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5729 continue;
5730 }
5731
5732 statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5733 }
5734 }
5735
5736 uint16_t groupid = buf->ReadWord();
5737 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5738
5739 for (auto &station : stations) {
5740 StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5741
5742 if (statspec == nullptr) {
5743 GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5744 continue;
5745 }
5746
5747 if (statspec->grf_prop.grffile != nullptr) {
5748 GrfMsg(1, "StationMapSpriteGroup: Station {} mapped multiple times, skipping", station);
5749 continue;
5750 }
5751
5752 statspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
5753 statspec->grf_prop.grffile = _cur.grffile;
5754 statspec->grf_prop.local_id = station;
5755 StationClass::Assign(statspec);
5756 }
5757 }
5758
5759
5760 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5761 {
5762 if (_cur.grffile->housespec.empty()) {
5763 GrfMsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5764 return;
5765 }
5766
5767 std::vector<uint16_t> houses;
5768 houses.reserve(idcount);
5769 for (uint i = 0; i < idcount; i++) {
5770 houses.push_back(buf->ReadExtendedByte());
5771 }
5772
5773 /* Skip the cargo type section, we only care about the default group */
5774 uint8_t cidcount = buf->ReadByte();
5775 buf->Skip(cidcount * 3);
5776
5777 uint16_t groupid = buf->ReadWord();
5778 if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5779
5780 for (auto &house : houses) {
5781 HouseSpec *hs = house >= _cur.grffile->housespec.size() ? nullptr : _cur.grffile->housespec[house].get();
5782
5783 if (hs == nullptr) {
5784 GrfMsg(1, "TownHouseMapSpriteGroup: House {} undefined, skipping.", house);
5785 continue;
5786 }
5787
5788 hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5789 }
5790 }
5791
5792 static void IndustryMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5793 {
5794 if (_cur.grffile->industryspec.empty()) {
5795 GrfMsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5796 return;
5797 }
5798
5799 std::vector<uint16_t> industries;
5800 industries.reserve(idcount);
5801 for (uint i = 0; i < idcount; i++) {
5802 industries.push_back(buf->ReadExtendedByte());
5803 }
5804
5805 /* Skip the cargo type section, we only care about the default group */
5806 uint8_t cidcount = buf->ReadByte();
5807 buf->Skip(cidcount * 3);
5808
5809 uint16_t groupid = buf->ReadWord();
5810 if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5811
5812 for (auto &industry : industries) {
5813 IndustrySpec *indsp = industry >= _cur.grffile->industryspec.size() ? nullptr : _cur.grffile->industryspec[industry].get();
5814
5815 if (indsp == nullptr) {
5816 GrfMsg(1, "IndustryMapSpriteGroup: Industry {} undefined, skipping", industry);
5817 continue;
5818 }
5819
5820 indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5821 }
5822 }
5823
5824 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5825 {
5826 if (_cur.grffile->indtspec.empty()) {
5827 GrfMsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5828 return;
5829 }
5830
5831 std::vector<uint16_t> indtiles;
5832 indtiles.reserve(idcount);
5833 for (uint i = 0; i < idcount; i++) {
5834 indtiles.push_back(buf->ReadExtendedByte());
5835 }
5836
5837 /* Skip the cargo type section, we only care about the default group */
5838 uint8_t cidcount = buf->ReadByte();
5839 buf->Skip(cidcount * 3);
5840
5841 uint16_t groupid = buf->ReadWord();
5842 if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5843
5844 for (auto &indtile : indtiles) {
5845 IndustryTileSpec *indtsp = indtile >= _cur.grffile->indtspec.size() ? nullptr : _cur.grffile->indtspec[indtile].get();
5846
5847 if (indtsp == nullptr) {
5848 GrfMsg(1, "IndustrytileMapSpriteGroup: Industry tile {} undefined, skipping", indtile);
5849 continue;
5850 }
5851
5852 indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5853 }
5854 }
5855
5856 static void CargoMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5857 {
5858 std::vector<uint16_t> cargoes;
5859 cargoes.reserve(idcount);
5860 for (uint i = 0; i < idcount; i++) {
5861 cargoes.push_back(buf->ReadExtendedByte());
5862 }
5863
5864 /* Skip the cargo type section, we only care about the default group */
5865 uint8_t cidcount = buf->ReadByte();
5866 buf->Skip(cidcount * 3);
5867
5868 uint16_t groupid = buf->ReadWord();
5869 if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5870
5871 for (auto &cid : cargoes) {
5872 if (cid >= NUM_CARGO) {
5873 GrfMsg(1, "CargoMapSpriteGroup: Cargo ID {} out of range, skipping", cid);
5874 continue;
5875 }
5876
5877 CargoSpec *cs = CargoSpec::Get(cid);
5878 cs->grffile = _cur.grffile;
5879 cs->group = _cur.spritegroups[groupid];
5880 }
5881 }
5882
5883 static void ObjectMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5884 {
5885 if (_cur.grffile->objectspec.empty()) {
5886 GrfMsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5887 return;
5888 }
5889
5890 std::vector<uint16_t> objects;
5891 objects.reserve(idcount);
5892 for (uint i = 0; i < idcount; i++) {
5893 objects.push_back(buf->ReadExtendedByte());
5894 }
5895
5896 uint8_t cidcount = buf->ReadByte();
5897 for (uint c = 0; c < cidcount; c++) {
5898 uint8_t ctype = buf->ReadByte();
5899 uint16_t groupid = buf->ReadWord();
5900 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5901
5902 /* The only valid option here is purchase list sprite groups. */
5903 if (ctype != 0xFF) {
5904 GrfMsg(1, "ObjectMapSpriteGroup: Invalid cargo bitnum {} for objects, skipping.", ctype);
5905 continue;
5906 }
5907
5908 for (auto &object : objects) {
5909 ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5910
5911 if (spec == nullptr) {
5912 GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5913 continue;
5914 }
5915
5916 spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_PURCHASE] = _cur.spritegroups[groupid];
5917 }
5918 }
5919
5920 uint16_t groupid = buf->ReadWord();
5921 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5922
5923 for (auto &object : objects) {
5924 ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5925
5926 if (spec == nullptr) {
5927 GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5928 continue;
5929 }
5930
5931 if (spec->grf_prop.grffile != nullptr) {
5932 GrfMsg(1, "ObjectMapSpriteGroup: Object {} mapped multiple times, skipping", object);
5933 continue;
5934 }
5935
5936 spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_DEFAULT] = _cur.spritegroups[groupid];
5937 spec->grf_prop.grffile = _cur.grffile;
5938 spec->grf_prop.local_id = object;
5939 }
5940 }
5941
5942 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5943 {
5944 std::vector<uint8_t> railtypes;
5945 railtypes.reserve(idcount);
5946 for (uint i = 0; i < idcount; i++) {
5947 uint16_t id = buf->ReadExtendedByte();
5948 railtypes.push_back(id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE);
5949 }
5950
5951 uint8_t cidcount = buf->ReadByte();
5952 for (uint c = 0; c < cidcount; c++) {
5953 uint8_t ctype = buf->ReadByte();
5954 uint16_t groupid = buf->ReadWord();
5955 if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5956
5957 if (ctype >= RTSG_END) continue;
5958
5959 extern RailTypeInfo _railtypes[RAILTYPE_END];
5960 for (auto &railtype : railtypes) {
5961 if (railtype != INVALID_RAILTYPE) {
5962 RailTypeInfo *rti = &_railtypes[railtype];
5963
5964 rti->grffile[ctype] = _cur.grffile;
5965 rti->group[ctype] = _cur.spritegroups[groupid];
5966 }
5967 }
5968 }
5969
5970 /* Railtypes do not use the default group. */
5971 buf->ReadWord();
5972 }
5973
5974 static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8_t idcount, RoadTramType rtt)
5975 {
5976 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5977
5978 std::vector<uint8_t> roadtypes;
5979 roadtypes.reserve(idcount);
5980 for (uint i = 0; i < idcount; i++) {
5981 uint16_t id = buf->ReadExtendedByte();
5982 roadtypes.push_back(id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE);
5983 }
5984
5985 uint8_t cidcount = buf->ReadByte();
5986 for (uint c = 0; c < cidcount; c++) {
5987 uint8_t ctype = buf->ReadByte();
5988 uint16_t groupid = buf->ReadWord();
5989 if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
5990
5991 if (ctype >= ROTSG_END) continue;
5992
5993 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
5994 for (auto &roadtype : roadtypes) {
5995 if (roadtype != INVALID_ROADTYPE) {
5996 RoadTypeInfo *rti = &_roadtypes[roadtype];
5997
5998 rti->grffile[ctype] = _cur.grffile;
5999 rti->group[ctype] = _cur.spritegroups[groupid];
6000 }
6001 }
6002 }
6003
6004 /* Roadtypes do not use the default group. */
6005 buf->ReadWord();
6006 }
6007
6008 static void AirportMapSpriteGroup(ByteReader *buf, uint8_t idcount)
6009 {
6010 if (_cur.grffile->airportspec.empty()) {
6011 GrfMsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
6012 return;
6013 }
6014
6015 std::vector<uint16_t> airports;
6016 airports.reserve(idcount);
6017 for (uint i = 0; i < idcount; i++) {
6018 airports.push_back(buf->ReadExtendedByte());
6019 }
6020
6021 /* Skip the cargo type section, we only care about the default group */
6022 uint8_t cidcount = buf->ReadByte();
6023 buf->Skip(cidcount * 3);
6024
6025 uint16_t groupid = buf->ReadWord();
6026 if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
6027
6028 for (auto &airport : airports) {
6029 AirportSpec *as = airport >= _cur.grffile->airportspec.size() ? nullptr : _cur.grffile->airportspec[airport].get();
6030
6031 if (as == nullptr) {
6032 GrfMsg(1, "AirportMapSpriteGroup: Airport {} undefined, skipping", airport);
6033 continue;
6034 }
6035
6036 as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6037 }
6038 }
6039
6040 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8_t idcount)
6041 {
6042 if (_cur.grffile->airtspec.empty()) {
6043 GrfMsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
6044 return;
6045 }
6046
6047 std::vector<uint16_t> airptiles;
6048 airptiles.reserve(idcount);
6049 for (uint i = 0; i < idcount; i++) {
6050 airptiles.push_back(buf->ReadExtendedByte());
6051 }
6052
6053 /* Skip the cargo type section, we only care about the default group */
6054 uint8_t cidcount = buf->ReadByte();
6055 buf->Skip(cidcount * 3);
6056
6057 uint16_t groupid = buf->ReadWord();
6058 if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
6059
6060 for (auto &airptile : airptiles) {
6061 AirportTileSpec *airtsp = airptile >= _cur.grffile->airtspec.size() ? nullptr : _cur.grffile->airtspec[airptile].get();
6062
6063 if (airtsp == nullptr) {
6064 GrfMsg(1, "AirportTileMapSpriteGroup: Airport tile {} undefined, skipping", airptile);
6065 continue;
6066 }
6067
6068 airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6069 }
6070 }
6071
6072 static void RoadStopMapSpriteGroup(ByteReader *buf, uint8_t idcount)
6073 {
6074 if (_cur.grffile->roadstops.empty()) {
6075 GrfMsg(1, "RoadStopMapSpriteGroup: No roadstops defined, skipping");
6076 return;
6077 }
6078
6079 std::vector<uint16_t> roadstops;
6080 roadstops.reserve(idcount);
6081 for (uint i = 0; i < idcount; i++) {
6082 roadstops.push_back(buf->ReadExtendedByte());
6083 }
6084
6085 uint8_t cidcount = buf->ReadByte();
6086 for (uint c = 0; c < cidcount; c++) {
6087 uint8_t ctype = buf->ReadByte();
6088 uint16_t groupid = buf->ReadWord();
6089 if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) continue;
6090
6091 ctype = TranslateCargo(GSF_ROADSTOPS, ctype);
6092 if (!IsValidCargoID(ctype)) continue;
6093
6094 for (auto &roadstop : roadstops) {
6095 RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6096
6097 if (roadstopspec == nullptr) {
6098 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping", roadstop);
6099 continue;
6100 }
6101
6102 roadstopspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
6103 }
6104 }
6105
6106 uint16_t groupid = buf->ReadWord();
6107 if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) return;
6108
6109 for (auto &roadstop : roadstops) {
6110 RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6111
6112 if (roadstopspec == nullptr) {
6113 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping.", roadstop);
6114 continue;
6115 }
6116
6117 if (roadstopspec->grf_prop.grffile != nullptr) {
6118 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} mapped multiple times, skipping", roadstop);
6119 continue;
6120 }
6121
6122 roadstopspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
6123 roadstopspec->grf_prop.grffile = _cur.grffile;
6124 roadstopspec->grf_prop.local_id = roadstop;
6125 RoadStopClass::Assign(roadstopspec);
6126 }
6127 }
6128
6129 /* Action 0x03 */
6130 static void FeatureMapSpriteGroup(ByteReader *buf)
6131 {
6132 /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
6133 * id-list := [<id>] [id-list]
6134 * cargo-list := <cargo-type> <cid> [cargo-list]
6135 *
6136 * B feature see action 0
6137 * B n-id bits 0-6: how many IDs this definition applies to
6138 * bit 7: if set, this is a wagon override definition (see below)
6139 * E ids the IDs for which this definition applies
6140 * B num-cid number of cargo IDs (sprite group IDs) in this definition
6141 * can be zero, in that case the def-cid is used always
6142 * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
6143 * W cid cargo ID (sprite group ID) for this type of cargo
6144 * W def-cid default cargo ID (sprite group ID) */
6145
6146 uint8_t feature = buf->ReadByte();
6147 uint8_t idcount = buf->ReadByte();
6148
6149 if (feature >= GSF_END) {
6150 GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6151 return;
6152 }
6153
6154 /* If idcount is zero, this is a feature callback */
6155 if (idcount == 0) {
6156 /* Skip number of cargo ids? */
6157 buf->ReadByte();
6158 uint16_t groupid = buf->ReadWord();
6159 if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
6160
6161 GrfMsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x{:02X}", feature);
6162
6163 AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
6164 return;
6165 }
6166
6167 /* Mark the feature as used by the grf (generic callbacks do not count) */
6168 SetBit(_cur.grffile->grf_features, feature);
6169
6170 GrfMsg(6, "FeatureMapSpriteGroup: Feature 0x{:02X}, {} ids", feature, idcount);
6171
6172 switch (feature) {
6173 case GSF_TRAINS:
6174 case GSF_ROADVEHICLES:
6175 case GSF_SHIPS:
6176 case GSF_AIRCRAFT:
6177 VehicleMapSpriteGroup(buf, feature, idcount);
6178 return;
6179
6180 case GSF_CANALS:
6181 CanalMapSpriteGroup(buf, idcount);
6182 return;
6183
6184 case GSF_STATIONS:
6185 StationMapSpriteGroup(buf, idcount);
6186 return;
6187
6188 case GSF_HOUSES:
6189 TownHouseMapSpriteGroup(buf, idcount);
6190 return;
6191
6192 case GSF_INDUSTRIES:
6193 IndustryMapSpriteGroup(buf, idcount);
6194 return;
6195
6196 case GSF_INDUSTRYTILES:
6197 IndustrytileMapSpriteGroup(buf, idcount);
6198 return;
6199
6200 case GSF_CARGOES:
6201 CargoMapSpriteGroup(buf, idcount);
6202 return;
6203
6204 case GSF_AIRPORTS:
6205 AirportMapSpriteGroup(buf, idcount);
6206 return;
6207
6208 case GSF_OBJECTS:
6209 ObjectMapSpriteGroup(buf, idcount);
6210 break;
6211
6212 case GSF_RAILTYPES:
6213 RailTypeMapSpriteGroup(buf, idcount);
6214 break;
6215
6216 case GSF_ROADTYPES:
6217 RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
6218 break;
6219
6220 case GSF_TRAMTYPES:
6221 RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
6222 break;
6223
6224 case GSF_AIRPORTTILES:
6225 AirportTileMapSpriteGroup(buf, idcount);
6226 return;
6227
6228 case GSF_ROADSTOPS:
6229 RoadStopMapSpriteGroup(buf, idcount);
6230 return;
6231
6232 default:
6233 GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6234 return;
6235 }
6236 }
6237
6238 /* Action 0x04 */
6239 static void FeatureNewName(ByteReader *buf)
6240 {
6241 /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
6242 *
6243 * B veh-type see action 0 (as 00..07, + 0A
6244 * But IF veh-type = 48, then generic text
6245 * B language-id If bit 6 is set, This is the extended language scheme,
6246 * with up to 64 language.
6247 * Otherwise, it is a mapping where set bits have meaning
6248 * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6249 * Bit 7 set means this is a generic text, not a vehicle one (or else)
6250 * B num-veh number of vehicles which are getting a new name
6251 * B/W offset number of the first vehicle that gets a new name
6252 * Byte : ID of vehicle to change
6253 * Word : ID of string to change/add
6254 * S data new texts, each of them zero-terminated, after
6255 * which the next name begins. */
6256
6257 bool new_scheme = _cur.grffile->grf_version >= 7;
6258
6259 uint8_t feature = buf->ReadByte();
6260 if (feature >= GSF_END && feature != 0x48) {
6261 GrfMsg(1, "FeatureNewName: Unsupported feature 0x{:02X}, skipping", feature);
6262 return;
6263 }
6264
6265 uint8_t lang = buf->ReadByte();
6266 uint8_t num = buf->ReadByte();
6267 bool generic = HasBit(lang, 7);
6268 uint16_t id;
6269 if (generic) {
6270 id = buf->ReadWord();
6271 } else if (feature <= GSF_AIRCRAFT) {
6272 id = buf->ReadExtendedByte();
6273 } else {
6274 id = buf->ReadByte();
6275 }
6276
6277 ClrBit(lang, 7);
6278
6279 uint16_t endid = id + num;
6280
6281 GrfMsg(6, "FeatureNewName: About to rename engines {}..{} (feature 0x{:02X}) in language 0x{:02X}",
6282 id, endid, feature, lang);
6283
6284 for (; id < endid && buf->HasData(); id++) {
6285 const char *name = buf->ReadString();
6286 GrfMsg(8, "FeatureNewName: 0x{:04X} <- {}", id, name);
6287
6288 switch (feature) {
6289 case GSF_TRAINS:
6290 case GSF_ROADVEHICLES:
6291 case GSF_SHIPS:
6292 case GSF_AIRCRAFT:
6293 if (!generic) {
6294 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6295 if (e == nullptr) break;
6296 StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6297 e->info.string_id = string;
6298 } else {
6299 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6300 }
6301 break;
6302
6303 default:
6304 if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0x10000)) {
6305 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6306 break;
6307 }
6308
6309 switch (GB(id, 8, 8)) {
6310 case 0xC4: // Station class name
6311 if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6312 GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6313 } else {
6314 StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
6315 StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6316 }
6317 break;
6318
6319 case 0xC5: // Station name
6320 if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6321 GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6322 } else {
6323 _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6324 }
6325 break;
6326
6327 case 0xC7: // Airporttile name
6328 if (GB(id, 0, 8) >= _cur.grffile->airtspec.size() || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6329 GrfMsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x{:X}, ignoring", GB(id, 0, 8));
6330 } else {
6331 _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6332 }
6333 break;
6334
6335 case 0xC9: // House name
6336 if (GB(id, 0, 8) >= _cur.grffile->housespec.size() || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6337 GrfMsg(1, "FeatureNewName: Attempt to name undefined house 0x{:X}, ignoring.", GB(id, 0, 8));
6338 } else {
6339 _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6340 }
6341 break;
6342
6343 default:
6344 GrfMsg(7, "FeatureNewName: Unsupported ID (0x{:04X})", id);
6345 break;
6346 }
6347 break;
6348 }
6349 }
6350 }
6351
6360 static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const char *name)
6361 {
6362
6363 if (offset >= max_sprites) {
6364 GrfMsg(1, "GraphicsNew: {} sprite offset must be less than {}, skipping", name, max_sprites);
6365 uint orig_num = num;
6366 num = 0;
6367 return orig_num;
6368 }
6369
6370 if (offset + num > max_sprites) {
6371 GrfMsg(4, "GraphicsNew: {} sprite overflow, truncating...", name);
6372 uint orig_num = num;
6373 num = std::max(max_sprites - offset, 0);
6374 return orig_num - num;
6375 }
6376
6377 return 0;
6378 }
6379
6380
6382 enum Action5BlockType {
6383 A5BLOCK_FIXED,
6384 A5BLOCK_ALLOW_OFFSET,
6385 A5BLOCK_INVALID,
6386 };
6388 struct Action5Type {
6389 Action5BlockType block_type;
6390 SpriteID sprite_base;
6391 uint16_t min_sprites;
6392 uint16_t max_sprites;
6393 const char *name;
6394 };
6395
6397 static const Action5Type _action5_types[] = {
6398 /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6399 /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6400 /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6401 /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6402 /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6403 /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6404 /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6405 /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6406 /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6407 /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6408 /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6409 /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6410 /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6411 /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6412 /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6413 /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6414 /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6415 /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6416 /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6417 /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6418 /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6419 /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6420 /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6421 /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6422 /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6423 /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6424 };
6425
6426 /* Action 0x05 */
6427 static void GraphicsNew(ByteReader *buf)
6428 {
6429 /* <05> <graphics-type> <num-sprites> <other data...>
6430 *
6431 * B graphics-type What set of graphics the sprites define.
6432 * E num-sprites How many sprites are in this set?
6433 * V other data Graphics type specific data. Currently unused. */
6434
6435 uint8_t type = buf->ReadByte();
6436 uint16_t num = buf->ReadExtendedByte();
6437 uint16_t offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
6438 ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6439
6440 if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6441 /* Special not-TTDP-compatible case used in openttd.grf
6442 * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6443 GrfMsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6444 LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6445 LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6446 LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6447 LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6448 LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6449 LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6450 LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6451 LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6452 LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6453 LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6454 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
6455 return;
6456 }
6457
6458 /* Supported type? */
6459 if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6460 GrfMsg(2, "GraphicsNew: Custom graphics (type 0x{:02X}) sprite block of length {} (unimplemented, ignoring)", type, num);
6461 _cur.skip_sprites = num;
6462 return;
6463 }
6464
6465 const Action5Type *action5_type = &_action5_types[type];
6466
6467 /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6468 * except for the long version of the shore type:
6469 * Ignore offset if not allowed */
6470 if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6471 GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6472 offset = 0;
6473 }
6474
6475 /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6476 * This does not make sense, if <offset> is allowed */
6477 if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6478 GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) count must be at least {}. Only {} were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num);
6479 _cur.skip_sprites = num;
6480 return;
6481 }
6482
6483 /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6484 uint16_t skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6485 SpriteID replace = action5_type->sprite_base + offset;
6486
6487 /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6488 GrfMsg(2, "GraphicsNew: Replacing sprites {} to {} of {} (type 0x{:02X}) at SpriteID 0x{:04X}", offset, offset + num - 1, action5_type->name, type, replace);
6489
6490 if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
6491
6492 if (type == 0x0B) {
6493 static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6494 static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6495 if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6496 if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6497 }
6498
6499 /* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */
6500 bool dup_oneway_sprites = ((type == 0x09) && (offset + num <= SPR_ONEWAY_SLOPE_N_OFFSET));
6501
6502 for (; num > 0; num--) {
6503 _cur.nfo_line++;
6504 int load_index = (replace == 0 ? _cur.spriteid++ : replace++);
6505 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line);
6506 if (dup_oneway_sprites) {
6507 DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_N_OFFSET);
6508 DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_S_OFFSET);
6509 }
6510 }
6511
6512 _cur.skip_sprites = skip_num;
6513 }
6514
6515 /* Action 0x05 (SKIP) */
6516 static void SkipAct5(ByteReader *buf)
6517 {
6518 /* Ignore type byte */
6519 buf->ReadByte();
6520
6521 /* Skip the sprites of this action */
6522 _cur.skip_sprites = buf->ReadExtendedByte();
6523
6524 GrfMsg(3, "SkipAct5: Skipping {} sprites", _cur.skip_sprites);
6525 }
6526
6538 bool GetGlobalVariable(byte param, uint32_t *value, const GRFFile *grffile)
6539 {
6540 switch (param) {
6541 case 0x00: // current date
6542 *value = std::max(TimerGameCalendar::date - CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR, TimerGameCalendar::Date(0)).base();
6543 return true;
6544
6545 case 0x01: // current year
6546 *value = (Clamp(TimerGameCalendar::year, CalendarTime::ORIGINAL_BASE_YEAR, CalendarTime::ORIGINAL_MAX_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base();
6547 return true;
6548
6549 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)
6550 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date);
6551 TimerGameCalendar::Date start_of_year = TimerGameCalendar::ConvertYMDToDate(ymd.year, 0, 1);
6552 *value = ymd.month | (ymd.day - 1) << 8 | (TimerGameCalendar::IsLeapYear(ymd.year) ? 1 << 15 : 0) | (TimerGameCalendar::date - start_of_year).base() << 16;
6553 return true;
6554 }
6555
6556 case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6557 *value = _settings_game.game_creation.landscape;
6558 return true;
6559
6560 case 0x06: // road traffic side, bit 4 clear=left, set=right
6561 *value = _settings_game.vehicle.road_side << 4;
6562 return true;
6563
6564 case 0x09: // date fraction
6565 *value = TimerGameCalendar::date_fract * 885;
6566 return true;
6567
6568 case 0x0A: // animation counter
6569 *value = GB(TimerGameTick::counter, 0, 16);
6570 return true;
6571
6572 case 0x0B: { // TTDPatch version
6573 uint major = 2;
6574 uint minor = 6;
6575 uint revision = 1; // special case: 2.0.1 is 2.0.10
6576 uint build = 1382;
6577 *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6578 return true;
6579 }
6580
6581 case 0x0D: // TTD Version, 00=DOS, 01=Windows
6582 *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6583 return true;
6584
6585 case 0x0E: // Y-offset for train sprites
6586 *value = _cur.grffile->traininfo_vehicle_pitch;
6587 return true;
6588
6589 case 0x0F: // Rail track type cost factors
6590 *value = 0;
6591 SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6592 if (_settings_game.vehicle.disable_elrails) {
6593 /* skip elrail multiplier - disabled */
6594 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6595 } else {
6596 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6597 /* Skip monorail multiplier - no space in result */
6598 }
6599 SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6600 return true;
6601
6602 case 0x11: // current rail tool type
6603 *value = 0; // constant fake value to avoid desync
6604 return true;
6605
6606 case 0x12: // Game mode
6607 *value = _game_mode;
6608 return true;
6609
6610 /* case 0x13: // Tile refresh offset to left not implemented */
6611 /* case 0x14: // Tile refresh offset to right not implemented */
6612 /* case 0x15: // Tile refresh offset upwards not implemented */
6613 /* case 0x16: // Tile refresh offset downwards not implemented */
6614 /* case 0x17: // temperate snow line not implemented */
6615
6616 case 0x1A: // Always -1
6617 *value = UINT_MAX;
6618 return true;
6619
6620 case 0x1B: // Display options
6621 *value = 0x3F; // constant fake value to avoid desync
6622 return true;
6623
6624 case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6625 *value = 1;
6626 return true;
6627
6628 case 0x1E: // Miscellaneous GRF features
6629 *value = _misc_grf_features;
6630
6631 /* Add the local flags */
6632 assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6633 if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6634 return true;
6635
6636 /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6637
6638 case 0x20: { // snow line height
6639 byte snowline = GetSnowLine();
6640 if (_settings_game.game_creation.landscape == LT_ARCTIC && snowline <= _settings_game.construction.map_height_limit) {
6641 *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6642 } else {
6643 /* No snow */
6644 *value = 0xFF;
6645 }
6646 return true;
6647 }
6648
6649 case 0x21: // OpenTTD version
6650 *value = _openttd_newgrf_version;
6651 return true;
6652
6653 case 0x22: // difficulty level
6654 *value = SP_CUSTOM;
6655 return true;
6656
6657 case 0x23: // long format date
6658 *value = TimerGameCalendar::date.base();
6659 return true;
6660
6661 case 0x24: // long format year
6662 *value = TimerGameCalendar::year.base();
6663 return true;
6664
6665 default: return false;
6666 }
6667 }
6668
6669 static uint32_t GetParamVal(byte param, uint32_t *cond_val)
6670 {
6671 /* First handle variable common with VarAction2 */
6672 uint32_t value;
6673 if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6674
6675
6676 /* Non-common variable */
6677 switch (param) {
6678 case 0x84: { // GRF loading stage
6679 uint32_t res = 0;
6680
6681 if (_cur.stage > GLS_INIT) SetBit(res, 0);
6682 if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6683 if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6684 return res;
6685 }
6686
6687 case 0x85: // TTDPatch flags, only for bit tests
6688 if (cond_val == nullptr) {
6689 /* Supported in Action 0x07 and 0x09, not 0x0D */
6690 return 0;
6691 } else {
6692 uint32_t index = *cond_val / 0x20;
6693 uint32_t param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6694 *cond_val %= 0x20;
6695 return param_val;
6696 }
6697
6698 case 0x88: // GRF ID check
6699 return 0;
6700
6701 /* case 0x99: Global ID offset not implemented */
6702
6703 default:
6704 /* GRF Parameter */
6705 if (param < 0x80) return _cur.grffile->GetParam(param);
6706
6707 /* In-game variable. */
6708 GrfMsg(1, "Unsupported in-game variable 0x{:02X}", param);
6709 return UINT_MAX;
6710 }
6711 }
6712
6713 /* Action 0x06 */
6714 static void CfgApply(ByteReader *buf)
6715 {
6716 /* <06> <param-num> <param-size> <offset> ... <FF>
6717 *
6718 * B param-num Number of parameter to substitute (First = "zero")
6719 * Ignored if that parameter was not specified in newgrf.cfg
6720 * B param-size How many bytes to replace. If larger than 4, the
6721 * bytes of the following parameter are used. In that
6722 * case, nothing is applied unless *all* parameters
6723 * were specified.
6724 * B offset Offset into data from beginning of next sprite
6725 * to place where parameter is to be stored. */
6726
6727 /* Preload the next sprite */
6728 SpriteFile &file = *_cur.file;
6729 size_t pos = file.GetPos();
6730 uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6731 uint8_t type = file.ReadByte();
6732
6733 /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6734 if (type != 0xFF) {
6735 GrfMsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6736
6737 /* Reset the file position to the start of the next sprite */
6738 file.SeekTo(pos, SEEK_SET);
6739 return;
6740 }
6741
6742 /* Get (or create) the override for the next sprite. */
6743 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6744 std::vector<byte> &preload_sprite = _grf_line_to_action6_sprite_override[location];
6745
6746 /* Load new sprite data if it hasn't already been loaded. */
6747 if (preload_sprite.empty()) {
6748 preload_sprite.resize(num);
6749 file.ReadBlock(preload_sprite.data(), num);
6750 }
6751
6752 /* Reset the file position to the start of the next sprite */
6753 file.SeekTo(pos, SEEK_SET);
6754
6755 /* Now perform the Action 0x06 on our data. */
6756 for (;;) {
6757 uint i;
6758 uint param_num;
6759 uint param_size;
6760 uint offset;
6761 bool add_value;
6762
6763 /* Read the parameter to apply. 0xFF indicates no more data to change. */
6764 param_num = buf->ReadByte();
6765 if (param_num == 0xFF) break;
6766
6767 /* Get the size of the parameter to use. If the size covers multiple
6768 * double words, sequential parameter values are used. */
6769 param_size = buf->ReadByte();
6770
6771 /* Bit 7 of param_size indicates we should add to the original value
6772 * instead of replacing it. */
6773 add_value = HasBit(param_size, 7);
6774 param_size = GB(param_size, 0, 7);
6775
6776 /* Where to apply the data to within the pseudo sprite data. */
6777 offset = buf->ReadExtendedByte();
6778
6779 /* If the parameter is a GRF parameter (not an internal variable) check
6780 * if it (and all further sequential parameters) has been defined. */
6781 if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6782 GrfMsg(2, "CfgApply: Ignoring (param {} not set)", (param_num + (param_size - 1) / 4));
6783 break;
6784 }
6785
6786 GrfMsg(8, "CfgApply: Applying {} bytes from parameter 0x{:02X} at offset 0x{:04X}", param_size, param_num, offset);
6787
6788 bool carry = false;
6789 for (i = 0; i < param_size && offset + i < num; i++) {
6790 uint32_t value = GetParamVal(param_num + i / 4, nullptr);
6791 /* Reset carry flag for each iteration of the variable (only really
6792 * matters if param_size is greater than 4) */
6793 if (i % 4 == 0) carry = false;
6794
6795 if (add_value) {
6796 uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6797 preload_sprite[offset + i] = GB(new_value, 0, 8);
6798 /* Check if the addition overflowed */
6799 carry = new_value >= 256;
6800 } else {
6801 preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6802 }
6803 }
6804 }
6805 }
6806
6816 static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
6817 {
6818 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6819 error->data = _cur.grfconfig->GetName();
6820 }
6821
6822 /* Action 0x07
6823 * Action 0x09 */
6824 static void SkipIf(ByteReader *buf)
6825 {
6826 /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6827 *
6828 * B param-num
6829 * B param-size
6830 * B condition-type
6831 * V value
6832 * B num-sprites */
6833 uint32_t cond_val = 0;
6834 uint32_t mask = 0;
6835 bool result;
6836
6837 uint8_t param = buf->ReadByte();
6838 uint8_t paramsize = buf->ReadByte();
6839 uint8_t condtype = buf->ReadByte();
6840
6841 if (condtype < 2) {
6842 /* Always 1 for bit tests, the given value should be ignored. */
6843 paramsize = 1;
6844 }
6845
6846 switch (paramsize) {
6847 case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6848 case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6849 case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6850 case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6851 default: break;
6852 }
6853
6854 if (param < 0x80 && _cur.grffile->param_end <= param) {
6855 GrfMsg(7, "SkipIf: Param {} undefined, skipping test", param);
6856 return;
6857 }
6858
6859 GrfMsg(7, "SkipIf: Test condtype {}, param 0x{:02X}, condval 0x{:08X}", condtype, param, cond_val);
6860
6861 /* condtypes that do not use 'param' are always valid.
6862 * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6863 */
6864 if (condtype >= 0x0B) {
6865 /* Tests that ignore 'param' */
6866 switch (condtype) {
6867 case 0x0B: result = !IsValidCargoID(GetCargoIDByLabel(BSWAP32(cond_val)));
6868 break;
6869 case 0x0C: result = IsValidCargoID(GetCargoIDByLabel(BSWAP32(cond_val)));
6870 break;
6871 case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6872 break;
6873 case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6874 break;
6875 case 0x0F: {
6876 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6877 result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6878 break;
6879 }
6880 case 0x10: {
6881 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6882 result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6883 break;
6884 }
6885 case 0x11: {
6886 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6887 result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6888 break;
6889 }
6890 case 0x12: {
6891 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6892 result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6893 break;
6894 }
6895 default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6896 }
6897 } else if (param == 0x88) {
6898 /* GRF ID checks */
6899
6900 GRFConfig *c = GetGRFConfig(cond_val, mask);
6901
6902 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6903 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
6904 c = nullptr;
6905 }
6906
6907 if (condtype != 10 && c == nullptr) {
6908 GrfMsg(7, "SkipIf: GRFID 0x{:08X} unknown, skipping test", BSWAP32(cond_val));
6909 return;
6910 }
6911
6912 switch (condtype) {
6913 /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6914 case 0x06: // Is GRFID active?
6915 result = c->status == GCS_ACTIVATED;
6916 break;
6917
6918 case 0x07: // Is GRFID non-active?
6919 result = c->status != GCS_ACTIVATED;
6920 break;
6921
6922 case 0x08: // GRFID is not but will be active?
6923 result = c->status == GCS_INITIALISED;
6924 break;
6925
6926 case 0x09: // GRFID is or will be active?
6927 result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6928 break;
6929
6930 case 0x0A: // GRFID is not nor will be active
6931 /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6932 result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6933 break;
6934
6935 default: GrfMsg(1, "SkipIf: Unsupported GRF condition type {:02X}. Ignoring", condtype); return;
6936 }
6937 } else {
6938 /* Tests that use 'param' and are not GRF ID checks. */
6939 uint32_t param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6940 switch (condtype) {
6941 case 0x00: result = !!(param_val & (1 << cond_val));
6942 break;
6943 case 0x01: result = !(param_val & (1 << cond_val));
6944 break;
6945 case 0x02: result = (param_val & mask) == cond_val;
6946 break;
6947 case 0x03: result = (param_val & mask) != cond_val;
6948 break;
6949 case 0x04: result = (param_val & mask) < cond_val;
6950 break;
6951 case 0x05: result = (param_val & mask) > cond_val;
6952 break;
6953 default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6954 }
6955 }
6956
6957 if (!result) {
6958 GrfMsg(2, "SkipIf: Not skipping sprites, test was false");
6959 return;
6960 }
6961
6962 uint8_t numsprites = buf->ReadByte();
6963
6964 /* numsprites can be a GOTO label if it has been defined in the GRF
6965 * file. The jump will always be the first matching label that follows
6966 * the current nfo_line. If no matching label is found, the first matching
6967 * label in the file is used. */
6968 const GRFLabel *choice = nullptr;
6969 for (const auto &label : _cur.grffile->labels) {
6970 if (label.label != numsprites) continue;
6971
6972 /* Remember a goto before the current line */
6973 if (choice == nullptr) choice = &label;
6974 /* If we find a label here, this is definitely good */
6975 if (label.nfo_line > _cur.nfo_line) {
6976 choice = &label;
6977 break;
6978 }
6979 }
6980
6981 if (choice != nullptr) {
6982 GrfMsg(2, "SkipIf: Jumping to label 0x{:X} at line {}, test was true", choice->label, choice->nfo_line);
6983 _cur.file->SeekTo(choice->pos, SEEK_SET);
6984 _cur.nfo_line = choice->nfo_line;
6985 return;
6986 }
6987
6988 GrfMsg(2, "SkipIf: Skipping {} sprites, test was true", numsprites);
6989 _cur.skip_sprites = numsprites;
6990 if (_cur.skip_sprites == 0) {
6991 /* Zero means there are no sprites to skip, so
6992 * we use -1 to indicate that all further
6993 * sprites should be skipped. */
6994 _cur.skip_sprites = -1;
6995
6996 /* If an action 8 hasn't been encountered yet, disable the grf. */
6997 if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6998 DisableGrf();
6999 }
7000 }
7001 }
7002
7003
7004 /* Action 0x08 (GLS_FILESCAN) */
7005 static void ScanInfo(ByteReader *buf)
7006 {
7007 uint8_t grf_version = buf->ReadByte();
7008 uint32_t grfid = buf->ReadDWord();
7009 const char *name = buf->ReadString();
7010
7011 _cur.grfconfig->ident.grfid = grfid;
7012
7013 if (grf_version < 2 || grf_version > 8) {
7014 SetBit(_cur.grfconfig->flags, GCF_INVALID);
7015 Debug(grf, 0, "{}: NewGRF \"{}\" (GRFID {:08X}) uses GRF version {}, which is incompatible with this version of OpenTTD.", _cur.grfconfig->filename, name, BSWAP32(grfid), grf_version);
7016 }
7017
7018 /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
7019 if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
7020
7021 AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
7022
7023 if (buf->HasData()) {
7024 const char *info = buf->ReadString();
7025 AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
7026 }
7027
7028 /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
7029 _cur.skip_sprites = -1;
7030 }
7031
7032 /* Action 0x08 */
7033 static void GRFInfo(ByteReader *buf)
7034 {
7035 /* <08> <version> <grf-id> <name> <info>
7036 *
7037 * B version newgrf version, currently 06
7038 * 4*B grf-id globally unique ID of this .grf file
7039 * S name name of this .grf set
7040 * S info string describing the set, and e.g. author and copyright */
7041
7042 uint8_t version = buf->ReadByte();
7043 uint32_t grfid = buf->ReadDWord();
7044 const char *name = buf->ReadString();
7045
7046 if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
7047 DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
7048 return;
7049 }
7050
7051 if (_cur.grffile->grfid != grfid) {
7052 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));
7053 _cur.grffile->grfid = grfid;
7054 }
7055
7056 _cur.grffile->grf_version = version;
7057 _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
7058
7059 /* Do swap the GRFID for displaying purposes since people expect that */
7060 Debug(grf, 1, "GRFInfo: Loaded GRFv{} set {:08X} - {} (palette: {}, version: {})", version, BSWAP32(grfid), name, (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version);
7061 }
7062
7063 /* Action 0x0A */
7064 static void SpriteReplace(ByteReader *buf)
7065 {
7066 /* <0A> <num-sets> <set1> [<set2> ...]
7067 * <set>: <num-sprites> <first-sprite>
7068 *
7069 * B num-sets How many sets of sprites to replace.
7070 * Each set:
7071 * B num-sprites How many sprites are in this set
7072 * W first-sprite First sprite number to replace */
7073
7074 uint8_t num_sets = buf->ReadByte();
7075
7076 for (uint i = 0; i < num_sets; i++) {
7077 uint8_t num_sprites = buf->ReadByte();
7078 uint16_t first_sprite = buf->ReadWord();
7079
7080 GrfMsg(2, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}",
7081 i, num_sprites, first_sprite
7082 );
7083
7084 for (uint j = 0; j < num_sprites; j++) {
7085 int load_index = first_sprite + j;
7086 _cur.nfo_line++;
7087 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
7088
7089 /* Shore sprites now located at different addresses.
7090 * So detect when the old ones get replaced. */
7091 if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
7092 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
7093 }
7094 }
7095 }
7096 }
7097
7098 /* Action 0x0A (SKIP) */
7099 static void SkipActA(ByteReader *buf)
7100 {
7101 uint8_t num_sets = buf->ReadByte();
7102
7103 for (uint i = 0; i < num_sets; i++) {
7104 /* Skip the sprites this replaces */
7105 _cur.skip_sprites += buf->ReadByte();
7106 /* But ignore where they go */
7107 buf->ReadWord();
7108 }
7109
7110 GrfMsg(3, "SkipActA: Skipping {} sprites", _cur.skip_sprites);
7111 }
7112
7113 /* Action 0x0B */
7114 static void GRFLoadError(ByteReader *buf)
7115 {
7116 /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
7117 *
7118 * B severity 00: notice, continue loading grf file
7119 * 01: warning, continue loading grf file
7120 * 02: error, but continue loading grf file, and attempt
7121 * loading grf again when loading or starting next game
7122 * 03: error, abort loading and prevent loading again in
7123 * the future (only when restarting the patch)
7124 * B language-id see action 4, use 1F for built-in error messages
7125 * B message-id message to show, see below
7126 * S message for custom messages (message-id FF), text of the message
7127 * not present for built-in messages.
7128 * V data additional data for built-in (or custom) messages
7129 * B parnum parameter numbers to be shown in the message (maximum of 2) */
7130
7131 static const StringID msgstr[] = {
7132 STR_NEWGRF_ERROR_VERSION_NUMBER,
7133 STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
7134 STR_NEWGRF_ERROR_UNSET_SWITCH,
7135 STR_NEWGRF_ERROR_INVALID_PARAMETER,
7136 STR_NEWGRF_ERROR_LOAD_BEFORE,
7137 STR_NEWGRF_ERROR_LOAD_AFTER,
7138 STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
7139 };
7140
7141 static const StringID sevstr[] = {
7142 STR_NEWGRF_ERROR_MSG_INFO,
7143 STR_NEWGRF_ERROR_MSG_WARNING,
7144 STR_NEWGRF_ERROR_MSG_ERROR,
7145 STR_NEWGRF_ERROR_MSG_FATAL
7146 };
7147
7148 byte severity = buf->ReadByte();
7149 byte lang = buf->ReadByte();
7150 byte message_id = buf->ReadByte();
7151
7152 /* Skip the error if it isn't valid for the current language. */
7153 if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
7154
7155 /* Skip the error until the activation stage unless bit 7 of the severity
7156 * is set. */
7157 if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
7158 GrfMsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage {}", _cur.stage);
7159 return;
7160 }
7161 ClrBit(severity, 7);
7162
7163 if (severity >= lengthof(sevstr)) {
7164 GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity);
7165 severity = 2;
7166 } else if (severity == 3) {
7167 /* This is a fatal error, so make sure the GRF is deactivated and no
7168 * more of it gets loaded. */
7169 DisableGrf();
7170
7171 /* Make sure we show fatal errors, instead of silly infos from before */
7172 _cur.grfconfig->error.reset();
7173 }
7174
7175 if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
7176 GrfMsg(7, "GRFLoadError: Invalid message id.");
7177 return;
7178 }
7179
7180 if (buf->Remaining() <= 1) {
7181 GrfMsg(7, "GRFLoadError: No message data supplied.");
7182 return;
7183 }
7184
7185 /* For now we can only show one message per newgrf file. */
7186 if (_cur.grfconfig->error.has_value()) return;
7187
7188 _cur.grfconfig->error = {sevstr[severity]};
7189 GRFError *error = &_cur.grfconfig->error.value();
7190
7191 if (message_id == 0xFF) {
7192 /* This is a custom error message. */
7193 if (buf->HasData()) {
7194 const char *message = buf->ReadString();
7195
7196 error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
7197 } else {
7198 GrfMsg(7, "GRFLoadError: No custom message supplied.");
7199 error->custom_message.clear();
7200 }
7201 } else {
7202 error->message = msgstr[message_id];
7203 }
7204
7205 if (buf->HasData()) {
7206 const char *data = buf->ReadString();
7207
7208 error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
7209 } else {
7210 GrfMsg(7, "GRFLoadError: No message data supplied.");
7211 error->data.clear();
7212 }
7213
7214 /* Only two parameter numbers can be used in the string. */
7215 for (uint i = 0; i < error->param_value.size() && buf->HasData(); i++) {
7216 uint param_number = buf->ReadByte();
7217 error->param_value[i] = _cur.grffile->GetParam(param_number);
7218 }
7219 }
7220
7221 /* Action 0x0C */
7222 static void GRFComment(ByteReader *buf)
7223 {
7224 /* <0C> [<ignored...>]
7225 *
7226 * V ignored Anything following the 0C is ignored */
7227
7228 if (!buf->HasData()) return;
7229
7230 const char *text = buf->ReadString();
7231 GrfMsg(2, "GRFComment: {}", text);
7232 }
7233
7234 /* Action 0x0D (GLS_SAFETYSCAN) */
7235 static void SafeParamSet(ByteReader *buf)
7236 {
7237 uint8_t target = buf->ReadByte();
7238
7239 /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
7240 if (target < 0x80 || target == 0x9E) return;
7241
7242 /* GRM could be unsafe, but as here it can only happen after other GRFs
7243 * are loaded, it should be okay. If the GRF tried to use the slots it
7244 * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
7245 * sprites is considered safe. */
7246
7247 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7248
7249 /* Skip remainder of GRF */
7250 _cur.skip_sprites = -1;
7251 }
7252
7253
7254 static uint32_t GetPatchVariable(uint8_t param)
7255 {
7256 switch (param) {
7257 /* start year - 1920 */
7258 case 0x0B: return (std::max(_settings_game.game_creation.starting_year, CalendarTime::ORIGINAL_BASE_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base();
7259
7260 /* freight trains weight factor */
7261 case 0x0E: return _settings_game.vehicle.freight_trains;
7262
7263 /* empty wagon speed increase */
7264 case 0x0F: return 0;
7265
7266 /* plane speed factor; our patch option is reversed from TTDPatch's,
7267 * the following is good for 1x, 2x and 4x (most common?) and...
7268 * well not really for 3x. */
7269 case 0x10:
7270 switch (_settings_game.vehicle.plane_speed) {
7271 default:
7272 case 4: return 1;
7273 case 3: return 2;
7274 case 2: return 2;
7275 case 1: return 4;
7276 }
7277
7278
7279 /* 2CC colourmap base sprite */
7280 case 0x11: return SPR_2CCMAP_BASE;
7281
7282 /* map size: format = -MABXYSS
7283 * M : the type of map
7284 * bit 0 : set : squared map. Bit 1 is now not relevant
7285 * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7286 * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7287 * clear : X is the bigger edge.
7288 * A : minimum edge(log2) of the map
7289 * B : maximum edge(log2) of the map
7290 * XY : edges(log2) of each side of the map.
7291 * SS : combination of both X and Y, thus giving the size(log2) of the map
7292 */
7293 case 0x13: {
7294 byte map_bits = 0;
7295 byte log_X = Map::LogX() - 6; // subtraction is required to make the minimal size (64) zero based
7296 byte log_Y = Map::LogY() - 6;
7297 byte max_edge = std::max(log_X, log_Y);
7298
7299 if (log_X == log_Y) { // we have a squared map, since both edges are identical
7300 SetBit(map_bits, 0);
7301 } else {
7302 if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7303 }
7304
7305 return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7306 (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7307 }
7308
7309 /* The maximum height of the map. */
7310 case 0x14:
7311 return _settings_game.construction.map_height_limit;
7312
7313 /* Extra foundations base sprite */
7314 case 0x15:
7315 return SPR_SLOPES_BASE;
7316
7317 /* Shore base sprite */
7318 case 0x16:
7319 return SPR_SHORE_BASE;
7320
7321 /* Game map seed */
7322 case 0x17:
7323 return _settings_game.game_creation.generation_seed;
7324
7325 default:
7326 GrfMsg(2, "ParamSet: Unknown Patch variable 0x{:02X}.", param);
7327 return 0;
7328 }
7329 }
7330
7331
7332 static uint32_t PerformGRM(uint32_t *grm, uint16_t num_ids, uint16_t count, uint8_t op, uint8_t target, const char *type)
7333 {
7334 uint start = 0;
7335 uint size = 0;
7336
7337 if (op == 6) {
7338 /* Return GRFID of set that reserved ID */
7339 return grm[_cur.grffile->GetParam(target)];
7340 }
7341
7342 /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7343 if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7344
7345 for (uint i = start; i < num_ids; i++) {
7346 if (grm[i] == 0) {
7347 size++;
7348 } else {
7349 if (op == 2 || op == 3) break;
7350 start = i + 1;
7351 size = 0;
7352 }
7353
7354 if (size == count) break;
7355 }
7356
7357 if (size == count) {
7358 /* Got the slot... */
7359 if (op == 0 || op == 3) {
7360 GrfMsg(2, "ParamSet: GRM: Reserving {} {} at {}", count, type, start);
7361 for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7362 }
7363 return start;
7364 }
7365
7366 /* Unable to allocate */
7367 if (op != 4 && op != 5) {
7368 /* Deactivate GRF */
7369 GrfMsg(0, "ParamSet: GRM: Unable to allocate {} {}, deactivating", count, type);
7370 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7371 return UINT_MAX;
7372 }
7373
7374 GrfMsg(1, "ParamSet: GRM: Unable to allocate {} {}", count, type);
7375 return UINT_MAX;
7376 }
7377
7378
7380 static void ParamSet(ByteReader *buf)
7381 {
7382 /* <0D> <target> <operation> <source1> <source2> [<data>]
7383 *
7384 * B target parameter number where result is stored
7385 * B operation operation to perform, see below
7386 * B source1 first source operand
7387 * B source2 second source operand
7388 * D data data to use in the calculation, not necessary
7389 * if both source1 and source2 refer to actual parameters
7390 *
7391 * Operations
7392 * 00 Set parameter equal to source1
7393 * 01 Addition, source1 + source2
7394 * 02 Subtraction, source1 - source2
7395 * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7396 * 04 Signed multiplication, source1 * source2 (both signed)
7397 * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7398 * signed quantity; left shift if positive and right shift if
7399 * negative, source1 is unsigned)
7400 * 06 Signed bit shift, source1 by source2
7401 * (source2 like in 05, and source1 as well)
7402 */
7403
7404 uint8_t target = buf->ReadByte();
7405 uint8_t oper = buf->ReadByte();
7406 uint32_t src1 = buf->ReadByte();
7407 uint32_t src2 = buf->ReadByte();
7408
7409 uint32_t data = 0;
7410 if (buf->Remaining() >= 4) data = buf->ReadDWord();
7411
7412 /* You can add 80 to the operation to make it apply only if the target
7413 * is not defined yet. In this respect, a parameter is taken to be
7414 * defined if any of the following applies:
7415 * - it has been set to any value in the newgrf(w).cfg parameter list
7416 * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7417 * an earlier action D */
7418 if (HasBit(oper, 7)) {
7419 if (target < 0x80 && target < _cur.grffile->param_end) {
7420 GrfMsg(7, "ParamSet: Param {} already defined, skipping", target);
7421 return;
7422 }
7423
7424 oper = GB(oper, 0, 7);
7425 }
7426
7427 if (src2 == 0xFE) {
7428 if (GB(data, 0, 8) == 0xFF) {
7429 if (data == 0x0000FFFF) {
7430 /* Patch variables */
7431 src1 = GetPatchVariable(src1);
7432 } else {
7433 /* GRF Resource Management */
7434 uint8_t op = src1;
7435 uint8_t feature = GB(data, 8, 8);
7436 uint16_t count = GB(data, 16, 16);
7437
7438 if (_cur.stage == GLS_RESERVE) {
7439 if (feature == 0x08) {
7440 /* General sprites */
7441 if (op == 0) {
7442 /* Check if the allocated sprites will fit below the original sprite limit */
7443 if (_cur.spriteid + count >= 16384) {
7444 GrfMsg(0, "ParamSet: GRM: Unable to allocate {} sprites; try changing NewGRF order", count);
7445 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7446 return;
7447 }
7448
7449 /* Reserve space at the current sprite ID */
7450 GrfMsg(4, "ParamSet: GRM: Allocated {} sprites at {}", count, _cur.spriteid);
7451 _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
7452 _cur.spriteid += count;
7453 }
7454 }
7455 /* Ignore GRM result during reservation */
7456 src1 = 0;
7457 } else if (_cur.stage == GLS_ACTIVATION) {
7458 switch (feature) {
7459 case 0x00: // Trains
7460 case 0x01: // Road Vehicles
7461 case 0x02: // Ships
7462 case 0x03: // Aircraft
7463 if (!_settings_game.vehicle.dynamic_engines) {
7464 src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7465 if (_cur.skip_sprites == -1) return;
7466 } else {
7467 /* GRM does not apply for dynamic engine allocation. */
7468 switch (op) {
7469 case 2:
7470 case 3:
7471 src1 = _cur.grffile->GetParam(target);
7472 break;
7473
7474 default:
7475 src1 = 0;
7476 break;
7477 }
7478 }
7479 break;
7480
7481 case 0x08: // General sprites
7482 switch (op) {
7483 case 0:
7484 /* Return space reserved during reservation stage */
7485 src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
7486 GrfMsg(4, "ParamSet: GRM: Using pre-allocated sprites at {}", src1);
7487 break;
7488
7489 case 1:
7490 src1 = _cur.spriteid;
7491 break;
7492
7493 default:
7494 GrfMsg(1, "ParamSet: GRM: Unsupported operation {} for general sprites", op);
7495 return;
7496 }
7497 break;
7498
7499 case 0x0B: // Cargo
7500 /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7501 src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7502 if (_cur.skip_sprites == -1) return;
7503 break;
7504
7505 default: GrfMsg(1, "ParamSet: GRM: Unsupported feature 0x{:X}", feature); return;
7506 }
7507 } else {
7508 /* Ignore GRM during initialization */
7509 src1 = 0;
7510 }
7511 }
7512 } else {
7513 /* Read another GRF File's parameter */
7514 const GRFFile *file = GetFileByGRFID(data);
7515 GRFConfig *c = GetGRFConfig(data);
7516 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7517 /* Disable the read GRF if it is a static NewGRF. */
7518 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
7519 src1 = 0;
7520 } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7521 src1 = 0;
7522 } else if (src1 == 0xFE) {
7523 src1 = c->version;
7524 } else {
7525 src1 = file->GetParam(src1);
7526 }
7527 }
7528 } else {
7529 /* The source1 and source2 operands refer to the grf parameter number
7530 * like in action 6 and 7. In addition, they can refer to the special
7531 * variables available in action 7, or they can be FF to use the value
7532 * of <data>. If referring to parameters that are undefined, a value
7533 * of 0 is used instead. */
7534 src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7535 src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7536 }
7537
7538 uint32_t res;
7539 switch (oper) {
7540 case 0x00:
7541 res = src1;
7542 break;
7543
7544 case 0x01:
7545 res = src1 + src2;
7546 break;
7547
7548 case 0x02:
7549 res = src1 - src2;
7550 break;
7551
7552 case 0x03:
7553 res = src1 * src2;
7554 break;
7555
7556 case 0x04:
7557 res = (int32_t)src1 * (int32_t)src2;
7558 break;
7559
7560 case 0x05:
7561 if ((int32_t)src2 < 0) {
7562 res = src1 >> -(int32_t)src2;
7563 } else {
7564 res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7565 }
7566 break;
7567
7568 case 0x06:
7569 if ((int32_t)src2 < 0) {
7570 res = (int32_t)src1 >> -(int32_t)src2;
7571 } else {
7572 res = (int32_t)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7573 }
7574 break;
7575
7576 case 0x07: // Bitwise AND
7577 res = src1 & src2;
7578 break;
7579
7580 case 0x08: // Bitwise OR
7581 res = src1 | src2;
7582 break;
7583
7584 case 0x09: // Unsigned division
7585 if (src2 == 0) {
7586 res = src1;
7587 } else {
7588 res = src1 / src2;
7589 }
7590 break;
7591
7592 case 0x0A: // Signed division
7593 if (src2 == 0) {
7594 res = src1;
7595 } else {
7596 res = (int32_t)src1 / (int32_t)src2;
7597 }
7598 break;
7599
7600 case 0x0B: // Unsigned modulo
7601 if (src2 == 0) {
7602 res = src1;
7603 } else {
7604 res = src1 % src2;
7605 }
7606 break;
7607
7608 case 0x0C: // Signed modulo
7609 if (src2 == 0) {
7610 res = src1;
7611 } else {
7612 res = (int32_t)src1 % (int32_t)src2;
7613 }
7614 break;
7615
7616 default: GrfMsg(0, "ParamSet: Unknown operation {}, skipping", oper); return;
7617 }
7618
7619 switch (target) {
7620 case 0x8E: // Y-Offset for train sprites
7621 _cur.grffile->traininfo_vehicle_pitch = res;
7622 break;
7623
7624 case 0x8F: { // Rail track type cost factors
7625 extern RailTypeInfo _railtypes[RAILTYPE_END];
7626 _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7627 if (_settings_game.vehicle.disable_elrails) {
7628 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7629 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7630 } else {
7631 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7632 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7633 }
7634 _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7635 break;
7636 }
7637
7638 /* not implemented */
7639 case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7640 case 0x94: // Tile refresh offset to right
7641 case 0x95: // Tile refresh offset upwards
7642 case 0x96: // Tile refresh offset downwards
7643 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
7644 case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7645 GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7646 break;
7647
7648 case 0x9E: // Miscellaneous GRF features
7649 /* Set train list engine width */
7650 _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7651 /* Remove the local flags from the global flags */
7652 ClrBit(res, GMB_TRAIN_WIDTH_32_PIXELS);
7653
7654 /* Only copy safe bits for static grfs */
7655 if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7656 uint32_t safe_bits = 0;
7657 SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7658
7659 _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7660 } else {
7661 _misc_grf_features = res;
7662 }
7663 break;
7664
7665 case 0x9F: // locale-dependent settings
7666 GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7667 break;
7668
7669 default:
7670 if (target < 0x80) {
7671 _cur.grffile->param[target] = res;
7672 /* param is zeroed by default */
7673 if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7674 } else {
7675 GrfMsg(7, "ParamSet: Skipping unknown target 0x{:02X}", target);
7676 }
7677 break;
7678 }
7679 }
7680
7681 /* Action 0x0E (GLS_SAFETYSCAN) */
7682 static void SafeGRFInhibit(ByteReader *buf)
7683 {
7684 /* <0E> <num> <grfids...>
7685 *
7686 * B num Number of GRFIDs that follow
7687 * D grfids GRFIDs of the files to deactivate */
7688
7689 uint8_t num = buf->ReadByte();
7690
7691 for (uint i = 0; i < num; i++) {
7692 uint32_t grfid = buf->ReadDWord();
7693
7694 /* GRF is unsafe it if tries to deactivate other GRFs */
7695 if (grfid != _cur.grfconfig->ident.grfid) {
7696 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7697
7698 /* Skip remainder of GRF */
7699 _cur.skip_sprites = -1;
7700
7701 return;
7702 }
7703 }
7704 }
7705
7706 /* Action 0x0E */
7707 static void GRFInhibit(ByteReader *buf)
7708 {
7709 /* <0E> <num> <grfids...>
7710 *
7711 * B num Number of GRFIDs that follow
7712 * D grfids GRFIDs of the files to deactivate */
7713
7714 uint8_t num = buf->ReadByte();
7715
7716 for (uint i = 0; i < num; i++) {
7717 uint32_t grfid = buf->ReadDWord();
7718 GRFConfig *file = GetGRFConfig(grfid);
7719
7720 /* Unset activation flag */
7721 if (file != nullptr && file != _cur.grfconfig) {
7722 GrfMsg(2, "GRFInhibit: Deactivating file '{}'", file->filename);
7723 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7724 error->data = _cur.grfconfig->GetName();
7725 }
7726 }
7727 }
7728
7730 static void FeatureTownName(ByteReader *buf)
7731 {
7732 /* <0F> <id> <style-name> <num-parts> <parts>
7733 *
7734 * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7735 * V style-name Name of the style (only for final definition)
7736 * B num-parts Number of parts in this definition
7737 * V parts The parts */
7738
7739 uint32_t grfid = _cur.grffile->grfid;
7740
7741 GRFTownName *townname = AddGRFTownName(grfid);
7742
7743 byte id = buf->ReadByte();
7744 GrfMsg(6, "FeatureTownName: definition 0x{:02X}", id & 0x7F);
7745
7746 if (HasBit(id, 7)) {
7747 /* Final definition */
7748 ClrBit(id, 7);
7749 bool new_scheme = _cur.grffile->grf_version >= 7;
7750
7751 byte lang = buf->ReadByte();
7752 StringID style = STR_UNDEFINED;
7753
7754 do {
7755 ClrBit(lang, 7);
7756
7757 const char *name = buf->ReadString();
7758
7759 std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7760 GrfMsg(6, "FeatureTownName: lang 0x{:X} -> '{}'", lang, lang_name);
7761
7762 style = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7763
7764 lang = buf->ReadByte();
7765 } while (lang != 0);
7766 townname->styles.emplace_back(style, id);
7767 }
7768
7769 uint8_t parts = buf->ReadByte();
7770 GrfMsg(6, "FeatureTownName: {} parts", parts);
7771
7772 townname->partlists[id].reserve(parts);
7773 for (uint partnum = 0; partnum < parts; partnum++) {
7774 NamePartList &partlist = townname->partlists[id].emplace_back();
7775 uint8_t texts = buf->ReadByte();
7776 partlist.bitstart = buf->ReadByte();
7777 partlist.bitcount = buf->ReadByte();
7778 partlist.maxprob = 0;
7779 GrfMsg(6, "FeatureTownName: part {} contains {} texts and will use GB(seed, {}, {})", partnum, texts, partlist.bitstart, partlist.bitcount);
7780
7781 partlist.parts.reserve(texts);
7782 for (uint textnum = 0; textnum < texts; textnum++) {
7783 NamePart &part = partlist.parts.emplace_back();
7784 part.prob = buf->ReadByte();
7785
7786 if (HasBit(part.prob, 7)) {
7787 byte ref_id = buf->ReadByte();
7788 if (ref_id >= GRFTownName::MAX_LISTS || townname->partlists[ref_id].empty()) {
7789 GrfMsg(0, "FeatureTownName: definition 0x{:02X} doesn't exist, deactivating", ref_id);
7790 DelGRFTownName(grfid);
7791 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7792 return;
7793 }
7794 part.id = ref_id;
7795 GrfMsg(6, "FeatureTownName: part {}, text {}, uses intermediate definition 0x{:02X} (with probability {})", partnum, textnum, ref_id, part.prob & 0x7F);
7796 } else {
7797 const char *text = buf->ReadString();
7798 part.text = TranslateTTDPatchCodes(grfid, 0, false, text);
7799 GrfMsg(6, "FeatureTownName: part {}, text {}, '{}' (with probability {})", partnum, textnum, part.text, part.prob);
7800 }
7801 partlist.maxprob += GB(part.prob, 0, 7);
7802 }
7803 GrfMsg(6, "FeatureTownName: part {}, total probability {}", partnum, partlist.maxprob);
7804 }
7805 }
7806
7808 static void DefineGotoLabel(ByteReader *buf)
7809 {
7810 /* <10> <label> [<comment>]
7811 *
7812 * B label The label to define
7813 * V comment Optional comment - ignored */
7814
7815 byte nfo_label = buf->ReadByte();
7816
7817 _cur.grffile->labels.emplace_back(nfo_label, _cur.nfo_line, _cur.file->GetPos());
7818
7819 GrfMsg(2, "DefineGotoLabel: GOTO target with label 0x{:02X}", nfo_label);
7820 }
7821
7826 static void ImportGRFSound(SoundEntry *sound)
7827 {
7828 const GRFFile *file;
7829 uint32_t grfid = _cur.file->ReadDword();
7830 SoundID sound_id = _cur.file->ReadWord();
7831
7832 file = GetFileByGRFID(grfid);
7833 if (file == nullptr || file->sound_offset == 0) {
7834 GrfMsg(1, "ImportGRFSound: Source file not available");
7835 return;
7836 }
7837
7838 if (sound_id >= file->num_sounds) {
7839 GrfMsg(1, "ImportGRFSound: Sound effect {} is invalid", sound_id);
7840 return;
7841 }
7842
7843 GrfMsg(2, "ImportGRFSound: Copying sound {} ({}) from file {:x}", sound_id, file->sound_offset + sound_id, grfid);
7844
7845 *sound = *GetSound(file->sound_offset + sound_id);
7846
7847 /* Reset volume and priority, which TTDPatch doesn't copy */
7848 sound->volume = 128;
7849 sound->priority = 0;
7850 }
7851
7857 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7858 {
7859 /* Set default volume and priority */
7860 sound->volume = 0x80;
7861 sound->priority = 0;
7862
7863 if (offs != SIZE_MAX) {
7864 /* Sound is present in the NewGRF. */
7865 sound->file = _cur.file;
7866 sound->file_offset = offs;
7867 sound->grf_container_ver = _cur.file->GetContainerVersion();
7868 }
7869 }
7870
7871 /* Action 0x11 */
7872 static void GRFSound(ByteReader *buf)
7873 {
7874 /* <11> <num>
7875 *
7876 * W num Number of sound files that follow */
7877
7878 uint16_t num = buf->ReadWord();
7879 if (num == 0) return;
7880
7881 SoundEntry *sound;
7882 if (_cur.grffile->sound_offset == 0) {
7883 _cur.grffile->sound_offset = GetNumSounds();
7884 _cur.grffile->num_sounds = num;
7885 sound = AllocateSound(num);
7886 } else {
7887 sound = GetSound(_cur.grffile->sound_offset);
7888 }
7889
7890 SpriteFile &file = *_cur.file;
7891 byte grf_container_version = file.GetContainerVersion();
7892 for (int i = 0; i < num; i++) {
7893 _cur.nfo_line++;
7894
7895 /* Check whether the index is in range. This might happen if multiple action 11 are present.
7896 * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7897 bool invalid = i >= _cur.grffile->num_sounds;
7898
7899 size_t offs = file.GetPos();
7900
7901 uint32_t len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7902 byte type = file.ReadByte();
7903
7904 if (grf_container_version >= 2 && type == 0xFD) {
7905 /* Reference to sprite section. */
7906 if (invalid) {
7907 GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7908 file.SkipBytes(len);
7909 } else if (len != 4) {
7910 GrfMsg(1, "GRFSound: Invalid sprite section import");
7911 file.SkipBytes(len);
7912 } else {
7913 uint32_t id = file.ReadDword();
7914 if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7915 }
7916 continue;
7917 }
7918
7919 if (type != 0xFF) {
7920 GrfMsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7921 file.SkipBytes(7);
7922 SkipSpriteData(*_cur.file, type, len - 8);
7923 continue;
7924 }
7925
7926 if (invalid) {
7927 GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7928 file.SkipBytes(len);
7929 }
7930
7931 byte action = file.ReadByte();
7932 switch (action) {
7933 case 0xFF:
7934 /* Allocate sound only in init stage. */
7935 if (_cur.stage == GLS_INIT) {
7936 if (grf_container_version >= 2) {
7937 GrfMsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7938 } else {
7939 LoadGRFSound(offs, sound + i);
7940 }
7941 }
7942 file.SkipBytes(len - 1); // already read <action>
7943 break;
7944
7945 case 0xFE:
7946 if (_cur.stage == GLS_ACTIVATION) {
7947 /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7948 * importing sounds, so this is probably all wrong... */
7949 if (file.ReadByte() != 0) GrfMsg(1, "GRFSound: Import type mismatch");
7950 ImportGRFSound(sound + i);
7951 } else {
7952 file.SkipBytes(len - 1); // already read <action>
7953 }
7954 break;
7955
7956 default:
7957 GrfMsg(1, "GRFSound: Unexpected Action {:x} found, skipping", action);
7958 file.SkipBytes(len - 1); // already read <action>
7959 break;
7960 }
7961 }
7962 }
7963
7964 /* Action 0x11 (SKIP) */
7965 static void SkipAct11(ByteReader *buf)
7966 {
7967 /* <11> <num>
7968 *
7969 * W num Number of sound files that follow */
7970
7971 _cur.skip_sprites = buf->ReadWord();
7972
7973 GrfMsg(3, "SkipAct11: Skipping {} sprites", _cur.skip_sprites);
7974 }
7975
7977 static void LoadFontGlyph(ByteReader *buf)
7978 {
7979 /* <12> <num_def> <font_size> <num_char> <base_char>
7980 *
7981 * B num_def Number of definitions
7982 * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7983 * B num_char Number of consecutive glyphs
7984 * W base_char First character index */
7985
7986 uint8_t num_def = buf->ReadByte();
7987
7988 for (uint i = 0; i < num_def; i++) {
7989 FontSize size = (FontSize)buf->ReadByte();
7990 uint8_t num_char = buf->ReadByte();
7991 uint16_t base_char = buf->ReadWord();
7992
7993 if (size >= FS_END) {
7994 GrfMsg(1, "LoadFontGlyph: Size {} is not supported, ignoring", size);
7995 }
7996
7997 GrfMsg(7, "LoadFontGlyph: Loading {} glyph(s) at 0x{:04X} for size {}", num_char, base_char, size);
7998
7999 for (uint c = 0; c < num_char; c++) {
8000 if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
8001 _cur.nfo_line++;
8002 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
8003 }
8004 }
8005 }
8006
8008 static void SkipAct12(ByteReader *buf)
8009 {
8010 /* <12> <num_def> <font_size> <num_char> <base_char>
8011 *
8012 * B num_def Number of definitions
8013 * B font_size Size of font (0 = normal, 1 = small, 2 = large)
8014 * B num_char Number of consecutive glyphs
8015 * W base_char First character index */
8016
8017 uint8_t num_def = buf->ReadByte();
8018
8019 for (uint i = 0; i < num_def; i++) {
8020 /* Ignore 'size' byte */
8021 buf->ReadByte();
8022
8023 /* Sum up number of characters */
8024 _cur.skip_sprites += buf->ReadByte();
8025
8026 /* Ignore 'base_char' word */
8027 buf->ReadWord();
8028 }
8029
8030 GrfMsg(3, "SkipAct12: Skipping {} sprites", _cur.skip_sprites);
8031 }
8032
8034 static void TranslateGRFStrings(ByteReader *buf)
8035 {
8036 /* <13> <grfid> <num-ent> <offset> <text...>
8037 *
8038 * 4*B grfid The GRFID of the file whose texts are to be translated
8039 * B num-ent Number of strings
8040 * W offset First text ID
8041 * S text... Zero-terminated strings */
8042
8043 uint32_t grfid = buf->ReadDWord();
8044 const GRFConfig *c = GetGRFConfig(grfid);
8045 if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
8046 GrfMsg(7, "TranslateGRFStrings: GRFID 0x{:08X} unknown, skipping action 13", BSWAP32(grfid));
8047 return;
8048 }
8049
8050 if (c->status == GCS_INITIALISED) {
8051 /* If the file is not active but will be activated later, give an error
8052 * and disable this file. */
8053 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
8054
8055 error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
8056
8057 return;
8058 }
8059
8060 /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
8061 * to be added as a generic string, thus the language id of 0x7F. For this to work
8062 * new_scheme has to be true as well, which will also be implicitly the case for version 8
8063 * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
8064 * not change anything if a string has been provided specifically for this language. */
8065 byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
8066 byte num_strings = buf->ReadByte();
8067 uint16_t first_id = buf->ReadWord();
8068
8069 if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
8070 GrfMsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x{:04X}, number: 0x{:02X})", first_id, num_strings);
8071 return;
8072 }
8073
8074 for (uint i = 0; i < num_strings && buf->HasData(); i++) {
8075 const char *string = buf->ReadString();
8076
8077 if (StrEmpty(string)) {
8078 GrfMsg(7, "TranslateGRFString: Ignoring empty string.");
8079 continue;
8080 }
8081
8082 AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
8083 }
8084 }
8085
8087 static bool ChangeGRFName(byte langid, const char *str)
8088 {
8089 AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
8090 return true;
8091 }
8092
8094 static bool ChangeGRFDescription(byte langid, const char *str)
8095 {
8096 AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
8097 return true;
8098 }
8099
8101 static bool ChangeGRFURL(byte langid, const char *str)
8102 {
8103 AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
8104 return true;
8105 }
8106
8108 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
8109 {
8110 if (len != 1) {
8111 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got {}, ignoring this field", len);
8112 buf->Skip(len);
8113 } else {
8114 _cur.grfconfig->num_valid_params = std::min(buf->ReadByte(), ClampTo<uint8_t>(_cur.grfconfig->param.size()));
8115 }
8116 return true;
8117 }
8118
8120 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
8121 {
8122 if (len != 1) {
8123 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got {}, ignoring this field", len);
8124 buf->Skip(len);
8125 } else {
8126 char data = buf->ReadByte();
8127 GRFPalette pal = GRFP_GRF_UNSET;
8128 switch (data) {
8129 case '*':
8130 case 'A': pal = GRFP_GRF_ANY; break;
8131 case 'W': pal = GRFP_GRF_WINDOWS; break;
8132 case 'D': pal = GRFP_GRF_DOS; break;
8133 default:
8134 GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'PALS', ignoring this field", data);
8135 break;
8136 }
8137 if (pal != GRFP_GRF_UNSET) {
8138 _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
8139 _cur.grfconfig->palette |= pal;
8140 }
8141 }
8142 return true;
8143 }
8144
8146 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
8147 {
8148 if (len != 1) {
8149 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got {}, ignoring this field", len);
8150 buf->Skip(len);
8151 } else {
8152 char data = buf->ReadByte();
8153 GRFPalette pal = GRFP_BLT_UNSET;
8154 switch (data) {
8155 case '8': pal = GRFP_BLT_UNSET; break;
8156 case '3': pal = GRFP_BLT_32BPP; break;
8157 default:
8158 GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'BLTR', ignoring this field", data);
8159 return true;
8160 }
8161 _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
8162 _cur.grfconfig->palette |= pal;
8163 }
8164 return true;
8165 }
8166
8168 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
8169 {
8170 if (len != 4) {
8171 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got {}, ignoring this field", len);
8172 buf->Skip(len);
8173 } else {
8174 /* Set min_loadable_version as well (default to minimal compatibility) */
8175 _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
8176 }
8177 return true;
8178 }
8179
8181 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
8182 {
8183 if (len != 4) {
8184 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got {}, ignoring this field", len);
8185 buf->Skip(len);
8186 } else {
8187 _cur.grfconfig->min_loadable_version = buf->ReadDWord();
8188 if (_cur.grfconfig->version == 0) {
8189 GrfMsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
8190 _cur.grfconfig->min_loadable_version = 0;
8191 }
8192 if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
8193 GrfMsg(2, "StaticGRFInfo: 'MINV' defined as {}, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
8194 _cur.grfconfig->min_loadable_version = _cur.grfconfig->version;
8195 }
8196 }
8197 return true;
8198 }
8199
8200 static GRFParameterInfo *_cur_parameter;
8201
8203 static bool ChangeGRFParamName(byte langid, const char *str)
8204 {
8205 AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
8206 return true;
8207 }
8208
8210 static bool ChangeGRFParamDescription(byte langid, const char *str)
8211 {
8212 AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
8213 return true;
8214 }
8215
8217 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
8218 {
8219 if (len != 1) {
8220 GrfMsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got {}, ignoring this field", len);
8221 buf->Skip(len);
8222 } else {
8223 GRFParameterType type = (GRFParameterType)buf->ReadByte();
8224 if (type < PTYPE_END) {
8225 _cur_parameter->type = type;
8226 } else {
8227 GrfMsg(3, "StaticGRFInfo: unknown parameter type {}, ignoring this field", type);
8228 }
8229 }
8230 return true;
8231 }
8232
8234 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
8235 {
8236 if (_cur_parameter->type != PTYPE_UINT_ENUM) {
8237 GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8238 buf->Skip(len);
8239 } else if (len != 8) {
8240 GrfMsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got {}, ignoring this field", len);
8241 buf->Skip(len);
8242 } else {
8243 uint32_t min_value = buf->ReadDWord();
8244 uint32_t max_value = buf->ReadDWord();
8245 if (min_value <= max_value) {
8246 _cur_parameter->min_value = min_value;
8247 _cur_parameter->max_value = max_value;
8248 } else {
8249 GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8250 }
8251 }
8252 return true;
8253 }
8254
8256 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
8257 {
8258 if (len < 1 || len > 3) {
8259 GrfMsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got {}, ignoring this field", len);
8260 buf->Skip(len);
8261 } else {
8262 byte param_nr = buf->ReadByte();
8263 if (param_nr >= _cur.grfconfig->param.size()) {
8264 GrfMsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param {}, ignoring this field", param_nr);
8265 buf->Skip(len - 1);
8266 } else {
8267 _cur_parameter->param_nr = param_nr;
8268 if (len >= 2) _cur_parameter->first_bit = std::min<byte>(buf->ReadByte(), 31);
8269 if (len >= 3) _cur_parameter->num_bit = std::min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
8270 }
8271 }
8272
8273 return true;
8274 }
8275
8277 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
8278 {
8279 if (len != 4) {
8280 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got {}, ignoring this field", len);
8281 buf->Skip(len);
8282 } else {
8283 _cur_parameter->def_value = buf->ReadDWord();
8284 }
8285 _cur.grfconfig->has_param_defaults = true;
8286 return true;
8287 }
8288
8289 typedef bool (*DataHandler)(size_t, ByteReader *);
8290 typedef bool (*TextHandler)(byte, const char *str);
8291 typedef bool (*BranchHandler)(ByteReader *);
8292
8300 struct AllowedSubtags {
8302 AllowedSubtags() :
8303 id(0),
8304 type(0)
8305 {}
8306
8312 AllowedSubtags(uint32_t id, DataHandler handler) :
8313 id(id),
8314 type('B')
8315 {
8316 this->handler.data = handler;
8317 }
8318
8324 AllowedSubtags(uint32_t id, TextHandler handler) :
8325 id(id),
8326 type('T')
8327 {
8328 this->handler.text = handler;
8329 }
8330
8336 AllowedSubtags(uint32_t id, BranchHandler handler) :
8337 id(id),
8338 type('C')
8339 {
8340 this->handler.call_handler = true;
8341 this->handler.u.branch = handler;
8342 }
8343
8349 AllowedSubtags(uint32_t id, AllowedSubtags *subtags) :
8350 id(id),
8351 type('C')
8352 {
8353 this->handler.call_handler = false;
8354 this->handler.u.subtags = subtags;
8355 }
8356
8357 uint32_t id;
8358 byte type;
8359 union {
8360 DataHandler data;
8361 TextHandler text;
8362 struct {
8363 union {
8364 BranchHandler branch;
8365 AllowedSubtags *subtags;
8366 } u;
8367 bool call_handler;
8368 };
8369 } handler;
8370 };
8371
8372 static bool SkipUnknownInfo(ByteReader *buf, byte type);
8373 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
8374
8381 static bool ChangeGRFParamValueNames(ByteReader *buf)
8382 {
8383 byte type = buf->ReadByte();
8384 while (type != 0) {
8385 uint32_t id = buf->ReadDWord();
8386 if (type != 'T' || id > _cur_parameter->max_value) {
8387 GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8388 if (!SkipUnknownInfo(buf, type)) return false;
8389 type = buf->ReadByte();
8390 continue;
8391 }
8392
8393 byte langid = buf->ReadByte();
8394 const char *name_string = buf->ReadString();
8395
8396 auto val_name = _cur_parameter->value_names.find(id);
8397 if (val_name != _cur_parameter->value_names.end()) {
8398 AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8399 } else {
8400 GRFTextList list;
8401 AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8402 _cur_parameter->value_names[id] = list;
8403 }
8404
8405 type = buf->ReadByte();
8406 }
8407 return true;
8408 }
8409
8411 AllowedSubtags _tags_parameters[] = {
8412 AllowedSubtags('NAME', ChangeGRFParamName),
8413 AllowedSubtags('DESC', ChangeGRFParamDescription),
8414 AllowedSubtags('TYPE', ChangeGRFParamType),
8415 AllowedSubtags('LIMI', ChangeGRFParamLimits),
8416 AllowedSubtags('MASK', ChangeGRFParamMask),
8417 AllowedSubtags('VALU', ChangeGRFParamValueNames),
8418 AllowedSubtags('DFLT', ChangeGRFParamDefault),
8419 AllowedSubtags()
8420 };
8421
8428 static bool HandleParameterInfo(ByteReader *buf)
8429 {
8430 byte type = buf->ReadByte();
8431 while (type != 0) {
8432 uint32_t id = buf->ReadDWord();
8433 if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8434 GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8435 if (!SkipUnknownInfo(buf, type)) return false;
8436 type = buf->ReadByte();
8437 continue;
8438 }
8439
8440 if (id >= _cur.grfconfig->param_info.size()) {
8441 _cur.grfconfig->param_info.resize(id + 1);
8442 }
8443 if (!_cur.grfconfig->param_info[id].has_value()) {
8444 _cur.grfconfig->param_info[id] = GRFParameterInfo(id);
8445 }
8446 _cur_parameter = &_cur.grfconfig->param_info[id].value();
8447 /* Read all parameter-data and process each node. */
8448 if (!HandleNodes(buf, _tags_parameters)) return false;
8449 type = buf->ReadByte();
8450 }
8451 return true;
8452 }
8453
8455 AllowedSubtags _tags_info[] = {
8456 AllowedSubtags('NAME', ChangeGRFName),
8457 AllowedSubtags('DESC', ChangeGRFDescription),
8458 AllowedSubtags('URL_', ChangeGRFURL),
8459 AllowedSubtags('NPAR', ChangeGRFNumUsedParams),
8460 AllowedSubtags('PALS', ChangeGRFPalette),
8461 AllowedSubtags('BLTR', ChangeGRFBlitter),
8462 AllowedSubtags('VRSN', ChangeGRFVersion),
8463 AllowedSubtags('MINV', ChangeGRFMinVersion),
8464 AllowedSubtags('PARA', HandleParameterInfo),
8465 AllowedSubtags()
8466 };
8467
8469 AllowedSubtags _tags_root[] = {
8470 AllowedSubtags('INFO', _tags_info),
8471 AllowedSubtags()
8472 };
8473
8474
8481 static bool SkipUnknownInfo(ByteReader *buf, byte type)
8482 {
8483 /* type and id are already read */
8484 switch (type) {
8485 case 'C': {
8486 byte new_type = buf->ReadByte();
8487 while (new_type != 0) {
8488 buf->ReadDWord(); // skip the id
8489 if (!SkipUnknownInfo(buf, new_type)) return false;
8490 new_type = buf->ReadByte();
8491 }
8492 break;
8493 }
8494
8495 case 'T':
8496 buf->ReadByte(); // lang
8497 buf->ReadString(); // actual text
8498 break;
8499
8500 case 'B': {
8501 uint16_t size = buf->ReadWord();
8502 buf->Skip(size);
8503 break;
8504 }
8505
8506 default:
8507 return false;
8508 }
8509
8510 return true;
8511 }
8512
8521 static bool HandleNode(byte type, uint32_t id, ByteReader *buf, AllowedSubtags subtags[])
8522 {
8523 uint i = 0;
8524 AllowedSubtags *tag;
8525 while ((tag = &subtags[i++])->type != 0) {
8526 if (tag->id != BSWAP32(id) || tag->type != type) continue;
8527 switch (type) {
8528 default: NOT_REACHED();
8529
8530 case 'T': {
8531 byte langid = buf->ReadByte();
8532 return tag->handler.text(langid, buf->ReadString());
8533 }
8534
8535 case 'B': {
8536 size_t len = buf->ReadWord();
8537 if (buf->Remaining() < len) return false;
8538 return tag->handler.data(len, buf);
8539 }
8540
8541 case 'C': {
8542 if (tag->handler.call_handler) {
8543 return tag->handler.u.branch(buf);
8544 }
8545 return HandleNodes(buf, tag->handler.u.subtags);
8546 }
8547 }
8548 }
8549 GrfMsg(2, "StaticGRFInfo: unknown type/id combination found, type={:c}, id={:x}", type, id);
8550 return SkipUnknownInfo(buf, type);
8551 }
8552
8559 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
8560 {
8561 byte type = buf->ReadByte();
8562 while (type != 0) {
8563 uint32_t id = buf->ReadDWord();
8564 if (!HandleNode(type, id, buf, subtags)) return false;
8565 type = buf->ReadByte();
8566 }
8567 return true;
8568 }
8569
8574 static void StaticGRFInfo(ByteReader *buf)
8575 {
8576 /* <14> <type> <id> <text/data...> */
8577 HandleNodes(buf, _tags_root);
8578 }
8579
8584 static void GRFUnsafe(ByteReader *)
8585 {
8586 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8587
8588 /* Skip remainder of GRF */
8589 _cur.skip_sprites = -1;
8590 }
8591
8592
8594 static void InitializeGRFSpecial()
8595 {
8596 _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1U : 0U) << 0x0C) // keepsmallairport
8597 | (1U << 0x0D) // newairports
8598 | (1U << 0x0E) // largestations
8599 | ((_settings_game.construction.max_bridge_length > 16 ? 1U : 0U) << 0x0F) // longbridges
8600 | (0U << 0x10) // loadtime
8601 | (1U << 0x12) // presignals
8602 | (1U << 0x13) // extpresignals
8603 | ((_settings_game.vehicle.never_expire_vehicles ? 1U : 0U) << 0x16) // enginespersist
8604 | (1U << 0x1B) // multihead
8605 | (1U << 0x1D) // lowmemory
8606 | (1U << 0x1E); // generalfixes
8607
8608 _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1U : 0U) << 0x07) // moreairports - based on units of noise
8609 | (1U << 0x08) // mammothtrains
8610 | (1U << 0x09) // trainrefit
8611 | (0U << 0x0B) // subsidiaries
8612 | ((_settings_game.order.gradual_loading ? 1U : 0U) << 0x0C) // gradualloading
8613 | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8614 | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8615 | (1U << 0x14) // bridgespeedlimits
8616 | (1U << 0x16) // eternalgame
8617 | (1U << 0x17) // newtrains
8618 | (1U << 0x18) // newrvs
8619 | (1U << 0x19) // newships
8620 | (1U << 0x1A) // newplanes
8621 | ((_settings_game.construction.train_signal_side == 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8622 | ((_settings_game.vehicle.disable_elrails ? 0U : 1U) << 0x1C); // electrifiedrailway
8623
8624 _ttdpatch_flags[2] = (1U << 0x01) // loadallgraphics - obsolote
8625 | (1U << 0x03) // semaphores
8626 | (1U << 0x0A) // newobjects
8627 | (0U << 0x0B) // enhancedgui
8628 | (0U << 0x0C) // newagerating
8629 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x0D) // buildonslopes
8630 | (1U << 0x0E) // fullloadany
8631 | (1U << 0x0F) // planespeed
8632 | (0U << 0x10) // moreindustriesperclimate - obsolete
8633 | (0U << 0x11) // moretoylandfeatures
8634 | (1U << 0x12) // newstations
8635 | (1U << 0x13) // tracktypecostdiff
8636 | (1U << 0x14) // manualconvert
8637 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x15) // buildoncoasts
8638 | (1U << 0x16) // canals
8639 | (1U << 0x17) // newstartyear
8640 | ((_settings_game.vehicle.freight_trains > 1 ? 1U : 0U) << 0x18) // freighttrains
8641 | (1U << 0x19) // newhouses
8642 | (1U << 0x1A) // newbridges
8643 | (1U << 0x1B) // newtownnames
8644 | (1U << 0x1C) // moreanimation
8645 | ((_settings_game.vehicle.wagon_speed_limits ? 1U : 0U) << 0x1D) // wagonspeedlimits
8646 | (1U << 0x1E) // newshistory
8647 | (0U << 0x1F); // custombridgeheads
8648
8649 _ttdpatch_flags[3] = (0U << 0x00) // newcargodistribution
8650 | (1U << 0x01) // windowsnap
8651 | ((_settings_game.economy.allow_town_roads || _generating_world ? 0U : 1U) << 0x02) // townbuildnoroad
8652 | (1U << 0x03) // pathbasedsignalling
8653 | (0U << 0x04) // aichoosechance
8654 | (1U << 0x05) // resolutionwidth
8655 | (1U << 0x06) // resolutionheight
8656 | (1U << 0x07) // newindustries
8657 | ((_settings_game.order.improved_load ? 1U : 0U) << 0x08) // fifoloading
8658 | (0U << 0x09) // townroadbranchprob
8659 | (0U << 0x0A) // tempsnowline
8660 | (1U << 0x0B) // newcargo
8661 | (1U << 0x0C) // enhancemultiplayer
8662 | (1U << 0x0D) // onewayroads
8663 | (1U << 0x0E) // irregularstations
8664 | (1U << 0x0F) // statistics
8665 | (1U << 0x10) // newsounds
8666 | (1U << 0x11) // autoreplace
8667 | (1U << 0x12) // autoslope
8668 | (0U << 0x13) // followvehicle
8669 | (1U << 0x14) // trams
8670 | (0U << 0x15) // enhancetunnels
8671 | (1U << 0x16) // shortrvs
8672 | (1U << 0x17) // articulatedrvs
8673 | ((_settings_game.vehicle.dynamic_engines ? 1U : 0U) << 0x18) // dynamic engines
8674 | (1U << 0x1E) // variablerunningcosts
8675 | (1U << 0x1F); // any switch is on
8676
8677 _ttdpatch_flags[4] = (1U << 0x00) // larger persistent storage
8678 | ((_settings_game.economy.inflation ? 1U : 0U) << 0x01) // inflation is on
8679 | (1U << 0x02); // extended string range
8680 }
8681
8683 static void ResetCustomStations()
8684 {
8685 for (GRFFile * const file : _grf_files) {
8686 file->stations.clear();
8687 }
8688 }
8689
8691 static void ResetCustomHouses()
8692 {
8693 for (GRFFile * const file : _grf_files) {
8694 file->housespec.clear();
8695 }
8696 }
8697
8699 static void ResetCustomAirports()
8700 {
8701 for (GRFFile * const file : _grf_files) {
8702 for (auto &as : file->airportspec) {
8703 if (as != nullptr) {
8704 /* We need to remove the tiles layouts */
8705 for (int j = 0; j < as->num_table; j++) {
8706 /* remove the individual layouts */
8707 free(as->table[j]);
8708 }
8709 free(as->table);
8710 free(as->depot_table);
8711 free(as->rotation);
8712 }
8713 }
8714 file->airportspec.clear();
8715 file->airtspec.clear();
8716 }
8717 }
8718
8720 static void ResetCustomIndustries()
8721 {
8722 for (GRFFile * const file : _grf_files) {
8723 file->industryspec.clear();
8724 file->indtspec.clear();
8725 }
8726 }
8727
8729 static void ResetCustomObjects()
8730 {
8731 for (GRFFile * const file : _grf_files) {
8732 file->objectspec.clear();
8733 }
8734 }
8735
8736 static void ResetCustomRoadStops()
8737 {
8738 for (auto file : _grf_files) {
8739 file->roadstops.clear();
8740 }
8741 }
8742
8744 static void ResetNewGRF()
8745 {
8746 for (GRFFile * const file : _grf_files) {
8747 delete file;
8748 }
8749
8750 _grf_files.clear();
8751 _cur.grffile = nullptr;
8752 }
8753
8755 static void ResetNewGRFErrors()
8756 {
8757 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8758 c->error.reset();
8759 }
8760 }
8761
8765 void ResetNewGRFData()
8766 {
8767 CleanUpStrings();
8768 CleanUpGRFTownNames();
8769
8770 /* Copy/reset original engine info data */
8771 SetupEngines();
8772
8773 /* Copy/reset original bridge info data */
8774 ResetBridges();
8775
8776 /* Reset rail type information */
8777 ResetRailTypes();
8778
8779 /* Copy/reset original road type info data */
8780 ResetRoadTypes();
8781
8782 /* Allocate temporary refit/cargo class data */
8783 _gted.resize(Engine::GetPoolSize());
8784
8785 /* Fill rail type label temporary data for default trains */
8786 for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8787 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8788 }
8789
8790 /* Reset GRM reservations */
8791 memset(&_grm_engines, 0, sizeof(_grm_engines));
8792 memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8793
8794 /* Reset generic feature callback lists */
8795 ResetGenericCallbacks();
8796
8797 /* Reset price base data */
8798 ResetPriceBaseMultipliers();
8799
8800 /* Reset the curencies array */
8801 ResetCurrencies();
8802
8803 /* Reset the house array */
8804 ResetCustomHouses();
8805 ResetHouses();
8806
8807 /* Reset the industries structures*/
8808 ResetCustomIndustries();
8809 ResetIndustries();
8810
8811 /* Reset the objects. */
8812 ObjectClass::Reset();
8813 ResetCustomObjects();
8814 ResetObjects();
8815
8816 /* Reset station classes */
8817 StationClass::Reset();
8818 ResetCustomStations();
8819
8820 /* Reset airport-related structures */
8821 AirportClass::Reset();
8822 ResetCustomAirports();
8823 AirportSpec::ResetAirports();
8824 AirportTileSpec::ResetAirportTiles();
8825
8826 /* Reset road stop classes */
8827 RoadStopClass::Reset();
8828 ResetCustomRoadStops();
8829
8830 /* Reset canal sprite groups and flags */
8831 memset(_water_feature, 0, sizeof(_water_feature));
8832
8833 /* Reset the snowline table. */
8834 ClearSnowLine();
8835
8836 /* Reset NewGRF files */
8837 ResetNewGRF();
8838
8839 /* Reset NewGRF errors. */
8840 ResetNewGRFErrors();
8841
8842 /* Set up the default cargo types */
8843 SetupCargoForClimate(_settings_game.game_creation.landscape);
8844
8845 /* Reset misc GRF features and train list display variables */
8846 _misc_grf_features = 0;
8847
8848 _loaded_newgrf_features.has_2CC = false;
8849 _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8850 _loaded_newgrf_features.shore = SHORE_REPLACE_NONE;
8851 _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NONE;
8852
8853 /* Clear all GRF overrides */
8854 _grf_id_overrides.clear();
8855
8856 InitializeSoundPool();
8857 _spritegroup_pool.CleanPool();
8858 }
8859
8863 void ResetPersistentNewGRFData()
8864 {
8865 /* Reset override managers */
8866 _engine_mngr.ResetToDefaultMapping();
8867 _house_mngr.ResetMapping();
8868 _industry_mngr.ResetMapping();
8869 _industile_mngr.ResetMapping();
8870 _airport_mngr.ResetMapping();
8871 _airporttile_mngr.ResetMapping();
8872 }
8873
8878 static void BuildCargoTranslationMap()
8879 {
8880 _cur.grffile->cargo_map.fill(UINT8_MAX);
8881
8882 for (const CargoSpec *cs : CargoSpec::Iterate()) {
8883 if (!cs->IsValid()) continue;
8884
8885 if (_cur.grffile->cargo_list.empty()) {
8886 /* Default translation table, so just a straight mapping to bitnum */
8887 _cur.grffile->cargo_map[cs->Index()] = cs->bitnum;
8888 } else {
8889 /* Check the translation table for this cargo's label */
8890 int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8891 if (idx >= 0) _cur.grffile->cargo_map[cs->Index()] = idx;
8892 }
8893 }
8894 }
8895
8900 static void InitNewGRFFile(const GRFConfig *config)
8901 {
8902 GRFFile *newfile = GetFileByFilename(config->filename);
8903 if (newfile != nullptr) {
8904 /* We already loaded it once. */
8905 _cur.grffile = newfile;
8906 return;
8907 }
8908
8909 newfile = new GRFFile(config);
8910 _grf_files.push_back(_cur.grffile = newfile);
8911 }
8912
8917 GRFFile::GRFFile(const GRFConfig *config)
8918 {
8919 this->filename = config->filename;
8920 this->grfid = config->ident.grfid;
8921
8922 /* Initialise local settings to defaults */
8923 this->traininfo_vehicle_pitch = 0;
8924 this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8925
8926 /* Mark price_base_multipliers as 'not set' */
8927 for (Price i = PR_BEGIN; i < PR_END; i++) {
8928 this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8929 }
8930
8931 /* Initialise rail type map with default rail types */
8932 std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8933 this->railtype_map[0] = RAILTYPE_RAIL;
8934 this->railtype_map[1] = RAILTYPE_ELECTRIC;
8935 this->railtype_map[2] = RAILTYPE_MONO;
8936 this->railtype_map[3] = RAILTYPE_MAGLEV;
8937
8938 /* Initialise road type map with default road types */
8939 std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8940 this->roadtype_map[0] = ROADTYPE_ROAD;
8941
8942 /* Initialise tram type map with default tram types */
8943 std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8944 this->tramtype_map[0] = ROADTYPE_TRAM;
8945
8946 /* Copy the initial parameter list
8947 * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8948 this->param = config->param;
8949 this->param_end = config->num_params;
8950 }
8951
8952 GRFFile::~GRFFile()
8953 {
8954 delete[] this->language_map;
8955 }
8956
8957
8961 static void CalculateRefitMasks()
8962 {
8963 CargoTypes original_known_cargoes = 0;
8964 for (int ct = 0; ct != NUM_ORIGINAL_CARGO; ++ct) {
8965 CargoID cid = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ct));
8966 if (IsValidCargoID(cid)) SetBit(original_known_cargoes, cid);
8967 }
8968
8969 for (Engine *e : Engine::Iterate()) {
8970 EngineID engine = e->index;
8971 EngineInfo *ei = &e->info;
8972 bool only_defaultcargo;
8973
8974 /* If the NewGRF did not set any cargo properties, we apply default values. */
8975 if (_gted[engine].defaultcargo_grf == nullptr) {
8976 /* If the vehicle has any capacity, apply the default refit masks */
8977 if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
8978 static constexpr byte T = 1 << LT_TEMPERATE;
8979 static constexpr byte A = 1 << LT_ARCTIC;
8980 static constexpr byte S = 1 << LT_TROPIC;
8981 static constexpr byte Y = 1 << LT_TOYLAND;
8982 static const struct DefaultRefitMasks {
8983 byte climate;
8984 CargoType cargo_type;
8985 CargoTypes cargo_allowed;
8986 CargoTypes cargo_disallowed;
8987 } _default_refit_masks[] = {
8988 {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
8989 {T | A | S , CT_MAIL, CC_MAIL, 0},
8990 {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
8991 { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
8992 {T | A , CT_COAL, CC_BULK, 0},
8993 { S , CT_COPPER_ORE, CC_BULK, 0},
8994 { Y, CT_SUGAR, CC_BULK, 0},
8995 {T | A | S , CT_OIL, CC_LIQUID, 0},
8996 { Y, CT_COLA, CC_LIQUID, 0},
8997 {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8998 { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
8999 { A | S , CT_FOOD, CC_REFRIGERATED, 0},
9000 { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
9001 };
9002
9003 if (e->type == VEH_AIRCRAFT) {
9004 /* Aircraft default to "light" cargoes */
9005 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
9006 _gted[engine].cargo_disallowed = CC_LIQUID;
9007 } else if (e->type == VEH_SHIP) {
9008 switch (ei->cargo_type) {
9009 case CT_PASSENGERS:
9010 /* Ferries */
9011 _gted[engine].cargo_allowed = CC_PASSENGERS;
9012 _gted[engine].cargo_disallowed = 0;
9013 break;
9014 case CT_OIL:
9015 /* Tankers */
9016 _gted[engine].cargo_allowed = CC_LIQUID;
9017 _gted[engine].cargo_disallowed = 0;
9018 break;
9019 default:
9020 /* Cargo ships */
9021 if (_settings_game.game_creation.landscape == LT_TOYLAND) {
9022 /* No tanker in toyland :( */
9023 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9024 _gted[engine].cargo_disallowed = CC_PASSENGERS;
9025 } else {
9026 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
9027 _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
9028 }
9029 break;
9030 }
9031 e->u.ship.old_refittable = true;
9032 } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
9033 /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
9034 * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
9035 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9036 _gted[engine].cargo_disallowed = 0;
9037 } else {
9038 /* Train wagons and road vehicles are classified by their default cargo type */
9039 for (const auto &drm : _default_refit_masks) {
9040 if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
9041 if (drm.cargo_type != ei->cargo_type) continue;
9042
9043 _gted[engine].cargo_allowed = drm.cargo_allowed;
9044 _gted[engine].cargo_disallowed = drm.cargo_disallowed;
9045 break;
9046 }
9047
9048 /* All original cargoes have specialised vehicles, so exclude them */
9049 _gted[engine].ctt_exclude_mask = original_known_cargoes;
9050 }
9051 }
9052 _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
9053
9054 /* Translate cargo_type using the original climate-specific cargo table. */
9055 ei->cargo_type = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ei->cargo_type));
9056 if (IsValidCargoID(ei->cargo_type)) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
9057 }
9058
9059 /* Compute refittability */
9060 {
9061 CargoTypes mask = 0;
9062 CargoTypes not_mask = 0;
9063 CargoTypes xor_mask = ei->refit_mask;
9064
9065 /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
9066 * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
9067 only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
9068
9069 if (_gted[engine].cargo_allowed != 0) {
9070 /* Build up the list of cargo types from the set cargo classes. */
9071 for (const CargoSpec *cs : CargoSpec::Iterate()) {
9072 if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
9073 if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
9074 }
9075 }
9076
9077 ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
9078
9079 /* Apply explicit refit includes/excludes. */
9080 ei->refit_mask |= _gted[engine].ctt_include_mask;
9081 ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
9082 }
9083
9084 /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
9085 if (IsValidCargoID(ei->cargo_type) && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = INVALID_CARGO;
9086
9087 /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
9088 * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
9089 if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && IsValidCargoID(ei->cargo_type) && !HasBit(ei->refit_mask, ei->cargo_type)) {
9090 ei->cargo_type = INVALID_CARGO;
9091 }
9092
9093 /* Check if this engine's cargo type is valid. If not, set to the first refittable
9094 * cargo type. Finally disable the vehicle, if there is still no cargo. */
9095 if (!IsValidCargoID(ei->cargo_type) && ei->refit_mask != 0) {
9096 /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
9097 const GRFFile *file = _gted[engine].defaultcargo_grf;
9098 if (file == nullptr) file = e->GetGRF();
9099 if (file != nullptr && file->grf_version >= 8 && !file->cargo_list.empty()) {
9100 /* Use first refittable cargo from cargo translation table */
9101 byte best_local_slot = UINT8_MAX;
9102 for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
9103 byte local_slot = file->cargo_map[cargo_type];
9104 if (local_slot < best_local_slot) {
9105 best_local_slot = local_slot;
9106 ei->cargo_type = cargo_type;
9107 }
9108 }
9109 }
9110
9111 if (!IsValidCargoID(ei->cargo_type)) {
9112 /* Use first refittable cargo slot */
9113 ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
9114 }
9115 }
9116 if (!IsValidCargoID(ei->cargo_type)) ei->climates = 0;
9117
9118 /* Clear refit_mask for not refittable ships */
9119 if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
9120 ei->refit_mask = 0;
9121 }
9122 }
9123 }
9124
9126 static void FinaliseCanals()
9127 {
9128 for (uint i = 0; i < CF_END; i++) {
9129 if (_water_feature[i].grffile != nullptr) {
9130 _water_feature[i].callback_mask = _water_feature[i].grffile->canal_local_properties[i].callback_mask;
9131 _water_feature[i].flags = _water_feature[i].grffile->canal_local_properties[i].flags;
9132 }
9133 }
9134 }
9135
9137 static void FinaliseEngineArray()
9138 {
9139 for (Engine *e : Engine::Iterate()) {
9140 if (e->GetGRF() == nullptr) {
9141 const EngineIDMapping &eid = _engine_mngr[e->index];
9142 if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
9143 e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
9144 }
9145 }
9146
9147 /* Do final mapping on variant engine ID. */
9148 if (e->info.variant_id != INVALID_ENGINE) {
9149 e->info.variant_id = GetNewEngineID(e->grf_prop.grffile, e->type, e->info.variant_id);
9150 }
9151
9152 if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
9153
9154 /* Skip wagons, there livery is defined via the engine */
9155 if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
9156 LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, nullptr);
9157 SetBit(_loaded_newgrf_features.used_liveries, ls);
9158 /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9159
9160 if (e->type == VEH_TRAIN) {
9161 SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
9162 switch (ls) {
9163 case LS_STEAM:
9164 case LS_DIESEL:
9165 case LS_ELECTRIC:
9166 case LS_MONORAIL:
9167 case LS_MAGLEV:
9168 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
9169 break;
9170
9171 case LS_DMU:
9172 case LS_EMU:
9173 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
9174 break;
9175
9176 default: NOT_REACHED();
9177 }
9178 }
9179 }
9180 }
9181
9182 /* Check engine variants don't point back on themselves (either directly or via a loop) then set appropriate flags
9183 * on variant engine. This is performed separately as all variant engines need to have been resolved. */
9184 for (Engine *e : Engine::Iterate()) {
9185 EngineID parent = e->info.variant_id;
9186 while (parent != INVALID_ENGINE) {
9187 parent = Engine::Get(parent)->info.variant_id;
9188 if (parent != e->index) continue;
9189
9190 /* Engine looped back on itself, so clear the variant. */
9191 e->info.variant_id = INVALID_ENGINE;
9192
9193 GrfMsg(1, "FinaliseEngineArray: Variant of engine {:x} in '{}' loops back on itself", _engine_mngr[e->index].internal_id, e->GetGRF()->filename);
9194 break;
9195 }
9196
9197 if (e->info.variant_id != INVALID_ENGINE) {
9198 Engine::Get(e->info.variant_id)->display_flags |= EngineDisplayFlags::HasVariants | EngineDisplayFlags::IsFolded;
9199 }
9200 }
9201 }
9202
9204 void FinaliseCargoArray()
9205 {
9206 for (CargoSpec &cs : CargoSpec::array) {
9207 if (cs.town_production_effect == INVALID_TPE) {
9208 /* Set default town production effect by cargo label. */
9209 switch (cs.label) {
9210 case 'PASS': cs.town_production_effect = TPE_PASSENGERS; break;
9211 case 'MAIL': cs.town_production_effect = TPE_MAIL; break;
9212 default: cs.town_production_effect = TPE_NONE; break;
9213 }
9214 }
9215 if (!cs.IsValid()) {
9216 cs.name = cs.name_single = cs.units_volume = STR_NEWGRF_INVALID_CARGO;
9217 cs.quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9218 cs.abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9219 }
9220 }
9221 }
9222
9234 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const std::string &filename)
9235 {
9236 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9237 (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9238 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9239 (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9240 next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9241 hs->enabled = false;
9242 if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9243 return false;
9244 }
9245
9246 /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9247 * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9248 * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9249 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9250 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9251 hs->enabled = false;
9252 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);
9253 return false;
9254 }
9255
9256 /* Substitute type is also used for override, and having an override with a different size causes crashes.
9257 * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9258 if (!filename.empty() && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9259 hs->enabled = false;
9260 Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9261 return false;
9262 }
9263
9264 /* Make sure that additional parts of multitile houses are not available. */
9265 if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9266 hs->enabled = false;
9267 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);
9268 return false;
9269 }
9270
9271 return true;
9272 }
9273
9280 static void EnsureEarlyHouse(HouseZones bitmask)
9281 {
9282 TimerGameCalendar::Year min_year = CalendarTime::MAX_YEAR;
9283
9284 for (int i = 0; i < NUM_HOUSES; i++) {
9285 HouseSpec *hs = HouseSpec::Get(i);
9286 if (hs == nullptr || !hs->enabled) continue;
9287 if ((hs->building_availability & bitmask) != bitmask) continue;
9288 if (hs->min_year < min_year) min_year = hs->min_year;
9289 }
9290
9291 if (min_year == 0) return;
9292
9293 for (int i = 0; i < NUM_HOUSES; i++) {
9294 HouseSpec *hs = HouseSpec::Get(i);
9295 if (hs == nullptr || !hs->enabled) continue;
9296 if ((hs->building_availability & bitmask) != bitmask) continue;
9297 if (hs->min_year == min_year) hs->min_year = 0;
9298 }
9299 }
9300
9307 static void FinaliseHouseArray()
9308 {
9309 /* If there are no houses with start dates before 1930, then all houses
9310 * with start dates of 1930 have them reset to 0. This is in order to be
9311 * compatible with TTDPatch, where if no houses have start dates before
9312 * 1930 and the date is before 1930, the game pretends that this is 1930.
9313 * If there have been any houses defined with start dates before 1930 then
9314 * the dates are left alone.
9315 * On the other hand, why 1930? Just 'fix' the houses with the lowest
9316 * minimum introduction date to 0.
9317 */
9318 for (GRFFile * const file : _grf_files) {
9319 if (file->housespec.empty()) continue;
9320
9321 size_t num_houses = file->housespec.size();
9322 for (size_t i = 0; i < num_houses; i++) {
9323 HouseSpec *hs = file->housespec[i].get();
9324
9325 if (hs == nullptr) continue;
9326
9327 const HouseSpec *next1 = (i + 1 < num_houses ? file->housespec[i + 1].get() : nullptr);
9328 const HouseSpec *next2 = (i + 2 < num_houses ? file->housespec[i + 2].get() : nullptr);
9329 const HouseSpec *next3 = (i + 3 < num_houses ? file->housespec[i + 3].get() : nullptr);
9330
9331 if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9332
9333 _house_mngr.SetEntitySpec(hs);
9334 }
9335 }
9336
9337 for (size_t i = 0; i < NUM_HOUSES; i++) {
9338 HouseSpec *hs = HouseSpec::Get(i);
9339 const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9340 const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9341 const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9342
9343 /* We need to check all houses again to we are sure that multitile houses
9344 * did get consecutive IDs and none of the parts are missing. */
9345 if (!IsHouseSpecValid(hs, next1, next2, next3, std::string{})) {
9346 /* GetHouseNorthPart checks 3 houses that are directly before
9347 * it in the house pool. If any of those houses have multi-tile
9348 * flags set it assumes it's part of a multitile house. Since
9349 * we can have invalid houses in the pool marked as disabled, we
9350 * don't want to have them influencing valid tiles. As such set
9351 * building_flags to zero here to make sure any house following
9352 * this one in the pool is properly handled as 1x1 house. */
9353 hs->building_flags = TILE_NO_FLAG;
9354 }
9355 }
9356
9357 HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9358 EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9359 EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9360 EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9361 EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9362 EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9363
9364 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9365 EnsureEarlyHouse(HZ_ZON1 | HZ_SUBARTC_ABOVE);
9366 EnsureEarlyHouse(HZ_ZON2 | HZ_SUBARTC_ABOVE);
9367 EnsureEarlyHouse(HZ_ZON3 | HZ_SUBARTC_ABOVE);
9368 EnsureEarlyHouse(HZ_ZON4 | HZ_SUBARTC_ABOVE);
9369 EnsureEarlyHouse(HZ_ZON5 | HZ_SUBARTC_ABOVE);
9370 }
9371 }
9372
9378 static void FinaliseIndustriesArray()
9379 {
9380 for (GRFFile * const file : _grf_files) {
9381 for (const auto &indsp : file->industryspec) {
9382 if (indsp == nullptr || !indsp->enabled) continue;
9383
9384 StringID strid;
9385 /* process the conversion of text at the end, so to be sure everything will be fine
9386 * and available. Check if it does not return undefind marker, which is a very good sign of a
9387 * substitute industry who has not changed the string been examined, thus using it as such */
9388 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9389 if (strid != STR_UNDEFINED) indsp->name = strid;
9390
9391 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9392 if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9393
9394 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9395 if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9396
9397 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9398 if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9399
9400 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9401 if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9402
9403 if (indsp->station_name != STR_NULL) {
9404 /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9405 * station's name. Don't want to lose the value, therefore, do not process. */
9406 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9407 if (strid != STR_UNDEFINED) indsp->station_name = strid;
9408 }
9409
9410 _industry_mngr.SetEntitySpec(indsp.get());
9411 }
9412
9413 for (const auto &indtsp : file->indtspec) {
9414 if (indtsp != nullptr) {
9415 _industile_mngr.SetEntitySpec(indtsp.get());
9416 }
9417 }
9418 }
9419
9420 for (auto &indsp : _industry_specs) {
9421 if (indsp.enabled && indsp.grf_prop.grffile != nullptr) {
9422 for (auto &conflicting : indsp.conflicting) {
9423 conflicting = MapNewGRFIndustryType(conflicting, indsp.grf_prop.grffile->grfid);
9424 }
9425 }
9426 if (!indsp.enabled) {
9427 indsp.name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9428 }
9429 }
9430 }
9431
9437 static void FinaliseObjectsArray()
9438 {
9439 for (GRFFile * const file : _grf_files) {
9440 for (auto &objectspec : file->objectspec) {
9441 if (objectspec != nullptr && objectspec->grf_prop.grffile != nullptr && objectspec->IsEnabled()) {
9442 _object_mngr.SetEntitySpec(objectspec.get());
9443 }
9444 }
9445 }
9446
9447 ObjectSpec::BindToClasses();
9448 }
9449
9455 static void FinaliseAirportsArray()
9456 {
9457 for (GRFFile * const file : _grf_files) {
9458 for (auto &as : file->airportspec) {
9459 if (as != nullptr && as->enabled) {
9460 _airport_mngr.SetEntitySpec(as.get());
9461 }
9462 }
9463
9464 for (auto &ats : file->airtspec) {
9465 if (ats != nullptr && ats->enabled) {
9466 _airporttile_mngr.SetEntitySpec(ats.get());
9467 }
9468 }
9469 }
9470 }
9471
9472 /* Here we perform initial decoding of some special sprites (as are they
9473 * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9474 * partial implementation yet).
9475 * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9476 * a crafted invalid GRF file. We should tell that to the user somehow, or
9477 * better make this more robust in the future. */
9478 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
9479 {
9480 /* XXX: There is a difference between staged loading in TTDPatch and
9481 * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9482 * during stage 1, whilst action 3 is carried out during stage 2 (to
9483 * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9484 * IDs are valid only within a given set (action 1) block, and may be
9485 * overwritten after action 3 associates them. But overwriting happens
9486 * in an earlier stage than associating, so... We just process actions
9487 * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9488 * --pasky
9489 * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9490 * is not in memory and scanning the file every time would be too expensive.
9491 * In other stages we skip action 0x10 since it's already dealt with. */
9492 static const SpecialSpriteHandler handlers[][GLS_END] = {
9493 /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9494 /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9495 /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9496 /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9497 /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9498 /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9499 /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9500 /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9501 /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9502 /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9503 /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9504 /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9505 /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9506 /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9507 /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9508 /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9509 /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9510 /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9511 /* 0x12 */ { SkipAct12, SkipAct12, SkipAct12, SkipAct12, SkipAct12, LoadFontGlyph, },
9512 /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9513 /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9514 };
9515
9516 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9517
9518 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9519 if (it == _grf_line_to_action6_sprite_override.end()) {
9520 /* No preloaded sprite to work with; read the
9521 * pseudo sprite content. */
9522 _cur.file->ReadBlock(buf, num);
9523 } else {
9524 /* Use the preloaded sprite data. */
9525 buf = _grf_line_to_action6_sprite_override[location].data();
9526 GrfMsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9527
9528 /* Skip the real (original) content of this action. */
9529 _cur.file->SeekTo(num, SEEK_CUR);
9530 }
9531
9532 ByteReader br(buf, buf + num);
9533 ByteReader *bufp = &br;
9534
9535 try {
9536 byte action = bufp->ReadByte();
9537
9538 if (action == 0xFF) {
9539 GrfMsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9540 } else if (action == 0xFE) {
9541 GrfMsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9542 } else if (action >= lengthof(handlers)) {
9543 GrfMsg(7, "DecodeSpecialSprite: Skipping unknown action 0x{:02X}", action);
9544 } else if (handlers[action][stage] == nullptr) {
9545 GrfMsg(7, "DecodeSpecialSprite: Skipping action 0x{:02X} in stage {}", action, stage);
9546 } else {
9547 GrfMsg(7, "DecodeSpecialSprite: Handling action 0x{:02X} in stage {}", action, stage);
9548 handlers[action][stage](bufp);
9549 }
9550 } catch (...) {
9551 GrfMsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9552 DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9553 }
9554 }
9555
9562 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9563 {
9564 _cur.file = &file;
9565 _cur.grfconfig = config;
9566
9567 Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9568
9569 byte grf_container_version = file.GetContainerVersion();
9570 if (grf_container_version == 0) {
9571 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9572 return;
9573 }
9574
9575 if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9576 /* We need the sprite offsets in the init stage for NewGRF sounds
9577 * and in the activation stage for real sprites. */
9578 ReadGRFSpriteOffsets(file);
9579 } else {
9580 /* Skip sprite section offset if present. */
9581 if (grf_container_version >= 2) file.ReadDword();
9582 }
9583
9584 if (grf_container_version >= 2) {
9585 /* Read compression value. */
9586 byte compression = file.ReadByte();
9587 if (compression != 0) {
9588 Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9589 return;
9590 }
9591 }
9592
9593 /* Skip the first sprite; we don't care about how many sprites this
9594 * does contain; newest TTDPatches and George's longvehicles don't
9595 * neither, apparently. */
9596 uint32_t num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9597 if (num == 4 && file.ReadByte() == 0xFF) {
9598 file.ReadDword();
9599 } else {
9600 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9601 return;
9602 }
9603
9604 _cur.ClearDataForNextFile();
9605
9606 ReusableBuffer<byte> buf;
9607
9608 while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9609 byte type = file.ReadByte();
9610 _cur.nfo_line++;
9611
9612 if (type == 0xFF) {
9613 if (_cur.skip_sprites == 0) {
9614 DecodeSpecialSprite(buf.Allocate(num), num, stage);
9615
9616 /* Stop all processing if we are to skip the remaining sprites */
9617 if (_cur.skip_sprites == -1) break;
9618
9619 continue;
9620 } else {
9621 file.SkipBytes(num);
9622 }
9623 } else {
9624 if (_cur.skip_sprites == 0) {
9625 GrfMsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9626 DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9627 break;
9628 }
9629
9630 if (grf_container_version >= 2 && type == 0xFD) {
9631 /* Reference to data section. Container version >= 2 only. */
9632 file.SkipBytes(num);
9633 } else {
9634 file.SkipBytes(7);
9635 SkipSpriteData(file, type, num - 8);
9636 }
9637 }
9638
9639 if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9640 }
9641 }
9642
9651 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9652 {
9653 const std::string &filename = config->filename;
9654
9655 /* A .grf file is activated only if it was active when the game was
9656 * started. If a game is loaded, only its active .grfs will be
9657 * reactivated, unless "loadallgraphics on" is used. A .grf file is
9658 * considered active if its action 8 has been processed, i.e. its
9659 * action 8 hasn't been skipped using an action 7.
9660 *
9661 * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9662 * carried out. All others are ignored, because they only need to be
9663 * processed once at initialization. */
9664 if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9665 _cur.grffile = GetFileByFilename(filename);
9666 if (_cur.grffile == nullptr) UserError("File '{}' lost in cache.\n", filename);
9667 if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9668 if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9669 }
9670
9671 bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9672 if (temporary) {
9673 SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9674 LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9675 } else {
9676 LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9677 }
9678 }
9679
9687 static void ActivateOldShore()
9688 {
9689 /* Use default graphics, if no shore sprites were loaded.
9690 * Should not happen, as the base set's extra grf should include some. */
9691 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
9692
9693 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
9694 DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9695 DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9696 DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9697 DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9698 DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9699 DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9700 DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9701 DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9702 }
9703
9704 if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
9705 DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9706 DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9707 DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9708 DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9709 DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9710 DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9711 DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9712 DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9713
9714 /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9715 * If they would be used somewhen, then these grass tiles will most like not look as needed */
9716 DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9717 DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9718 }
9719 }
9720
9724 static void ActivateOldTramDepot()
9725 {
9726 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK) {
9727 DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9728 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9729 DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9730 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9731 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9732 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9733 }
9734 }
9735
9739 static void FinalisePriceBaseMultipliers()
9740 {
9741 extern const PriceBaseSpec _price_base_specs[];
9743 static const uint32_t override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9744
9745 /* Evaluate grf overrides */
9746 int num_grfs = (uint)_grf_files.size();
9747 std::vector<int> grf_overrides(num_grfs, -1);
9748 for (int i = 0; i < num_grfs; i++) {
9749 GRFFile *source = _grf_files[i];
9750 uint32_t override = _grf_id_overrides[source->grfid];
9751 if (override == 0) continue;
9752
9753 GRFFile *dest = GetFileByGRFID(override);
9754 if (dest == nullptr) continue;
9755
9756 grf_overrides[i] = find_index(_grf_files, dest);
9757 assert(grf_overrides[i] >= 0);
9758 }
9759
9760 /* Override features and price base multipliers of earlier loaded grfs */
9761 for (int i = 0; i < num_grfs; i++) {
9762 if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9763 GRFFile *source = _grf_files[i];
9764 GRFFile *dest = _grf_files[grf_overrides[i]];
9765
9766 uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9767 source->grf_features |= features;
9768 dest->grf_features |= features;
9769
9770 for (Price p = PR_BEGIN; p < PR_END; p++) {
9771 /* No price defined -> nothing to do */
9772 if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9773 Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9774 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9775 }
9776 }
9777
9778 /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9779 for (int i = num_grfs - 1; i >= 0; i--) {
9780 if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9781 GRFFile *source = _grf_files[i];
9782 GRFFile *dest = _grf_files[grf_overrides[i]];
9783
9784 uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9785 source->grf_features |= features;
9786 dest->grf_features |= features;
9787
9788 for (Price p = PR_BEGIN; p < PR_END; p++) {
9789 /* Already a price defined -> nothing to do */
9790 if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9791 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9792 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9793 }
9794 }
9795
9796 /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9797 for (int i = 0; i < num_grfs; i++) {
9798 if (grf_overrides[i] < 0) continue;
9799 GRFFile *source = _grf_files[i];
9800 GRFFile *dest = _grf_files[grf_overrides[i]];
9801
9802 uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9803 source->grf_features |= features;
9804 dest->grf_features |= features;
9805
9806 for (Price p = PR_BEGIN; p < PR_END; p++) {
9807 if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9808 if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9809 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9810 }
9811 source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9812 }
9813 }
9814
9815 /* Apply fallback prices for grf version < 8 */
9816 for (GRFFile * const file : _grf_files) {
9817 if (file->grf_version >= 8) continue;
9818 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9819 for (Price p = PR_BEGIN; p < PR_END; p++) {
9820 Price fallback_price = _price_base_specs[p].fallback_price;
9821 if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9822 /* No price multiplier has been set.
9823 * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9824 price_base_multipliers[p] = price_base_multipliers[fallback_price];
9825 }
9826 }
9827 }
9828
9829 /* Decide local/global scope of price base multipliers */
9830 for (GRFFile * const file : _grf_files) {
9831 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9832 for (Price p = PR_BEGIN; p < PR_END; p++) {
9833 if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9834 /* No multiplier was set; set it to a neutral value */
9835 price_base_multipliers[p] = 0;
9836 } else {
9837 if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9838 /* The grf does not define any objects of the feature,
9839 * so it must be a difficulty setting. Apply it globally */
9840 Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9841 SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9842 price_base_multipliers[p] = 0;
9843 } else {
9844 Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9845 }
9846 }
9847 }
9848 }
9849 }
9850
9851 extern void InitGRFTownGeneratorNames();
9852
9854 static void AfterLoadGRFs()
9855 {
9856 for (StringIDMapping &it : _string_to_grf_mapping) {
9857 *it.target = MapGRFStringID(it.grfid, it.source);
9858 }
9859 _string_to_grf_mapping.clear();
9860
9861 /* Clear the action 6 override sprites. */
9862 _grf_line_to_action6_sprite_override.clear();
9863
9864 /* Polish cargoes */
9865 FinaliseCargoArray();
9866
9867 /* Pre-calculate all refit masks after loading GRF files. */
9868 CalculateRefitMasks();
9869
9870 /* Polish engines */
9871 FinaliseEngineArray();
9872
9873 /* Set the actually used Canal properties */
9874 FinaliseCanals();
9875
9876 /* Add all new houses to the house array. */
9877 FinaliseHouseArray();
9878
9879 /* Add all new industries to the industry array. */
9880 FinaliseIndustriesArray();
9881
9882 /* Add all new objects to the object array. */
9883 FinaliseObjectsArray();
9884
9885 InitializeSortedCargoSpecs();
9886
9887 /* Sort the list of industry types. */
9888 SortIndustryTypes();
9889
9890 /* Create dynamic list of industry legends for smallmap_gui.cpp */
9891 BuildIndustriesLegend();
9892
9893 /* Build the routemap legend, based on the available cargos */
9894 BuildLinkStatsLegend();
9895
9896 /* Add all new airports to the airports array. */
9897 FinaliseAirportsArray();
9898 BindAirportSpecs();
9899
9900 /* Update the townname generators list */
9901 InitGRFTownGeneratorNames();
9902
9903 /* Run all queued vehicle list order changes */
9904 CommitVehicleListOrderChanges();
9905
9906 /* Load old shore sprites in new position, if they were replaced by ActionA */
9907 ActivateOldShore();
9908
9909 /* Load old tram depot sprites in new position, if no new ones are present */
9910 ActivateOldTramDepot();
9911
9912 /* Set up custom rail types */
9913 InitRailTypes();
9914 InitRoadTypes();
9915
9916 for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9917 if (_gted[e->index].rv_max_speed != 0) {
9918 /* Set RV maximum speed from the mph/0.8 unit value */
9919 e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9920 }
9921
9922 RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9923
9924 const GRFFile *file = e->GetGRF();
9925 if (file == nullptr || _gted[e->index].roadtramtype == 0) {
9926 e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
9927 continue;
9928 }
9929
9930 /* Remove +1 offset. */
9931 _gted[e->index].roadtramtype--;
9932
9933 const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
9934 if (_gted[e->index].roadtramtype < list->size())
9935 {
9936 RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
9937 RoadType rt = GetRoadTypeByLabel(rtl);
9938 if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
9939 e->u.road.roadtype = rt;
9940 continue;
9941 }
9942 }
9943
9944 /* Road type is not available, so disable this engine */
9945 e->info.climates = 0;
9946 }
9947
9948 for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
9949 RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
9950 if (railtype == INVALID_RAILTYPE) {
9951 /* Rail type is not available, so disable this engine */
9952 e->info.climates = 0;
9953 } else {
9954 e->u.rail.railtype = railtype;
9955 e->u.rail.intended_railtype = railtype;
9956 }
9957 }
9958
9959 SetYearEngineAgingStops();
9960
9961 FinalisePriceBaseMultipliers();
9962
9963 /* Deallocate temporary loading data */
9964 _gted.clear();
9965 _grm_sprites.clear();
9966 }
9967
9973 void LoadNewGRF(uint load_index, uint num_baseset)
9974 {
9975 /* In case of networking we need to "sync" the start values
9976 * so all NewGRFs are loaded equally. For this we use the
9977 * start date of the game and we set the counters, etc. to
9978 * 0 so they're the same too. */
9979 TimerGameCalendar::Date date = TimerGameCalendar::date;
9980 TimerGameCalendar::Year year = TimerGameCalendar::year;
9981 TimerGameCalendar::DateFract date_fract = TimerGameCalendar::date_fract;
9982
9983 TimerGameEconomy::Date economy_date = TimerGameEconomy::date;
9984 TimerGameEconomy::Year economy_year = TimerGameEconomy::year;
9985 TimerGameEconomy::DateFract economy_date_fract = TimerGameEconomy::date_fract;
9986
9987 uint64_t tick_counter = TimerGameTick::counter;
9988 byte display_opt = _display_opt;
9989
9990 if (_networking) {
9991 TimerGameCalendar::year = _settings_game.game_creation.starting_year;
9992 TimerGameCalendar::date = TimerGameCalendar::ConvertYMDToDate(TimerGameCalendar::year, 0, 1);
9993 TimerGameCalendar::date_fract = 0;
9994
9995 TimerGameEconomy::year = _settings_game.game_creation.starting_year.base();
9996 TimerGameEconomy::date = TimerGameEconomy::ConvertYMDToDate(TimerGameEconomy::year, 0, 1);
9997 TimerGameEconomy::date_fract = 0;
9998
9999 TimerGameTick::counter = 0;
10000 _display_opt = 0;
10001 }
10002
10003 InitializeGRFSpecial();
10004
10005 ResetNewGRFData();
10006
10007 /*
10008 * Reset the status of all files, so we can 'retry' to load them.
10009 * This is needed when one for example rearranges the NewGRFs in-game
10010 * and a previously disabled NewGRF becomes usable. If it would not
10011 * be reset, the NewGRF would remain disabled even though it should
10012 * have been enabled.
10013 */
10014 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10015 if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
10016 }
10017
10018 _cur.spriteid = load_index;
10019
10020 /* Load newgrf sprites
10021 * in each loading stage, (try to) open each file specified in the config
10022 * and load information from it. */
10023 for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
10024 /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
10025 * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
10026 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10027 if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
10028 }
10029
10030 if (stage == GLS_RESERVE) {
10031 static const uint32_t overrides[][2] = {
10032 { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
10033 { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
10034 { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
10035 };
10036 for (size_t i = 0; i < lengthof(overrides); i++) {
10037 SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
10038 }
10039 }
10040
10041 uint num_grfs = 0;
10042 uint num_non_static = 0;
10043
10044 _cur.stage = stage;
10045 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10046 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
10047 if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
10048
10049 Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
10050 if (!FioCheckFileExists(c->filename, subdir)) {
10051 Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
10052 c->status = GCS_NOT_FOUND;
10053 continue;
10054 }
10055
10056 if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
10057
10058 if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
10059 if (num_non_static == NETWORK_MAX_GRF_COUNT) {
10060 Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
10061 c->status = GCS_DISABLED;
10062 c->error = {STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED};
10063 continue;
10064 }
10065 num_non_static++;
10066 }
10067
10068 num_grfs++;
10069
10070 LoadNewGRFFile(c, stage, subdir, false);
10071 if (stage == GLS_RESERVE) {
10072 SetBit(c->flags, GCF_RESERVED);
10073 } else if (stage == GLS_ACTIVATION) {
10074 ClrBit(c->flags, GCF_RESERVED);
10075 assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
10076 ClearTemporaryNewGRFData(_cur.grffile);
10077 BuildCargoTranslationMap();
10078 Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
10079 } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
10080 /* We're not going to activate this, so free whatever data we allocated */
10081 ClearTemporaryNewGRFData(_cur.grffile);
10082 }
10083 }
10084 }
10085
10086 /* Pseudo sprite processing is finished; free temporary stuff */
10087 _cur.ClearDataForNextFile();
10088
10089 /* Call any functions that should be run after GRFs have been loaded. */
10090 AfterLoadGRFs();
10091
10092 /* Now revert back to the original situation */
10093 TimerGameCalendar::year = year;
10094 TimerGameCalendar::date = date;
10095 TimerGameCalendar::date_fract = date_fract;
10096
10097 TimerGameEconomy::year = economy_year;
10098 TimerGameEconomy::date = economy_date;
10099 TimerGameEconomy::date_fract = economy_date_fract;
10100
10101 TimerGameTick::counter = tick_counter;
10102 _display_opt = display_opt;
10103 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
ResetCustomHouses
static void ResetCustomHouses()
Reset and clear all NewGRF houses.
Definition: newgrf.cpp:8691
RoadTypeInfo::flags
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:127
ChangeGRFName
static bool ChangeGRFName(byte langid, const char *str)
Callback function for 'INFO'->'NAME' to add a translation to the newgrf name.
Definition: newgrf.cpp:8087
AllowedSubtags::call_handler
bool call_handler
True if there is a callback function for this node, false if there is a list of subnodes.
Definition: newgrf.cpp:8367
RoadTypeInfo::new_engine
StringID new_engine
Name of an engine for this type of road in the engine preview GUI.
Definition: road.h:108
StationChangeInfo
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
Define properties for stations.
Definition: newgrf.cpp:1907
ParamSet
static void ParamSet(ByteReader *buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:7380
GRFLocation
Definition: newgrf.cpp:362
CalculateRefitMasks
static void CalculateRefitMasks()
Precalculate refit masks from cargo classes for all vehicles.
Definition: newgrf.cpp:8961
OBJECT_SIZE_1X1
static const uint8_t OBJECT_SIZE_1X1
The value of a NewGRF's size property when the object is 1x1 tiles: low nibble for X,...
Definition: newgrf_object.h:43
GRFP_USE_MASK
@ GRFP_USE_MASK
Bitmask to get only the use palette use states.
Definition: newgrf_config.h:68
RoadTypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: road.h:104
HouseSpec::removal_cost
byte removal_cost
cost multiplier for removing it
Definition: house.h:103
CargoType
CargoType
Available types of cargo.
Definition: cargo_type.h:23
RoadStopSpec::clear_cost_multiplier
uint8_t clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_roadstop.h:147
AllocateSound
SoundEntry * AllocateSound(uint num)
Allocate sound slots.
Definition: newgrf_sound.cpp:31
RailVehicleInfo::pow_wag_power
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:56
GRFTempEngineData::UpdateRefittability
void UpdateRefittability(bool non_empty)
Update the summary refittability on setting a refittability property.
Definition: newgrf.cpp:341
RailVehicleInfo::curve_speed_mod
int16_t curve_speed_mod
Modifier to maximum speed in curves (fixed-point binary with 8 fractional bits)
Definition: engine_type.h:63
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:205
Action5Type::sprite_base
SpriteID sprite_base
Load the sprites starting from this sprite.
Definition: newgrf.cpp:6390
OrderSettings::improved_load
bool improved_load
improved loading algorithm
Definition: settings_type.h:506
GRFTownName::styles
std::vector< TownNameStyle > styles
Style names defined by the Town Name NewGRF.
Definition: newgrf_townname.h:42
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:25
RoadTypeInfo
Definition: road.h:78
DuplicateTileTable
static void DuplicateTileTable(AirportSpec *as)
Create a copy of the tile table so it can be freed later without problems.
Definition: newgrf.cpp:3856
NUM_STATIONS_PER_GRF
static const uint NUM_STATIONS_PER_GRF
The maximum amount of stations a single GRF is allowed to add.
Definition: newgrf.cpp:316
PROP_TRAIN_SPEED
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
Definition: newgrf_properties.h:21
GRFConfig::info
GRFTextWrapper info
NOSAVE: GRF info (author, copyright, ...) (Action 0x08)
Definition: newgrf_config.h:158
AllowedSubtags::AllowedSubtags
AllowedSubtags()
Create empty subtags object used to identify the end of a list.
Definition: newgrf.cpp:8302
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:29
RAILTYPE_MAGLEV
@ RAILTYPE_MAGLEV
Maglev.
Definition: rail_type.h:32
RailTypeInfo::introduction_date
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: rail.h:255
ResetCustomObjects
static void ResetCustomObjects()
Reset and clear all NewObjects.
Definition: newgrf.cpp:8729
RoadStopAvailabilityType
RoadStopAvailabilityType
Various different options for availability, restricting the roadstop to be only for busses or for tru...
Definition: newgrf_roadstop.h:46
RailVehicleInfo::pow_wag_weight
byte pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition: engine_type.h:57
Engine::IterateType
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
Definition: engine_base.h:186
IndustrySpec::map_colour
byte map_colour
colour used for the small map
Definition: industrytype.h:124
EngineDisplayFlags::HasVariants
@ HasVariants
Set if engine has variants.
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
TPE_NONE
@ TPE_NONE
Town will not produce this cargo type.
Definition: cargotype.h:38
LanguageMetadata
Make sure the size is right.
Definition: language.h:93
VE_DISABLE_EFFECT
@ VE_DISABLE_EFFECT
Flag to disable visual effect.
Definition: vehicle_base.h:91
newgrf_station.h
SetUnicodeGlyph
void SetUnicodeGlyph(FontSize size, char32_t key, SpriteID sprite)
Map a SpriteID to the font size and key.
Definition: fontcache.h:167
newgrf_house.h
TPE_MAIL
@ TPE_MAIL
Cargo behaves mail-like for production.
Definition: cargotype.h:40
GRFFile::language_map
struct LanguageMap * language_map
Mappings related to the languages.
Definition: newgrf.h:143
GRFFile::roadtype_list
std::vector< RoadTypeLabel > roadtype_list
Roadtype translation table (road)
Definition: newgrf.h:135
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:335
EngineOverrideManager::ResetToDefaultMapping
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition: engine.cpp:507
CargoSpec::label
CargoLabel label
Unique label of the cargo type.
Definition: cargotype.h:72
AircraftVehicleInfo::max_range
uint16_t max_range
Maximum range of this aircraft.
Definition: engine_type.h:110
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition: timer_game_tick.h:33
StationSpec::flags
byte flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Definition: newgrf_station.h:159
OBJECT_FLAG_2CC_COLOUR
@ OBJECT_FLAG_2CC_COLOUR
Object wants 2CC colour mapping.
Definition: newgrf_object.h:34
LanguageMap::case_map
std::vector< Mapping > case_map
Mapping of NewGRF and OpenTTD IDs for cases.
Definition: newgrf_text.h:67
PROP_TRAIN_CARGO_CAPACITY
@ PROP_TRAIN_CARGO_CAPACITY
Capacity (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:24
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:630
ResetCustomAirports
static void ResetCustomAirports()
Reset and clear all NewGRF airports.
Definition: newgrf.cpp:8699
AircraftVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
Definition: engine_type.h:107
GRFTextList
std::vector< GRFText > GRFTextList
A GRF text with a list of translations.
Definition: newgrf_text.h:28
PROP_ROADVEH_TRACTIVE_EFFORT
@ PROP_ROADVEH_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
Definition: newgrf_properties.h:39
SNOW_LINE_DAYS
static const uint SNOW_LINE_DAYS
Number of days in each month in the snow line table.
Definition: landscape.h:17
ObjectChangeInfo
static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for objects.
Definition: newgrf.cpp:4106
RoadTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: road.h:105
TimerGameConst< struct Calendar >::DAYS_TILL_ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
The date of the first day of the original base year.
Definition: timer_game_common.h:184
GetFileByGRFID
static GRFFile * GetFileByGRFID(uint32_t grfid)
Obtain a NewGRF file by its grfID.
Definition: newgrf.cpp:403
DeterministicSpriteGroupRange
Definition: newgrf_spritegroup.h:160
GRFConfig::num_valid_params
uint8_t num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
Definition: newgrf_config.h:169
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition: newgrf_station.h:147
NUM_INDUSTRYTYPES_PER_GRF
static const IndustryType NUM_INDUSTRYTYPES_PER_GRF
maximum number of industry types per NewGRF; limited to 128 because bit 7 has a special meaning in so...
Definition: industry_type.h:23
SPR_SHORE_BASE
static const SpriteID SPR_SHORE_BASE
shore tiles - action 05-0D
Definition: sprites.h:224
IndustryProductionSpriteGroup::num_output
uint8_t num_output
How many add_output values are valid.
Definition: newgrf_spritegroup.h:275
TAE_FOOD
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:31
TLF_DODRAW
@ TLF_DODRAW
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
Definition: newgrf_commons.h:35
ReusableBuffer
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition: alloc_type.hpp:24
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:104
ShipVehicleChangeInfo
static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for ships.
Definition: newgrf.cpp:1551
GetRoadTypeByLabel
RoadType GetRoadTypeByLabel(RoadTypeLabel label, bool allow_alternate_labels)
Get the road type for a given label.
Definition: road.cpp:254
GRFError::custom_message
std::string custom_message
Custom message (if present)
Definition: newgrf_config.h:112
PROP_ROADVEH_COST_FACTOR
@ PROP_ROADVEH_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:35
IsInsideMM
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:268
GCS_ACTIVATED
@ GCS_ACTIVATED
GRF file has been activated.
Definition: newgrf_config.h:39
ObjectSpec
Allow incrementing of ObjectClassID variables.
Definition: newgrf_object.h:60
RoadStopSpec
Road stop specification.
Definition: newgrf_roadstop.h:122
TileLayoutRegisters::dodraw
uint8_t dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
Definition: newgrf_commons.h:92
ObjectSpec::grf_prop
GRFFilePropsBase< 2 > grf_prop
Properties related the the grf file.
Definition: newgrf_object.h:62
GrfProcessingState::grffile
GRFFile * grffile
Currently processed GRF file.
Definition: newgrf.cpp:105
DrawTileSeqStruct::IsParentSprite
bool IsParentSprite() const
Check whether this is a parent sprite with a boundingbox.
Definition: sprite.h:47
BridgeSpec::flags
byte flags
bit 0 set: disable drawing of far pillars.
Definition: bridge.h:53
RoadTypeInfo::introduction_date
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: road.h:166
NamePartList::maxprob
uint16_t maxprob
Total probability of all parts.
Definition: newgrf_townname.h:27
_engine_offsets
const uint8_t _engine_offsets[4]
Offset of the first engine of each vehicle type in original engine data.
Definition: engine.cpp:61
GetRailTypeInfo
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:307
IsValidNewGRFImageIndex
static bool IsValidNewGRFImageIndex(uint8_t image_index)
Helper to check whether an image index is valid for a particular NewGRF vehicle.
Definition: newgrf.cpp:206
ResetCustomIndustries
static void ResetCustomIndustries()
Reset and clear all NewGRF industries.
Definition: newgrf.cpp:8720
PROP_TRAIN_RUNNING_COST_FACTOR
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:23
TimerGameCalendar::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_calendar.h:35
smallmap_gui.h
_grf_files
static std::vector< GRFFile * > _grf_files
List of all loaded GRF files.
Definition: newgrf.cpp:68
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1527
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:356
ShipVehicleInfo::canal_speed_frac
byte canal_speed_frac
Fraction of maximum speed for canal/river tiles.
Definition: engine_type.h:78
TLF_CHILD_X_OFFSET
@ TLF_CHILD_X_OFFSET
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:43
RoadTypeInfo::introduces_roadtypes
RoadTypes introduces_roadtypes
Bitmask of which other roadtypes are introduced when this roadtype is introduced.
Definition: road.h:177
GRFFile::price_base_multipliers
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:149
FeatureTownName
static void FeatureTownName(ByteReader *buf)
Action 0x0F - Define Town names.
Definition: newgrf.cpp:7730
Map::LogX
static debug_inline uint LogX()
Logarithm of the map size along the X side.
Definition: map_func.h:251
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, BranchHandler handler)
Create a branch node with a callback handler.
Definition: newgrf.cpp:8336
HouseSpec::max_year
TimerGameCalendar::Year max_year
last year it can be built
Definition: house.h:101
IndustriesChangeInfo
static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
Define properties for industries.
Definition: newgrf.cpp:3481
DeterministicSpriteGroup
Definition: newgrf_spritegroup.h:167
PROP_TRAIN_TRACTIVE_EFFORT
@ PROP_TRAIN_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
Definition: newgrf_properties.h:27
AllowedSubtags::branch
BranchHandler branch
Callback function for a branch node, only valid if type == 'C' && call_handler.
Definition: newgrf.cpp:8364
TimerGameEconomy::ConvertYMDToDate
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: timer_game_economy.cpp:66
timer_game_calendar.h
HandleNodes
static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
Handle the contents of a 'C' choice of an Action14.
Definition: newgrf.cpp:8559
EngineDisplayFlags::IsFolded
@ IsFolded
Set if display of variants should be folded (hidden).
HouseSpec::accepts_cargo
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:108
RoadTypeInfo::sorting_order
byte sorting_order
The sorting order of this roadtype for the toolbar dropdown.
Definition: road.h:182
AirportSpec::size_y
byte size_y
size of airport in y direction
Definition: newgrf_airport.h:108
NewGRFSpriteLayout::AllocateRegisters
void AllocateRegisters()
Allocate memory for register modifiers.
Definition: newgrf_commons.cpp:615
PALETTE_MODIFIER_COLOUR
@ PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition: sprites.h:1542
BASESET_DIR
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
currency.h
RoadStopSpec::name
StringID name
Name of this stop.
Definition: newgrf_roadstop.h:132
AnimationInfo::triggers
uint16_t triggers
The triggers that trigger animation.
Definition: newgrf_animation_type.h:22
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
NamePart::prob
byte prob
The relative probability of the following name to appear in the bottom 7 bits.
Definition: newgrf_townname.h:21
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:89
PROP_AIRCRAFT_MAIL_CAPACITY
@ PROP_AIRCRAFT_MAIL_CAPACITY
Mail Capacity.
Definition: newgrf_properties.h:53
RailTypeInfo::new_loco
StringID new_loco
Name of an engine for this type of rail in the engine preview GUI.
Definition: rail.h:181
AirportSpec::name
StringID name
name of this airport
Definition: newgrf_airport.h:113
CC_EXPRESS
@ CC_EXPRESS
Express cargo (Goods, Food, Candy, but also possible for passengers)
Definition: cargotype.h:55
FinaliseCanals
static void FinaliseCanals()
Set to use the correct action0 properties for each canal feature.
Definition: newgrf.cpp:9126
CanalProperties::callback_mask
uint8_t callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf.h:40
LanguageMap::plural_form
int plural_form
The plural form used for this language.
Definition: newgrf_text.h:68
CanalProperties::flags
uint8_t flags
Flags controlling display.
Definition: newgrf.h:41
CurrencySpec::symbol_pos
byte symbol_pos
The currency symbol is represented by two possible values, prefix and suffix Usage of one or the othe...
Definition: currency.h:90
EC_STEAM
@ EC_STEAM
Steam rail engine.
Definition: engine_type.h:34
PriceBaseSpec::grf_feature
uint grf_feature
GRF Feature that decides whether price multipliers apply locally or globally, #GSF_END if none.
Definition: economy_type.h:210
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
RandomizedSpriteGroup::cmp_mode
RandomizedSpriteGroupCompareMode cmp_mode
Check for these triggers:
Definition: newgrf_spritegroup.h:195
DeterministicSpriteGroupAdjust::parameter
byte parameter
Used for variables between 0x60 and 0x7F inclusive.
Definition: newgrf_spritegroup.h:151
VE_DEFAULT
@ VE_DEFAULT
Default value to indicate that visual effect should be based on engine class.
Definition: vehicle_base.h:95
A5BLOCK_INVALID
@ A5BLOCK_INVALID
unknown/not-implemented type
Definition: newgrf.cpp:6385
Action5BlockType
Action5BlockType
The type of action 5 type.
Definition: newgrf.cpp:6382
ChangeGRFParamLimits
static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PARAM'->param_num->'LIMI' to set the min/max value of a parameter.
Definition: newgrf.cpp:8234
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:234
PROP_ROADVEH_SHORTEN_FACTOR
@ PROP_ROADVEH_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:41
BridgeSpec::sprite_table
PalSpriteID ** sprite_table
table of sprites for drawing the bridge
Definition: bridge.h:52
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:134
ResetPersistentNewGRFData
void ResetPersistentNewGRFData()
Reset NewGRF data which is stored persistently in savegames.
Definition: newgrf.cpp:8863
PROP_SHIP_CARGO_CAPACITY
@ PROP_SHIP_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:45
ObjectSpec::generate_amount
uint8_t generate_amount
Number of objects which are attempted to be generated per 256^2 map during world generation.
Definition: newgrf_object.h:77
HouseExtraFlags
HouseExtraFlags
Definition: house.h:88
_bridge
BridgeSpec _bridge[MAX_BRIDGES]
The specification of all bridges.
Definition: tunnelbridge_cmd.cpp:52
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
GrfProcessingState::ClearDataForNextFile
void ClearDataForNextFile()
Clear temporary data before processing the next file in the current loading stage.
Definition: newgrf.cpp:116
PROP_AIRCRAFT_RUNNING_COST_FACTOR
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:51
RAILTYPE_MONO
@ RAILTYPE_MONO
Monorail.
Definition: rail_type.h:31
HouseSpec::enabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:111
AirportSpec::noise_level
byte noise_level
noise that this airport generates
Definition: newgrf_airport.h:109
ChangeGRFVersion
static bool ChangeGRFVersion(size_t len, ByteReader *buf)
Callback function for 'INFO'->'VRSN' to the version of the NewGRF.
Definition: newgrf.cpp:8168
IndustryProductionSpriteGroup::add_output
uint16_t add_output[INDUSTRY_NUM_OUTPUTS]
Add this much output cargo when successful (unsigned, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:276
SortIndustryTypes
void SortIndustryTypes()
Initialize the list of sorted industry types.
Definition: industry_gui.cpp:234
ResetPriceBaseMultipliers
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:891
ChangeGRFParamName
static bool ChangeGRFParamName(byte langid, const char *str)
Callback function for 'INFO'->'PARAM'->param_num->'NAME' to set the name of a parameter.
Definition: newgrf.cpp:8203
ResetRailTypes
void ResetRailTypes()
Reset all rail type information to its default values.
Definition: rail_cmd.cpp:65
GrfProcessingState::spritesets
std::map< uint, SpriteSet > spritesets[GSF_END]
Currently referenceable spritesets.
Definition: newgrf.cpp:96
StrMakeValid
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition: string.cpp:114
GrfProcessingState::spriteid
SpriteID spriteid
First available SpriteID for loading realsprites.
Definition: newgrf.cpp:101
GRFConfig::filename
std::string filename
Filename - either with or without full path.
Definition: newgrf_config.h:156
RailTypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:127
VehicleSettings::wagon_speed_limits
bool wagon_speed_limits
enable wagon speed limits
Definition: settings_type.h:522
CIR_INVALID_ID
@ CIR_INVALID_ID
Attempt to modify an invalid ID.
Definition: newgrf.cpp:983
GRFParameterInfo::param_nr
byte param_nr
GRF parameter to store content in.
Definition: newgrf_config.h:135
TLF_CUSTOM_PALETTE
@ TLF_CUSTOM_PALETTE
Palette is from Action 1 (moved to SPRITE_MODIFIER_CUSTOM_SPRITE in palette during loading).
Definition: newgrf_commons.h:38
ObjectSpec::height
uint8_t height
The height of this structure, in heightlevels; max MAX_TILE_HEIGHT.
Definition: newgrf_object.h:75
RailTypeInfo::alternate_labels
RailTypeLabelList alternate_labels
Rail type labels this type provides in addition to the main label.
Definition: rail.h:241
IndustryTileSpec::acceptance
std::array< int8_t, INDUSTRY_NUM_INPUTS > acceptance
Level of acceptance per cargo type (signed, may be negative!)
Definition: industrytype.h:156
IndustryTileSpec::callback_mask
uint8_t callback_mask
Bitmask of industry tile callbacks that have to be called.
Definition: industrytype.h:166
_tags_info
AllowedSubtags _tags_info[]
Action14 tags for the INFO node.
Definition: newgrf.cpp:8455
AnimationInfo::frames
uint8_t frames
The number of frames.
Definition: newgrf_animation_type.h:19
vehicle_base.h
ConvertTTDBasePrice
static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
Converts TTD(P) Base Price pointers into the enum used by OTTD See http://wiki.ttdpatch....
Definition: newgrf.cpp:958
fileio_func.h
GCS_NOT_FOUND
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:37
AirportSpec::min_year
TimerGameCalendar::Year min_year
first year the airport is available
Definition: newgrf_airport.h:111
newgrf_airport.h
SetupCargoForClimate
void SetupCargoForClimate(LandscapeID l)
Set up the default cargo types for the given landscape type.
Definition: cargotype.cpp:42
HouseSpec::callback_mask
uint16_t callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:115
build_industry.h
GRFTempEngineData::ctt_include_mask
CargoTypes ctt_include_mask
Cargo types always included in the refit mask.
Definition: newgrf.cpp:334
HouseSpec::building_name
StringID building_name
building name
Definition: house.h:104
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_economy.h:38
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:190
SetupEngines
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:563
GRFConfig::ident
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
Definition: newgrf_config.h:154
newgrf_townname.h
RailTypeInfo::introduction_required_railtypes
RailTypes introduction_required_railtypes
Bitmask of railtypes that are required for this railtype to be introduced at a given introduction_dat...
Definition: rail.h:261
AirportSpec::max_year
TimerGameCalendar::Year max_year
last year the airport is available
Definition: newgrf_airport.h:112
ttd_strnlen
size_t ttd_strnlen(const char *str, size_t maxlen)
Get the length of a string, within a limited buffer.
Definition: string_func.h:68
LiveryScheme
LiveryScheme
List of different livery schemes.
Definition: livery.h:21
AirportSpec::ResetAirports
static void ResetAirports()
This function initializes the airportspec array.
Definition: newgrf_airport.cpp:110
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:71
GetNewEngine
static Engine * GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access=false)
Returns the engine associated to a certain internal_id, resp.
Definition: newgrf.cpp:598
ReusableBuffer::Allocate
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition: alloc_type.hpp:42
GRFConfig::status
GRFStatus status
NOSAVE: GRFStatus, enum.
Definition: newgrf_config.h:165
GetNewGRFSoundID
SoundID GetNewGRFSoundID(const GRFFile *file, SoundID sound_id)
Resolve NewGRF sound ID.
Definition: newgrf_sound.cpp:169
VE_TYPE_COUNT
@ VE_TYPE_COUNT
Number of bits used for the effect type.
Definition: vehicle_base.h:85
town.h
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:716
NUM_OBJECTS_PER_GRF
static const ObjectType NUM_OBJECTS_PER_GRF
Number of supported objects per NewGRF.
Definition: object_type.h:24
BridgeSpec::speed
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: bridge.h:47
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition: cargotype.h:59
RoadStopSpec::cls_id
RoadStopClassID cls_id
The class to which this spec belongs.
Definition: newgrf_roadstop.h:130
GRFP_GRF_UNSET
@ GRFP_GRF_UNSET
The NewGRF provided no information.
Definition: newgrf_config.h:70
StrongType::Typedef
Templated helper to make a type-safe 'typedef' representing a single POD value.
Definition: strong_typedef_type.hpp:150
ObjectFlags
ObjectFlags
Various object behaviours.
Definition: newgrf_object.h:24
EngineInfo
Information about a vehicle.
Definition: engine_type.h:144
ChangeGRFParamType
static bool ChangeGRFParamType(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PARAM'->param_num->'TYPE' to set the typeof a parameter.
Definition: newgrf.cpp:8217
DSGA_OP_ADD
@ DSGA_OP_ADD
a + b
Definition: newgrf_spritegroup.h:121
GrfProcessingState::file
SpriteFile * file
File of currently processed GRF file.
Definition: newgrf.cpp:104
GRFLoadedFeatures::used_liveries
uint64_t used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:179
GMB_TRAIN_WIDTH_32_PIXELS
@ GMB_TRAIN_WIDTH_32_PIXELS
Use 32 pixels per train vehicle in depot gui and vehicle details. Never set in the global variable;.
Definition: newgrf.h:60
IndustrySpec::station_name
StringID station_name
Default name for nearby station.
Definition: industrytype.h:130
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
_display_opt
byte _display_opt
What do we want to draw/do?
Definition: transparency_gui.cpp:26
CIR_SUCCESS
@ CIR_SUCCESS
Variable was parsed and read.
Definition: newgrf.cpp:979
GRFConfig::min_loadable_version
uint32_t min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
Definition: newgrf_config.h:163
MAX_SPRITEGROUP
static const uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
Definition: newgrf.cpp:84
VehicleSettings::road_side
byte road_side
the side of the road vehicles drive on
Definition: settings_type.h:533
RoadTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: road.h:107
AllowedSubtags::text
TextHandler text
Callback function for a text node, only valid if type == 'T'.
Definition: newgrf.cpp:8361
RailTypeInfo::group
const SpriteGroup * group[RTSG_END]
Sprite groups for resolving sprites.
Definition: rail.h:281
VSG_SCOPE_PARENT
@ VSG_SCOPE_PARENT
Related object of the resolved one.
Definition: newgrf_spritegroup.h:101
Engine
Definition: engine_base.h:37
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:53
Action5Type::max_sprites
uint16_t max_sprites
If the Action5 contains more sprites, only the first max_sprites sprites will be used.
Definition: newgrf.cpp:6392
IndustryTileSpec::accepts_cargo
std::array< CargoID, INDUSTRY_NUM_INPUTS > accepts_cargo
Cargo accepted by this tile.
Definition: industrytype.h:155
GRFParameterInfo::type
GRFParameterType type
The type of this parameter.
Definition: newgrf_config.h:131
SoundEffectChangeInfo
static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
Define properties for sound effects.
Definition: newgrf.cpp:3130
RailTypeInfo::strings
struct RailTypeInfo::@26 strings
Strings associated with the rail type.
_tags_parameters
AllowedSubtags _tags_parameters[]
Action14 parameter tags.
Definition: newgrf.cpp:8411
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:128
SpriteFile::GetContainerVersion
byte GetContainerVersion() const
Get the version number of container type used by the file.
Definition: sprite_file_type.hpp:38
SoundEntry::grf_container_ver
byte grf_container_ver
NewGRF container version if the sound is from a NewGRF.
Definition: sound_type.h:22
IndustrySpec::cost_multiplier
uint8_t cost_multiplier
Base construction cost multiplier.
Definition: industrytype.h:107
fios.h
BridgeSpec::price
uint16_t price
the price multiplier
Definition: bridge.h:46
TranslateGRFStrings
static void TranslateGRFStrings(ByteReader *buf)
Action 0x13.
Definition: newgrf.cpp:8034
ConstructionSettings::max_bridge_length
uint16_t max_bridge_length
maximum length of bridges
Definition: settings_type.h:373
FinalisePriceBaseMultipliers
static void FinalisePriceBaseMultipliers()
Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them...
Definition: newgrf.cpp:9739
RandomAccessFile::ReadBlock
void ReadBlock(void *ptr, size_t size)
Read a block.
Definition: random_access_file.cpp:139
_engine_counts
const uint8_t _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:53
TLF_BB_Z_OFFSET
@ TLF_BB_Z_OFFSET
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:41
StrEmpty
bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:56
PaletteID
uint32_t PaletteID
The number of the palette.
Definition: gfx_type.h:18
GFX_WATERTILE_SPECIALCHECK
@ GFX_WATERTILE_SPECIALCHECK
not really a tile, but rather a very special check
Definition: industry_map.h:54
AirportSpec
Defines the data structure for an airport.
Definition: newgrf_airport.h:100
HasExactlyOneBit
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition: bitmath_func.hpp:259
GRFParameterInfo::min_value
uint32_t min_value
The minimal value this parameter can have.
Definition: newgrf_config.h:132
NUM_HOUSES_PER_GRF
static const HouseID NUM_HOUSES_PER_GRF
Number of supported houses per NewGRF; limited to 255 to allow extending Action3 with an extended byt...
Definition: house.h:25
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
genworld.h
TileLayoutRegisters
Additional modifiers for items in sprite layouts.
Definition: newgrf_commons.h:90
CargoSpec::initial_payment
int32_t initial_payment
Initial payment rate before inflation is applied.
Definition: cargotype.h:79
GRFP_BLT_UNSET
@ GRFP_BLT_UNSET
The NewGRF provided no information or doesn't care about a 32 bpp blitter.
Definition: newgrf_config.h:76
RandomAccessFile::ReadByte
byte ReadByte()
Read a byte from the file.
Definition: random_access_file.cpp:101
RailTypeInfo::curve_speed
byte curve_speed
Multiplier for curve maximum speed advantage.
Definition: rail.h:206
ObjectSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_object.h:63
CIR_UNHANDLED
@ CIR_UNHANDLED
Variable was parsed but unread.
Definition: newgrf.cpp:981
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
VSG_SCOPE_SELF
@ VSG_SCOPE_SELF
Resolved object itself.
Definition: newgrf_spritegroup.h:100
SPR_AQUEDUCT_BASE
static const SpriteID SPR_AQUEDUCT_BASE
Sprites for the Aqueduct.
Definition: sprites.h:186
RailVehicleInfo::cost_factor
byte cost_factor
Purchase cost factor; For multiheaded engines the sum of both engine prices.
Definition: engine_type.h:45
GrfProcessingState::nfo_line
uint32_t nfo_line
Currently processed pseudo sprite number in the GRF.
Definition: newgrf.cpp:107
RailTypeInfo::sorting_order
byte sorting_order
The sorting order of this railtype for the toolbar dropdown.
Definition: rail.h:271
ObjectSpec::callback_mask
uint16_t callback_mask
Bitmask of requested/allowed callbacks.
Definition: newgrf_object.h:74
industry_map.h
CargoSpec::array
static CargoSpec array[NUM_CARGO]
Array holding all CargoSpecs.
Definition: cargotype.h:196
DeterministicSpriteGroupAdjustOperation
DeterministicSpriteGroupAdjustOperation
Definition: newgrf_spritegroup.h:120
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:8312
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:619
GRFParameterInfo::num_bit
byte num_bit
Number of bits to use for this parameter.
Definition: newgrf_config.h:137
ReallocT
T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type.
Definition: alloc_func.hpp:111
RAILTYPE_ELECTRIC
@ RAILTYPE_ELECTRIC
Electric rails.
Definition: rail_type.h:30
RandomizedSpriteGroup::var_scope
VarSpriteGroupScope var_scope
Take this object:
Definition: newgrf_spritegroup.h:193
GCF_INVALID
@ GCF_INVALID
GRF is unusable with this version of OpenTTD.
Definition: newgrf_config.h:30
AllocateRoadType
RoadType AllocateRoadType(RoadTypeLabel label, RoadTramType rtt)
Allocate a new road type label.
Definition: road_cmd.cpp:134
AirportChangeInfo
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
Define properties for airports.
Definition: newgrf.cpp:3885
IndustryTileLayout
std::vector< IndustryTileLayoutTile > IndustryTileLayout
A complete tile layout for an industry is a list of tiles.
Definition: industrytype.h:100
GCF_INIT_ONLY
@ GCF_INIT_ONLY
GRF file is processed up to GLS_INIT.
Definition: newgrf_config.h:28
EC_ELECTRIC
@ EC_ELECTRIC
Electric rail engine.
Definition: engine_type.h:36
find_index
int find_index(Container const &container, typename Container::const_reference item)
Helper function to get the index of an item Consider using std::set, std::unordered_set or std::flat_...
Definition: container_func.hpp:41
FinaliseCargoArray
void FinaliseCargoArray()
Check for invalid cargoes.
Definition: newgrf.cpp:9204
StringIDMapping::target
StringID * target
Destination for mapping result.
Definition: newgrf.cpp:463
BridgeSpec
Struct containing information about a single bridge type.
Definition: bridge.h:42
IndustrySpec::closure_text
StringID closure_text
Message appearing when the industry closes.
Definition: industrytype.h:127
RailTypeInfo::compatible_railtypes
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition: rail.h:191
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:167
GrfProcessingState::SpriteSet::sprite
SpriteID sprite
SpriteID of the first sprite of the set.
Definition: newgrf.cpp:91
MemCpyT
void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:23
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:145
AirportTileSpec::ResetAirportTiles
static void ResetAirportTiles()
This function initializes the tile array of AirportTileSpec.
Definition: newgrf_airporttiles.cpp:58
TLF_KNOWN_FLAGS
@ TLF_KNOWN_FLAGS
Known flags. Any unknown set flag will disable the GRF.
Definition: newgrf_commons.h:49
ShipVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:76
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:59
HouseSpec::extra_flags
HouseExtraFlags extra_flags
some more flags
Definition: house.h:118
TileLayoutRegisters::sprite_var10
uint8_t sprite_var10
Value for variable 10 when resolving the sprite.
Definition: newgrf_commons.h:101
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition: newgrf_airporttiles.h:68
HouseSpec::probability
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:117
NETWORK_MAX_GRF_COUNT
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition: config.h:92
IndustryTileSpec::special_flags
IndustryTileSpecialFlags special_flags
Bitmask of extra flags used by the tile.
Definition: industrytype.h:168
StationSpec::cls_id
StationClassID cls_id
The class to which this spec belongs.
Definition: newgrf_station.h:125
RailTypeInfo::name
StringID name
Name of this rail type.
Definition: rail.h:176
EC_MAGLEV
@ EC_MAGLEV
Maglev engine.
Definition: engine_type.h:38
GRFTempEngineData::Refittability
Refittability
Summary state of refittability properties.
Definition: newgrf.cpp:321
GRFFileProps::override
uint16_t override
id of the entity been replaced by
Definition: newgrf_commons.h:332
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:626
RealSpriteGroup::loading
std::vector< const SpriteGroup * > loading
List of loading groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:90
Pool::PoolItem<&_engine_pool >::GetPoolSize
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:356
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
ObjectSpec::BindToClasses
static void BindToClasses()
Tie all ObjectSpecs to their class.
Definition: newgrf_object.cpp:111
InitGRFTownGeneratorNames
void InitGRFTownGeneratorNames()
Allocate memory for the NewGRF town names.
Definition: newgrf_townname.cpp:81
GRFP_GRF_DOS
@ GRFP_GRF_DOS
The NewGRF says the DOS palette can be used.
Definition: newgrf_config.h:71
ObjectSpec::size
uint8_t size
The size of this objects; low nibble for X, high nibble for Y.
Definition: newgrf_object.h:68
MAX_CATCHMENT
@ MAX_CATCHMENT
Maximum catchment for airports with "modified catchment" enabled.
Definition: station_type.h:84
TileLayoutRegisters::palette
uint8_t palette
Register specifying a signed offset for the palette.
Definition: newgrf_commons.h:94
MAX_NUM_CASES
static const uint8_t MAX_NUM_CASES
Maximum number of supported cases.
Definition: language.h:21
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, TextHandler handler)
Create a text leaf node.
Definition: newgrf.cpp:8324
GRFLoadedFeatures::has_2CC
bool has_2CC
Set if any vehicle is loaded which uses 2cc (two company colours).
Definition: newgrf.h:178
PROP_ROADVEH_SPEED
@ PROP_ROADVEH_SPEED
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
Definition: newgrf_properties.h:38
RailVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:58
GrfProcessingState::HasValidSpriteSets
bool HasValidSpriteSets(byte feature) const
Check whether there are any valid spritesets for a feature.
Definition: newgrf.cpp:152
DisableStaticNewGRFInfluencingNonStaticNewGRFs
static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
Disable a static NewGRF when it is influencing another (non-static) NewGRF as this could cause desync...
Definition: newgrf.cpp:6816
LoadNewGRF
void LoadNewGRF(uint load_index, uint num_baseset)
Load all the NewGRFs.
Definition: newgrf.cpp:9973
AirportSpec::rotation
const Direction * rotation
the rotation of each tiletable
Definition: newgrf_airport.h:103
LoadNewGRFFile
void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
Load a particular NewGRF.
Definition: newgrf.cpp:9651
SHORE_REPLACE_NONE
@ SHORE_REPLACE_NONE
No shore sprites were replaced.
Definition: newgrf.h:165
RailVehicleInfo::ai_passenger_only
byte ai_passenger_only
Bit value to tell AI that this engine is for passenger use only.
Definition: engine_type.h:55
GRFConfig::version
uint32_t version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
Definition: newgrf_config.h:162
AnimationInfo::status
uint8_t status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition: newgrf_animation_type.h:20
EconomySettings::station_noise_level
bool station_noise_level
build new airports when the town noise level is still within accepted limits
Definition: settings_type.h:557
RailVehicleInfo
Information about a rail vehicle.
Definition: engine_type.h:42
GRFLoadedFeatures::shore
ShoreReplacement shore
In which way shore sprites were replaced.
Definition: newgrf.h:180
RailTypeInfo::maintenance_multiplier
uint16_t maintenance_multiplier
Cost multiplier for maintenance of this rail type.
Definition: rail.h:221
error_func.h
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:122
NUM_AIRPORTTILES_PER_GRF
static const uint NUM_AIRPORTTILES_PER_GRF
Number of airport tiles per NewGRF; limited to 255 to allow extending Action3 with an extended byte l...
Definition: airport.h:21
RailVehicleInfo::engclass
EngineClass engclass
Class of engine for this vehicle.
Definition: engine_type.h:53
GRFParameterInfo::value_names
std::map< uint32_t, GRFTextList > value_names
Names for each value.
Definition: newgrf_config.h:138
BindAirportSpecs
void BindAirportSpecs()
Tie all airportspecs to their class.
Definition: newgrf_airport.cpp:123
EngineInfo::callback_mask
uint16_t callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:155
LoadNextSprite
bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
Definition: spritecache.cpp:609
VE_TYPE_START
@ VE_TYPE_START
First bit used for the type of effect.
Definition: vehicle_base.h:84
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
VehicleSettings::freight_trains
uint8_t freight_trains
value to multiply the weight of cargo by
Definition: settings_type.h:529
GRFFile::tramtype_list
std::vector< RoadTypeLabel > tramtype_list
Roadtype translation table (tram)
Definition: newgrf.h:138
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:611
BSWAP32
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:345
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:282
PROP_AIRCRAFT_CARGO_AGE_PERIOD
@ PROP_AIRCRAFT_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:54
NEW_INDUSTRYOFFSET
static const IndustryType NEW_INDUSTRYOFFSET
original number of industry types
Definition: industry_type.h:25
RailVehicleInfo::air_drag
byte air_drag
Coefficient of air drag.
Definition: engine_type.h:61
GCF_UNSAFE
@ GCF_UNSAFE
GRF file is unsafe for static usage.
Definition: newgrf_config.h:24
GCS_INITIALISED
@ GCS_INITIALISED
GRF file has been initialised.
Definition: newgrf_config.h:38
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:147
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
CargoSpec::weight
uint8_t weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:76
newgrf_engine.h
PROP_ROADVEH_CARGO_AGE_PERIOD
@ PROP_ROADVEH_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:40
GRFUnsafe
static void GRFUnsafe(ByteReader *)
Set the current NewGRF as unsafe for static use.
Definition: newgrf.cpp:8584
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:35
StringIDMapping::source
StringID source
Source StringID (GRF local).
Definition: newgrf.cpp:462
AirportSpec::num_table
byte num_table
number of elements in the table
Definition: newgrf_airport.h:104
SetPriceBaseMultiplier
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:903
IndustrySpec::conflicting
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:110
RoadStopSpec::spec_id
int spec_id
The ID of this spec inside the class.
Definition: newgrf_roadstop.h:131
MapNewGRFIndustryType
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32_t grf_id)
Map the GRF local type to an industry type.
Definition: newgrf_industries.cpp:40
CurrencySpec::suffix
std::string suffix
Suffix to apply when formatting money in this currency.
Definition: currency.h:79
TLF_BB_XY_OFFSET
@ TLF_BB_XY_OFFSET
Add signed offset to bounding box X and Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:40
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
StationSpec::layouts
std::vector< std::vector< std::vector< byte > > > layouts
Custom platform layouts.
Definition: newgrf_station.h:175
GetGRFSpriteOffset
size_t GetGRFSpriteOffset(uint32_t id)
Get the file offset for a specific sprite in the sprite section of a GRF.
Definition: spritecache.cpp:544
OverrideManagerBase::ResetMapping
void ResetMapping()
Resets the mapping, which is used while initializing game.
Definition: newgrf_commons.cpp:72
FinaliseIndustriesArray
static void FinaliseIndustriesArray()
Add all new industries to the industry array.
Definition: newgrf.cpp:9378
TLF_CHILD_Y_OFFSET
@ TLF_CHILD_Y_OFFSET
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:44
GRFP_GRF_ANY
@ GRFP_GRF_ANY
The NewGRF says any palette can be used.
Definition: newgrf_config.h:73
GCF_SYSTEM
@ GCF_SYSTEM
GRF file is an openttd-internal system grf.
Definition: newgrf_config.h:23
NEW_HOUSE_OFFSET
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
HandleParameterInfo
static bool HandleParameterInfo(ByteReader *buf)
Callback function for 'INFO'->'PARA' to set extra information about the parameters.
Definition: newgrf.cpp:8428
StationSpec::pylons
byte pylons
Bitmask of base tiles (0 - 7) which should contain elrail pylons.
Definition: newgrf_station.h:161
AirportTileTable::gfx
StationGfx gfx
AirportTile to use for this tile.
Definition: newgrf_airport.h:27
free
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:379
CallbackResultSpriteGroup
Definition: newgrf_spritegroup.h:210
CargoSpec::units_volume
StringID units_volume
Name of a single unit of cargo of this type.
Definition: cargotype.h:90
CargoSpec::IsValid
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:115
TAE_GOODS
@ TAE_GOODS
Cargo behaves goods/candy-like.
Definition: cargotype.h:29
RoadTypeInfo::maintenance_multiplier
uint16_t maintenance_multiplier
Cost multiplier for maintenance of this road type.
Definition: road.h:137
IndustryProductionSpriteGroup::version
uint8_t version
Production callback version used, or 0xFF if marked invalid.
Definition: newgrf_spritegroup.h:271
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:109
GetFileByFilename
static GRFFile * GetFileByFilename(const std::string &filename)
Obtain a NewGRF file by its filename.
Definition: newgrf.cpp:416
ConstructionSettings::map_height_limit
uint8_t map_height_limit
the maximum allowed heightlevel
Definition: settings_type.h:370
RoadVehicleInfo
Information about a road vehicle.
Definition: engine_type.h:114
CC_PIECE_GOODS
@ CC_PIECE_GOODS
Piece goods (Livestock, Wood, Steel, Paper)
Definition: cargotype.h:58
DrawTileSeqStruct::delta_z
int8_t delta_z
0x80 identifies child sprites
Definition: sprite.h:28
RoadStopSpec::build_cost_multiplier
uint8_t build_cost_multiplier
Build cost multiplier per tile.
Definition: newgrf_roadstop.h:146
BranchHandler
bool(* BranchHandler)(ByteReader *)
Type of callback function for branch nodes.
Definition: newgrf.cpp:8291
EngineIDMapping::grfid
uint32_t grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:193
ObjectSpec::end_of_life_date
TimerGameCalendar::Date end_of_life_date
When can't this object be built anymore.
Definition: newgrf_object.h:72
LanguageMap::Mapping::openttd_id
byte openttd_id
OpenTTD's internal ID for a case/gender.
Definition: newgrf_text.h:57
RoadVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:126
IndustryProductionSpriteGroup
Definition: newgrf_spritegroup.h:268
IndustrySpec::layouts
std::vector< IndustryTileLayout > layouts
List of possible tile layouts for the industry.
Definition: industrytype.h:106
TimerGameCalendar::ConvertYMDToDate
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: timer_game_calendar.cpp:55
SPRITE_MODIFIER_OPAQUE
@ SPRITE_MODIFIER_OPAQUE
Set when a sprite must not ever be displayed transparently.
Definition: sprites.h:1540
AnimationInfo::speed
uint8_t speed
The speed, i.e. the amount of time between frames.
Definition: newgrf_animation_type.h:21
IndustrySpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 accepted cargoes.
Definition: industrytype.h:119
INDUSTRYTILE_NOANIM
static const IndustryGfx INDUSTRYTILE_NOANIM
flag to mark industry tiles as having no animation
Definition: industry_type.h:31
INVALID_INDUSTRYTILE
static const IndustryGfx INVALID_INDUSTRYTILE
one above amount is considered invalid
Definition: industry_type.h:34
EF_USES_2CC
@ EF_USES_2CC
Vehicle uses two company colours.
Definition: engine_type.h:169
SHORE_REPLACE_ONLY_NEW
@ SHORE_REPLACE_ONLY_NEW
Only corner-shores were loaded by Action5 (openttd(w/d).grf only).
Definition: newgrf.h:168
BridgeSpec::transport_name
StringID transport_name[2]
description of the bridge, when built for road or rail
Definition: bridge.h:51
CC_BULK
@ CC_BULK
Bulk cargo (Coal, Grain etc., Ores, Fruit)
Definition: cargotype.h:57
_cargo_mask
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition: cargotype.cpp:31
SP_CUSTOM
@ SP_CUSTOM
No profile, special "custom" highscore.
Definition: settings_type.h:46
NUM_AIRPORTS_PER_GRF
@ NUM_AIRPORTS_PER_GRF
Maximal number of airports per NewGRF.
Definition: airport.h:40
IndustrySpec::production_up_text
StringID production_up_text
Message appearing when the industry's production is increasing.
Definition: industrytype.h:128
CleanUpStrings
void CleanUpStrings()
House cleaning.
Definition: newgrf_text.cpp:682
RailTypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: rail.h:177
EnsureEarlyHouse
static void EnsureEarlyHouse(HouseZones bitmask)
Make sure there is at least one house available in the year 0 for the given climate / housezone combi...
Definition: newgrf.cpp:9280
GrfProcessingState::SpriteSet
Definition of a single Action1 spriteset.
Definition: newgrf.cpp:90
LoadNewGRFFileFromFile
static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
Load a particular NewGRF from a SpriteFile.
Definition: newgrf.cpp:9562
CargoSpec::grffile
const struct GRFFile * grffile
NewGRF where #group belongs to.
Definition: cargotype.h:96
StaticGRFInfo
static void StaticGRFInfo(ByteReader *buf)
Handle Action 0x14.
Definition: newgrf.cpp:8574
EC_DIESEL
@ EC_DIESEL
Diesel rail engine.
Definition: engine_type.h:35
HZ_ZONALL
@ HZ_ZONALL
1F This is just to englobe all above types at once
Definition: house.h:78
SpriteGroupCargo::SG_DEFAULT
static constexpr CargoID SG_DEFAULT
Default type used when no more-specific cargo matches.
Definition: newgrf_cargo.h:23
NewGRFClass
Struct containing information relating to NewGRF classes for stations and airports.
Definition: newgrf_class.h:20
StationSettings::never_expire_airports
bool never_expire_airports
never expire airports
Definition: settings_type.h:594
AfterLoadGRFs
static void AfterLoadGRFs()
Finish loading NewGRFs and execute needed post-processing.
Definition: newgrf.cpp:9854
_cur_parameter
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:8200
IndustrySpec::minimal_cargo
byte minimal_cargo
minimum amount of cargo transported to the stations.
Definition: industrytype.h:118
TileLayoutRegisters::max_palette_offset
uint16_t max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset)
Definition: newgrf_commons.h:96
RoadTypeInfo::group
const SpriteGroup * group[ROTSG_END]
Sprite groups for resolving sprites.
Definition: road.h:192
LanguageMap::gender_map
std::vector< Mapping > gender_map
Mapping of NewGRF and OpenTTD IDs for genders.
Definition: newgrf_text.h:66
SHORE_REPLACE_ACTION_5
@ SHORE_REPLACE_ACTION_5
Shore sprites were replaced by Action5.
Definition: newgrf.h:166
StringIDMapping
Information for mapping static StringIDs.
Definition: newgrf.cpp:460
MAX_NUM_GENDERS
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
Definition: language.h:20
RoadVehicleInfo::air_drag
uint8_t air_drag
Coefficient of air drag.
Definition: engine_type.h:125
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:55
StationSpec::cargo_threshold
uint16_t cargo_threshold
Cargo threshold for choosing between little and lots of cargo.
Definition: newgrf_station.h:153
HouseSpec::animation
AnimationInfo animation
information about the animation.
Definition: house.h:120
NUM_INDUSTRYTILES_PER_GRF
static const IndustryGfx NUM_INDUSTRYTILES_PER_GRF
Maximum number of industry tiles per NewGRF; limited to 255 to allow extending Action3 with an extend...
Definition: industry_type.h:29
ValidateIndustryLayout
static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
Validate the industry layout; e.g.
Definition: newgrf.cpp:3448
RailTypeInfo::label
RailTypeLabel label
Unique 32 bit rail type identifier.
Definition: rail.h:236
timer_game_tick.h
TimerGameConst< struct Calendar >::ORIGINAL_MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: timer_game_common.h:167
RoadTypeInfo::alternate_labels
RoadTypeLabelList alternate_labels
Road type labels this type provides in addition to the main label.
Definition: road.h:152
ChangeGRFURL
static bool ChangeGRFURL(byte langid, const char *str)
Callback function for 'INFO'->'URL_' to set the newgrf url.
Definition: newgrf.cpp:8101
_water_feature
WaterFeature _water_feature[CF_END]
Table of canal 'feature' sprite groups.
Definition: newgrf_canal.cpp:21
PriceBaseSpec::fallback_price
Price fallback_price
Fallback price multiplier for new prices but old grfs.
Definition: economy_type.h:211
GRFParameterInfo
Information about one grf parameter.
Definition: newgrf_config.h:127
CargoSpec::sprite
SpriteID sprite
Icon to display this cargo type, may be 0xFFF (which means to resolve an action123 chain).
Definition: cargotype.h:94
GRFConfig::error
std::optional< GRFError > error
NOSAVE: Error/Warning during GRF loading (Action 0x0B)
Definition: newgrf_config.h:160
ANIM_STATUS_NO_ANIMATION
static const uint8_t ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:628
DrawTileSeqStruct::IsTerminator
bool IsTerminator() const
Check whether this is a sequence terminator.
Definition: sprite.h:41
AirportSpec::ttd_airport_type
TTDPAirportType ttd_airport_type
ttdpatch airport type (Small/Large/Helipad/Oilrig)
Definition: newgrf_airport.h:114
PROP_SHIP_CARGO_AGE_PERIOD
@ PROP_SHIP_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:47
CurrencySpec::code
std::string code
3 letter untranslated code to identify the currency.
Definition: currency.h:80
_action5_types
static const Action5Type _action5_types[]
The information about action 5 types.
Definition: newgrf.cpp:6397
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition: newgrf_commons.h:112
MAX_LANG
static const uint MAX_LANG
Maximum number of languages supported by the game, and the NewGRF specs.
Definition: strings_type.h:19
TimerGameCalendar::ConvertDateToYMD
static YearMonthDay ConvertDateToYMD(Date date)
Converts a Date to a Year, Month & Day.
Definition: timer_game_calendar.cpp:42
safeguards.h
RoadVehicleInfo::power
uint8_t power
Power in 10hp units.
Definition: engine_type.h:123
EngineIDMapping::substitute_id
uint8_t substitute_id
The (original) entity ID to use if this GRF is not available (currently not used)
Definition: engine_base.h:196
ChangeGRFParamMask
static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PARAM'->param_num->'MASK' to set the parameter and bits to use.
Definition: newgrf.cpp:8256
StationSpec::name
StringID name
Name of this station.
Definition: newgrf_station.h:126
ObjectOverrideManager::SetEntitySpec
void SetEntitySpec(ObjectSpec *spec)
Method to install the new object data in its proper slot The slot assignment is internal of this meth...
Definition: newgrf_commons.cpp:298
GameCreationSettings::starting_year
TimerGameCalendar::Year starting_year
starting date
Definition: settings_type.h:341
AddGRFString
StringID AddGRFString(uint32_t grfid, uint16_t stringid, byte langid_to_add, bool new_scheme, bool allow_newlines, const char *text_to_add, StringID def_string)
Add the new read string into our structure.
Definition: newgrf_text.cpp:543
GRFP_BLT_32BPP
@ GRFP_BLT_32BPP
The NewGRF prefers a 32 bpp blitter.
Definition: newgrf_config.h:77
IndustryTileSpec::slopes_refused
Slope slopes_refused
slope pattern on which this tile cannot be built
Definition: industrytype.h:157
ChangeGRFParamValueNames
static bool ChangeGRFParamValueNames(ByteReader *buf)
Callback function for 'INFO'->'PARA'->param_num->'VALU' to set the names of some parameter values (ty...
Definition: newgrf.cpp:8381
ImportGRFSound
static void ImportGRFSound(SoundEntry *sound)
Process a sound import from another GRF file.
Definition: newgrf.cpp:7826
GRFConfig::has_param_defaults
bool has_param_defaults
NOSAVE: did this newgrf specify any defaults for it's parameters.
Definition: newgrf_config.h:172
GRFFile::param_end
uint param_end
one more than the highest set parameter
Definition: newgrf.h:125
TLR_MAX_VAR10
static const uint TLR_MAX_VAR10
Maximum value for var 10.
Definition: newgrf_commons.h:105
GrfProcessingState
Temporary data during loading of GRFs.
Definition: newgrf.cpp:87
IndustryProductionSpriteGroup::subtract_input
int16_t subtract_input[INDUSTRY_NUM_INPUTS]
Take this much of the input cargo (can be negative, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:273
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1539
IndustryTileSpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:169
_tags_root
AllowedSubtags _tags_root[]
Action14 root tags.
Definition: newgrf.cpp:8469
FinaliseObjectsArray
static void FinaliseObjectsArray()
Add all new objects to the object array.
Definition: newgrf.cpp:9437
GRFTempEngineData::EMPTY
@ EMPTY
GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
Definition: newgrf.cpp:323
GRFTownName::partlists
std::vector< NamePartList > partlists[MAX_LISTS]
Lists of town name parts.
Definition: newgrf_townname.h:43
NamePart::text
std::string text
If probability bit 7 is clear.
Definition: newgrf_townname.h:19
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:58
HouseSpec::minimum_life
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:122
RoadStopSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_roadstop.h:129
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:59
AirportSpec::maintenance_cost
uint16_t maintenance_cost
maintenance cost multiplier
Definition: newgrf_airport.h:117
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:27
CurrencySpec::rate
uint16_t rate
The conversion rate compared to the base currency.
Definition: currency.h:75
TTDPAirportType
TTDPAirportType
Allow incrementing of AirportClassID variables.
Definition: newgrf_airport.h:83
CanalChangeInfo
static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for water features.
Definition: newgrf.cpp:2154
LoadTranslationTable
static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
Load a cargo- or railtype-translation table.
Definition: newgrf.cpp:2639
WaterFeature::callback_mask
uint8_t callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf_canal.h:25
CargoSpec::callback_mask
uint8_t callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:86
GlobalVarChangeInfo
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
Define properties for global variables.
Definition: newgrf.cpp:2676
newgrf_text.h
road.h
RoadVehicleInfo::tractive_effort
uint8_t tractive_effort
Coefficient of tractive effort.
Definition: engine_type.h:124
ObjectSpec::introduction_date
TimerGameCalendar::Date introduction_date
From when can this object be built.
Definition: newgrf_object.h:71
IndustrySpec::prospecting_chance
uint32_t prospecting_chance
Chance prospecting succeeds.
Definition: industrytype.h:109
NamePartList::bitcount
byte bitcount
Number of bits of random seed to use.
Definition: newgrf_townname.h:26
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:103
error.h
GrfProcessingState::GetSprite
SpriteID GetSprite(byte feature, uint set) const
Returns the first sprite of a spriteset.
Definition: newgrf.cpp:177
RailVehicleChangeInfo
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for rail vehicles.
Definition: newgrf.cpp:1038
OverrideManagerBase::AddEntityID
virtual uint16_t AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
Reserves a place in the mapping array for an entity to be installed.
Definition: newgrf_commons.cpp:109
CargoSpec::is_freight
bool is_freight
Cargo type is considered to be freight (affects train freight multiplier).
Definition: cargotype.h:82
RailTypeInfo::cost_multiplier
uint16_t cost_multiplier
Cost multiplier for building this rail type.
Definition: rail.h:216
HZ_ZON5
@ HZ_ZON5
center of town
Definition: house.h:77
TimerGameConst< struct Calendar >::MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year MAX_YEAR
MAX_YEAR, nicely rounded value of the number of years that can be encoded in a single 32 bits date,...
Definition: timer_game_common.h:173
GRFTempEngineData::ctt_exclude_mask
CargoTypes ctt_exclude_mask
Cargo types always excluded from the refit mask.
Definition: newgrf.cpp:335
GRFTempEngineData::defaultcargo_grf
const GRFFile * defaultcargo_grf
GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
Definition: newgrf.cpp:331
ResetCurrencies
void ResetCurrencies(bool preserve_custom)
Will fill _currency_specs array with default values from origin_currency_specs Called only from newgr...
Definition: currency.cpp:159
EngineIDMapping
Definition: engine_base.h:192
AirportTileTable
Tile-offset / AirportTileID pair.
Definition: newgrf_airport.h:25
IndustrySpec::appear_creation
byte appear_creation[NUM_LANDSCAPE]
Probability of appearance during map creation.
Definition: industrytype.h:132
GRFP_GRF_MASK
@ GRFP_GRF_MASK
Bitmask to get only the NewGRF supplied information.
Definition: newgrf_config.h:74
_loaded_newgrf_features
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:82
Pool::CleanPool
void CleanPool() override
Virtual method that deletes all items in the pool.
language.h
RoadTypeInfo::cost_multiplier
uint16_t cost_multiplier
Cost multiplier for building this road type.
Definition: road.h:132
IndustryTileSpec::anim_production
byte anim_production
Animation frame to start when goods are produced.
Definition: industrytype.h:158
newgrf_roadstop.h
RandomAccessFile::filename
std::string filename
Full name of the file; relative path to subdir plus the extension of the file.
Definition: random_access_file_type.h:26
CargoSpec::bitnum
uint8_t bitnum
Cargo bit number, is INVALID_CARGO_BITNUM for a non-used spec.
Definition: cargotype.h:73
RailVehicleInfo::tractive_effort
byte tractive_effort
Tractive effort coefficient.
Definition: engine_type.h:60
GRFFile::traininfo_vehicle_width
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Definition: newgrf.h:146
GetGRFStringID
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:587
CargoChangeInfo
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
Define properties for cargoes.
Definition: newgrf.cpp:2973
SoundEntry
Definition: sound_type.h:13
StationSpec::disallowed_platforms
byte disallowed_platforms
Bitmask of number of platforms available for the station.
Definition: newgrf_station.h:132
stdafx.h
GrfProcessingState::grfconfig
GRFConfig * grfconfig
Config of the currently processed GRF file.
Definition: newgrf.cpp:106
TLF_NON_GROUND_FLAGS
@ TLF_NON_GROUND_FLAGS
Flags which do not work for the (first) ground sprite.
Definition: newgrf_commons.h:55
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
RailTypeInfo::grffile
const GRFFile * grffile[RTSG_END]
NewGRF providing the Action3 for the railtype.
Definition: rail.h:276
landscape.h
OTTDByteReaderSignal
Definition: newgrf.cpp:211
PROP_AIRCRAFT_COST_FACTOR
@ PROP_AIRCRAFT_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:49
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:105
CargoLabel
uint32_t CargoLabel
Globally unique label of a cargo type.
Definition: cargotype.h:21
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
PROP_TRAIN_CURVE_SPEED_MOD
@ PROP_TRAIN_CURVE_SPEED_MOD
Modifier to maximum speed in curves.
Definition: newgrf_properties.h:31
IndustryTileSpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:170
SPR_RAILTYPE_TUNNEL_BASE
static const SpriteID SPR_RAILTYPE_TUNNEL_BASE
Tunnel sprites with grass only for custom railtype tunnel.
Definition: sprites.h:299
EngineClass
EngineClass
Type of rail engine.
Definition: engine_type.h:33
PALETTE_MODIFIER_TRANSPARENT
@ PALETTE_MODIFIER_TRANSPARENT
when a sprite is to be displayed transparently, this bit needs to be set.
Definition: sprites.h:1541
NEWGRF_DIR
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
Definition: fileio_type.h:117
IgnoreIndustryProperty
static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
Ignore an industry property.
Definition: newgrf.cpp:3358
GRFTempEngineData::refittability
Refittability refittability
Did the newgrf set any refittability property? If not, default refittability will be applied.
Definition: newgrf.cpp:332
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:154
HouseSpec::mail_generation
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:106
A5BLOCK_FIXED
@ A5BLOCK_FIXED
Only allow replacing a whole block of sprites. (TTDP compatible)
Definition: newgrf.cpp:6383
GRFTownName
Definition: newgrf_townname.h:38
A5BLOCK_ALLOW_OFFSET
@ A5BLOCK_ALLOW_OFFSET
Allow replacing any subset by specifiing an offset.
Definition: newgrf.cpp:6384
GRFConfig::palette
uint8_t palette
GRFPalette, bitset.
Definition: newgrf_config.h:170
HouseSpec::population
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:102
PROP_SHIP_RUNNING_COST_FACTOR
@ PROP_SHIP_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:46
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, byte type, uint16_t num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:113
IndustryProductionSpriteGroup::num_input
uint8_t num_input
How many subtract_input values are valid.
Definition: newgrf_spritegroup.h:272
GRFConfig::param_info
std::vector< std::optional< GRFParameterInfo > > param_info
NOSAVE: extra information about the parameters.
Definition: newgrf_config.h:171
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition: engine_type.h:29
RealSpriteGroup::loaded
std::vector< const SpriteGroup * > loaded
List of loaded groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:89
LanguageMap::Mapping
Mapping between NewGRF and OpenTTD IDs.
Definition: newgrf_text.h:55
VehicleSettings::plane_speed
uint8_t plane_speed
divisor for speed of aircraft
Definition: settings_type.h:528
NamePartList::bitstart
byte bitstart
Start of random seed bits to use.
Definition: newgrf_townname.h:25
BuildCargoTranslationMap
static void BuildCargoTranslationMap()
Construct the Cargo Mapping.
Definition: newgrf.cpp:8878
IndustrySpec::number_of_sounds
uint8_t number_of_sounds
Number of sounds available in the sounds array.
Definition: industrytype.h:133
HouseSpec::cargo_acceptance
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:107
WaterFeature::grffile
const GRFFile * grffile
NewGRF where 'group' belongs to.
Definition: newgrf_canal.h:24
HandleNode
static bool HandleNode(byte type, uint32_t id, ByteReader *buf, AllowedSubtags subtags[])
Handle the nodes of an Action14.
Definition: newgrf.cpp:8521
GRFFilePropsBase::local_id
uint16_t local_id
id defined by the grf file for this entity
Definition: newgrf_commons.h:318
ShipVehicleInfo::old_refittable
bool old_refittable
Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
Definition: engine_type.h:75
AllowedSubtags::type
byte type
The type of the node, must be one of 'C', 'B' or 'T'.
Definition: newgrf.cpp:8358
GRFParameterInfo::first_bit
byte first_bit
First bit to use in the GRF parameter.
Definition: newgrf_config.h:136
BuildIndustriesLegend
void BuildIndustriesLegend()
Fills an array for the industries legends.
Definition: smallmap_gui.cpp:186
SetSnowLine
void SetSnowLine(byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
Set a variable snow line, as loaded from a newgrf file.
Definition: landscape.cpp:592
newgrf_object.h
RailTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:231
ReadSpriteLayoutSprite
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)
Read a sprite and a palette from the GRF and convert them into a format suitable to OpenTTD.
Definition: newgrf.cpp:737
BridgeSpec::min_length
byte min_length
the minimum length (not counting start and end tile)
Definition: bridge.h:44
IndustrySpec::callback_mask
uint16_t callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:136
ObjectSpec::name
StringID name
The name for this object.
Definition: newgrf_object.h:65
ChangeGRFBlitter
static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
Callback function for 'INFO'->'BLTR' to set the blitter info.
Definition: newgrf.cpp:8146
RailTypeInfo::powered_railtypes
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
Definition: rail.h:188
GRFTempEngineData::rv_max_speed
uint8_t rv_max_speed
Temporary storage of RV prop 15, maximum speed in mph/0.8.
Definition: newgrf.cpp:333
RandomAccessFile::GetPos
size_t GetPos() const
Get position in the file.
Definition: random_access_file.cpp:74
AirportSpec::size_x
byte size_x
size of airport in x direction
Definition: newgrf_airport.h:107
FinaliseEngineArray
static void FinaliseEngineArray()
Check for invalid engines.
Definition: newgrf.cpp:9137
GRFParameterType
GRFParameterType
The possible types of a newgrf parameter.
Definition: newgrf_config.h:120
ChangeGRFNumUsedParams
static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
Callback function for 'INFO'->'NPAR' to set the number of valid parameters.
Definition: newgrf.cpp:8108
GRFTempEngineData::UNSET
@ UNSET
No properties assigned. Default refit masks shall be activated.
Definition: newgrf.cpp:322
TranslateRefitMask
static CargoTypes TranslateRefitMask(uint32_t refit_mask)
Translate the refit mask.
Definition: newgrf.cpp:941
ChangeGRFMinVersion
static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
Callback function for 'INFO'->'MINV' to the minimum compatible version of the NewGRF.
Definition: newgrf.cpp:8181
GetGlobalVariable
bool GetGlobalVariable(byte param, uint32_t *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
Definition: newgrf.cpp:6538
RAILTYPE_RAIL
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition: rail_type.h:29
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:62
GCS_UNKNOWN
@ GCS_UNKNOWN
The status of this grf file is unknown.
Definition: newgrf_config.h:35
RailTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: rail.h:178
SpriteFile
RandomAccessFile with some extra information specific for sprite files.
Definition: sprite_file_type.hpp:19
DeterministicSpriteGroupAdjust
Definition: newgrf_spritegroup.h:147
PriceBaseSpec
Describes properties of price bases.
Definition: economy_type.h:207
GRFError::param_value
std::array< uint32_t, 2 > param_value
Values of GRF parameters to show for message and custom_message.
Definition: newgrf_config.h:116
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:138
GRFFile::canal_local_properties
CanalProperties canal_local_properties[CF_END]
Canal properties as set by this NewGRF.
Definition: newgrf.h:141
GRFError
Information about why GRF had problems during initialisation.
Definition: newgrf_config.h:109
RoadTypeInfo::grffile
const GRFFile * grffile[ROTSG_END]
NewGRF providing the Action3 for the roadtype.
Definition: road.h:187
NUM_ROADSTOPS_PER_GRF
static const int NUM_ROADSTOPS_PER_GRF
The maximum amount of roadstops a single GRF is allowed to add.
Definition: newgrf_roadstop.h:23
ChangeGRFDescription
static bool ChangeGRFDescription(byte langid, const char *str)
Callback function for 'INFO'->'DESC' to add a translation to the newgrf description.
Definition: newgrf.cpp:8094
GCS_DISABLED
@ GCS_DISABLED
GRF file is disabled.
Definition: newgrf_config.h:36
CIR_DISABLED
@ CIR_DISABLED
GRF was disabled due to error.
Definition: newgrf.cpp:980
RandomAccessFile::ReadWord
uint16_t ReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: random_access_file.cpp:118
GRFError::message
StringID message
Default message.
Definition: newgrf_config.h:114
AllocateRailType
RailType AllocateRailType(RailTypeLabel label)
Allocate a new rail type label.
Definition: rail_cmd.cpp:150
GRFParameterInfo::max_value
uint32_t max_value
The maximal value of this parameter.
Definition: newgrf_config.h:133
vehicle_func.h
rev.h
CURRENCY_END
@ CURRENCY_END
always the last item
Definition: currency.h:70
PROP_TRAIN_WEIGHT
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:25
PROP_VEHICLE_LOAD_AMOUNT
@ PROP_VEHICLE_LOAD_AMOUNT
Loading speed.
Definition: newgrf_properties.h:19
GRFFile::GRFFile
GRFFile(const struct GRFConfig *config)
Constructor for GRFFile.
Definition: newgrf.cpp:8917
INVALID_TPE
@ INVALID_TPE
Invalid town production effect.
Definition: cargotype.h:47
CargoSpec::town_production_effect
TownProductionEffect town_production_effect
The effect on town cargo production.
Definition: cargotype.h:84
VehicleSettings::dynamic_engines
bool dynamic_engines
enable dynamic allocation of engine data
Definition: settings_type.h:530
newgrf_sound.h
RoadVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:127
Pool::PoolItem<&_engine_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:384
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:320
GRFConfig::flags
uint8_t flags
NOSAVE: GCF_Flags, bitset.
Definition: newgrf_config.h:164
GRFP_GRF_WINDOWS
@ GRFP_GRF_WINDOWS
The NewGRF says the Windows palette can be used.
Definition: newgrf_config.h:72
strings_func.h
TLF_VAR10_FLAGS
@ TLF_VAR10_FLAGS
Flags which refer to using multiple action-1-2-3 chains.
Definition: newgrf_commons.h:58
TimerGameEconomy::year
static Year year
Current year, starting at 0.
Definition: timer_game_economy.h:35
StationSpec
Station specification.
Definition: newgrf_station.h:112
CLEAN_RANDOMSOUNDS
@ CLEAN_RANDOMSOUNDS
Free the dynamically allocated sounds table.
Definition: industrytype.h:22
AirportSpec::enabled
bool enabled
Entity still available (by default true). Newgrf can disable it, though.
Definition: newgrf_airport.h:119
SetNewGRFOverride
static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
Set the override for a NewGRF.
Definition: newgrf.cpp:584
LanguageMap
Mapping of language data between a NewGRF and OpenTTD.
Definition: newgrf_text.h:53
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:28
IndustrySpec::removal_cost_multiplier
uint32_t removal_cost_multiplier
Base removal cost multiplier.
Definition: industrytype.h:108
IndustrytilesChangeInfo
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
Define properties for industry tiles.
Definition: newgrf.cpp:3225
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:126
bridge.h
RailTypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: rail.h:246
EngineIDMapping::internal_id
uint16_t internal_id
The internal ID within the GRF file.
Definition: engine_base.h:194
NEW_AIRPORT_OFFSET
@ NEW_AIRPORT_OFFSET
Number of the first newgrf airport.
Definition: airport.h:39
RandomAccessFile::SkipBytes
void SkipBytes(size_t n)
Skip n bytes ahead in the file.
Definition: random_access_file.cpp:149
EngineInfo::base_life
TimerGameCalendar::Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life.
Definition: engine_type.h:147
GameCreationSettings::generation_seed
uint32_t generation_seed
noise seed for world generation
Definition: settings_type.h:340
GRFTempEngineData
Temporary engine data used when loading only.
Definition: newgrf.cpp:319
CC_ARMOURED
@ CC_ARMOURED
Armoured cargo (Valuables, Gold, Diamonds)
Definition: cargotype.h:56
ResetNewGRFErrors
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8755
IsHouseSpecValid
static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const std::string &filename)
Check if a given housespec is valid and disable it if it's not.
Definition: newgrf.cpp:9234
GRFConfig::name
GRFTextWrapper name
NOSAVE: GRF name (Action 0x08)
Definition: newgrf_config.h:157
ResetNewGRF
static void ResetNewGRF()
Reset and clear all NewGRFs.
Definition: newgrf.cpp:8744
GRFLoadedFeatures::tram
TramReplacement tram
In which way tram depots were replaced.
Definition: newgrf.h:181
GRFConfig::param
std::array< uint32_t, 0x80 > param
GRF parameters.
Definition: newgrf_config.h:167
GRFParameterInfo::desc
GRFTextList desc
The description of this parameter.
Definition: newgrf_config.h:130
AllowedSubtags
Data structure to store the allowed id/type combinations for action 14.
Definition: newgrf.cpp:8300
FinaliseAirportsArray
static void FinaliseAirportsArray()
Add all new airports to the airport array.
Definition: newgrf.cpp:9455
TileLayoutRegisters::parent
uint8_t parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
Definition: newgrf_commons.h:98
RailTypeInfo::fallback_railtype
byte fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition: rail.h:201
SHORE_REPLACE_ACTION_A
@ SHORE_REPLACE_ACTION_A
Shore sprites were replaced by ActionA (using grass tiles for the corner-shores).
Definition: newgrf.h:167
GCF_RESERVED
@ GCF_RESERVED
GRF file passed GLS_RESERVE stage.
Definition: newgrf_config.h:29
NamePartList
Definition: newgrf_townname.h:24
TRAMWAY_REPLACE_DEPOT_WITH_TRACK
@ TRAMWAY_REPLACE_DEPOT_WITH_TRACK
Electrified depot graphics with tram track were loaded.
Definition: newgrf.h:173
abs
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:23
IndustryTileSpec::animation
AnimationInfo animation
Information about the animation (is it looping, how many loops etc)
Definition: industrytype.h:167
MapSpriteMappingRecolour
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
Map the colour modifiers of TTDPatch to those that Open is using.
Definition: newgrf.cpp:706
ObjectSpec::climate
uint8_t climate
In which climates is this object available?
Definition: newgrf_object.h:67
TranslateTTDPatchCodes
std::string TranslateTTDPatchCodes(uint32_t grfid, uint8_t language_id, bool allow_newlines, const std::string &str, StringControlCode byte80)
Translate TTDPatch string codes into something OpenTTD can handle (better).
Definition: newgrf_text.cpp:236
RAILTYPE_END
@ RAILTYPE_END
Used for iterations.
Definition: rail_type.h:33
CC_REFRIGERATED
@ CC_REFRIGERATED
Refrigerated cargo (Food, Fruit)
Definition: cargotype.h:60
CommonVehicleChangeInfo
static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
Define properties common to all vehicles.
Definition: newgrf.cpp:995
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:371
RealSpriteGroup
Definition: newgrf_spritegroup.h:79
AllowedSubtags::subtags
AllowedSubtags * subtags
Pointer to a list of subtags, only valid if type == 'C' && !call_handler.
Definition: newgrf.cpp:8365
HZ_SUBARTC_ABOVE
@ HZ_SUBARTC_ABOVE
11 800 can appear in sub-arctic climate above the snow line
Definition: house.h:79
TextHandler
bool(* TextHandler)(byte, const char *str)
Type of callback function for text nodes.
Definition: newgrf.cpp:8290
Action5Type::block_type
Action5BlockType block_type
How is this Action5 type processed?
Definition: newgrf.cpp:6389
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition: newgrf_airport.h:120
CargoSpec::quantifier
StringID quantifier
Text for multiple units of cargo of this type.
Definition: cargotype.h:91
IndustrySpec::random_sounds
const uint8_t * random_sounds
array of random sounds.
Definition: industrytype.h:134
SPR_AIRPORT_PREVIEW_BASE
static const SpriteID SPR_AIRPORT_PREVIEW_BASE
Airport preview sprites.
Definition: sprites.h:248
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:174
industrytype.h
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition: engine_type.h:28
TimerGame< struct Calendar >::IsLeapYear
static constexpr bool IsLeapYear(Year year)
Checks whether the given year is a leap year or not.
Definition: timer_game_common.h:63
GetEngineLiveryScheme
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
Definition: vehicle.cpp:1941
ShipVehicleInfo::acceleration
uint8_t acceleration
Acceleration (1 unit = 1/3.2 mph per tick = 0.5 km-ish/h per tick)
Definition: engine_type.h:70
LanguagePackHeader::GetGenderIndex
uint8_t GetGenderIndex(const char *gender_str) const
Get the index for the given gender.
Definition: language.h:68
GetDefaultCargoID
CargoID GetDefaultCargoID(LandscapeID l, CargoType ct)
Get the cargo ID of a default cargo, if present.
Definition: cargotype.cpp:94
InitializeSortedCargoSpecs
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
Definition: cargotype.cpp:194
EngineInfo::variant_id
EngineID variant_id
Engine variant ID. If set, will be treated specially in purchase lists.
Definition: engine_type.h:159
EngineOverrideManager::GetID
EngineID GetID(VehicleType type, uint16_t grf_local_id, uint32_t grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:530
GrfProcessingState::AddSpriteSets
void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
Records new spritesets.
Definition: newgrf.cpp:136
SPR_OPENTTD_BASE
static const SpriteID SPR_OPENTTD_BASE
Extra graphic spritenumbers.
Definition: sprites.h:56
SpriteGroupCargo::SG_PURCHASE
static constexpr CargoID SG_PURCHASE
Used in purchase lists before an item exists.
Definition: newgrf_cargo.h:24
IndustrySpec::production_down_text
StringID production_down_text
Message appearing when the industry's production is decreasing.
Definition: industrytype.h:129
TAE_WATER
@ TAE_WATER
Cargo behaves water-like.
Definition: cargotype.h:30
TRAMWAY_REPLACE_DEPOT_NONE
@ TRAMWAY_REPLACE_DEPOT_NONE
No tram depot graphics were loaded.
Definition: newgrf.h:172
RailVehicleInfo::user_def_data
byte user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition: engine_type.h:62
AlterVehicleListOrder
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
Definition: newgrf_engine.cpp:1299
GetNewEngineID
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
Return the ID of a new engine.
Definition: newgrf.cpp:690
RoadVehicleChangeInfo
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for road vehicles.
Definition: newgrf.cpp:1346
LanguageMap::GetLanguageMap
static const LanguageMap * GetLanguageMap(uint32_t grfid, uint8_t language_id)
Get the language map associated with a given NewGRF and language.
Definition: newgrf.cpp:2622
AirportTileSpec::enabled
bool enabled
entity still available (by default true). newgrf can disable it, though
Definition: newgrf_airporttiles.h:73
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:327
IndustrySpec::appear_ingame
byte appear_ingame[NUM_LANDSCAPE]
Probability of appearance in game.
Definition: industrytype.h:131
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:139
_ttdpatch_flags
static uint32_t _ttdpatch_flags[8]
32 * 8 = 256 flags.
Definition: newgrf.cpp:79
TRAMWAY_REPLACE_DEPOT_NO_TRACK
@ TRAMWAY_REPLACE_DEPOT_NO_TRACK
Electrified depot graphics without tram track were loaded.
Definition: newgrf.h:174
RoadTypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: road.h:157
NewGRFSpriteLayout::consistent_max_offset
uint consistent_max_offset
Number of sprites in all referenced spritesets.
Definition: newgrf_commons.h:119
HouseSpec::watched_cargoes
CargoTypes watched_cargoes
Cargo types watched for acceptance.
Definition: house.h:123
IsSnowLineSet
bool IsSnowLineSet()
Has a snow line table already been loaded.
Definition: landscape.cpp:582
StationClassID
StationClassID
Definition: newgrf_station.h:83
ConstructionSettings::train_signal_side
byte train_signal_side
show signals on left / driving / right side
Definition: settings_type.h:376
HouseSpec::class_id
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:119
GRFParameterInfo::name
GRFTextList name
The name of this parameter.
Definition: newgrf_config.h:129
IndustrySpec::cleanup_flag
uint8_t cleanup_flag
flags indicating which data should be freed upon cleaning up
Definition: industrytype.h:137
GRFParameterInfo::def_value
uint32_t def_value
Default value of this parameter.
Definition: newgrf_config.h:134
RailVehicleInfo::weight
uint16_t weight
Weight of vehicle (tons); For multiheaded engines the weight of each single engine.
Definition: engine_type.h:50
Pool::PoolItem<&_engine_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:305
IndustryTileLayoutTile
Definition of one tile in an industry tile layout.
Definition: industrytype.h:94
EngineInfo::cargo_age_period
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:158
VehicleSettings::disable_elrails
bool disable_elrails
when true, the elrails are disabled
Definition: settings_type.h:523
TimerGameConst< struct Calendar >::MIN_YEAR
static constexpr TimerGame< struct Calendar >::Year MIN_YEAR
The absolute minimum year in OTTD.
Definition: timer_game_common.h:176
InitNewGRFFile
static void InitNewGRFFile(const GRFConfig *config)
Prepare loading a NewGRF file with its config.
Definition: newgrf.cpp:8900
CommitVehicleListOrderChanges
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
Definition: newgrf_engine.cpp:1329
ShipVehicleInfo
Information about a ship vehicle.
Definition: engine_type.h:67
HouseSpec::building_availability
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:110
NFO_UTF8_IDENTIFIER
static const char32_t NFO_UTF8_IDENTIFIER
This character, the thorn ('þ'), indicates a unicode string to NFO.
Definition: newgrf_text.h:19
NewGRFClass::name
StringID name
Name of this class.
Definition: newgrf_class.h:39
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:25
MapGRFStringID
StringID MapGRFStringID(uint32_t grfid, StringID str)
Used when setting an object's property to map to the GRF's strings while taking in consideration the ...
Definition: newgrf.cpp:550
RoadTypeFlags
RoadTypeFlags
Roadtype flags.
Definition: road.h:46
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
AirportSpec::GetWithoutOverride
static AirportSpec * GetWithoutOverride(byte type)
Retrieve airport spec for the given airport.
Definition: newgrf_airport.cpp:74
TileLayoutFlags
TileLayoutFlags
Flags to enable register usage in sprite layouts.
Definition: newgrf_commons.h:32
CargoSpec::name
StringID name
Name of this type of cargo.
Definition: cargotype.h:88
PROP_ROADVEH_CARGO_CAPACITY
@ PROP_ROADVEH_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:34
RailVehicleInfo::railtype
RailType railtype
Railtype, mangled if elrail is disabled.
Definition: engine_type.h:46
ResetNewGRFData
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8765
AircraftVehicleChangeInfo
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for aircraft.
Definition: newgrf.cpp:1742
GRFFile::cargo_list
std::vector< CargoLabel > cargo_list
Cargo translation table (local ID -> label)
Definition: newgrf.h:129
SanitizeSpriteOffset
static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const char *name)
Sanitize incoming sprite offsets for Action 5 graphics replacements.
Definition: newgrf.cpp:6360
GrfMsgI
void GrfMsgI(int severity, const std::string &msg)
Debug() function dedicated to newGRF debugging messages Function is essentially the same as Debug(grf...
Definition: newgrf.cpp:393
PalSpriteID
Combination of a palette sprite and a 'real' sprite.
Definition: gfx_type.h:22
GRFConfig::url
GRFTextWrapper url
NOSAVE: URL belonging to this GRF.
Definition: newgrf_config.h:159
GRFFile::labels
std::vector< GRFLabel > labels
List of labels.
Definition: newgrf.h:127
VSG_SCOPE_RELATIVE
@ VSG_SCOPE_RELATIVE
Relative position (vehicles only)
Definition: newgrf_spritegroup.h:102
ActivateOldTramDepot
static void ActivateOldTramDepot()
Replocate the old tram depot sprites to the new position, if no new ones were loaded.
Definition: newgrf.cpp:9724
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, AllowedSubtags *subtags)
Create a branch node with a list of sub-nodes.
Definition: newgrf.cpp:8349
container_func.hpp
ExtraEngineFlags
ExtraEngineFlags
Definition: engine_type.h:131
HZ_CLIMALL
@ HZ_CLIMALL
Bitmask of all climate bits.
Definition: house.h:84
RoadTypeInfo::strings
struct RoadTypeInfo::@29 strings
Strings associated with the rail type.
GrfProcessingState::stage
GrfLoadingStage stage
Current loading stage.
Definition: newgrf.cpp:100
ORIGINAL_SAMPLE_COUNT
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition: sound_type.h:116
_gted
static std::vector< GRFTempEngineData > _gted
Temporary engine data used during NewGRF loading.
Definition: newgrf.cpp:351
IgnoreObjectProperty
static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
Ignore properties for objects.
Definition: newgrf.cpp:4059
CHECK_NOTHING
@ CHECK_NOTHING
Always succeeds.
Definition: industrytype.h:38
AircraftVehicleInfo::mail_capacity
byte mail_capacity
Mail capacity (bags).
Definition: engine_type.h:108
NamePart
Definition: newgrf_townname.h:18
CargoSpec::name_single
StringID name_single
Name of a single entity of this type of cargo.
Definition: cargotype.h:89
GRFTownName::MAX_LISTS
static const uint MAX_LISTS
Maximum number of town name lists that can be defined per GRF.
Definition: newgrf_townname.h:39
PTYPE_END
@ PTYPE_END
Invalid parameter type.
Definition: newgrf_config.h:123
AllowedSubtags::id
uint32_t id
The identifier for this node.
Definition: newgrf.cpp:8357
GrfProcessingState::GetNumEnts
uint GetNumEnts(byte feature, uint set) const
Returns the number of sprites in a spriteset.
Definition: newgrf.cpp:189
CargoSpec::abbrev
StringID abbrev
Two letter abbreviation for this cargo type.
Definition: cargotype.h:92
HouseSpec::processing_time
byte processing_time
Periodic refresh multiplier.
Definition: house.h:121
IndustrySpec::life_type
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition: industrytype.h:121
Action5Type::name
const char * name
Name for error messages.
Definition: newgrf.cpp:6393
WaterFeature::flags
uint8_t flags
Flags controlling display.
Definition: newgrf_canal.h:26
RailVehicleInfo::power
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition: engine_type.h:49
FinaliseHouseArray
static void FinaliseHouseArray()
Add all new houses to the house array.
Definition: newgrf.cpp:9307
RailVehicleInfo::intended_railtype
RailType intended_railtype
Intended railtype, regardless of elrail being enabled or disabled.
Definition: engine_type.h:47
ObjectSpec::build_cost_multiplier
uint8_t build_cost_multiplier
Build cost multiplier per tile.
Definition: newgrf_object.h:69
NamePartList::parts
std::vector< NamePart > parts
List of parts to choose from.
Definition: newgrf_townname.h:28
NewGRFSpriteLayout::Clone
void Clone(const DrawTileSeqStruct *source)
Clone the building sprites of a spritelayout.
Definition: newgrf_commons.cpp:565
TileIndexDiffC::y
int16_t y
The y value of the coordinate.
Definition: map_type.h:33
RandomAccessFile::SeekTo
void SeekTo(size_t pos, int mode)
Seek in the current file.
Definition: random_access_file.cpp:84
RailTypeInfo::introduces_railtypes
RailTypes introduces_railtypes
Bitmask of which other railtypes are introduced when this railtype is introduced.
Definition: rail.h:266
RailVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:59
CurrencySpec::to_euro
TimerGameCalendar::Year to_euro
Year of switching to the Euro. May also be CF_NOEURO or CF_ISEURO.
Definition: currency.h:77
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:164
DrawTileSprites::seq
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition: sprite.h:60
CIR_UNKNOWN
@ CIR_UNKNOWN
Variable is unknown.
Definition: newgrf.cpp:982
GRFTempEngineData::NONEMPTY
@ NONEMPTY
GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not av...
Definition: newgrf.cpp:324
TimerGame< struct Calendar >::DateFract
uint16_t DateFract
The fraction of a date we're in, i.e.
Definition: timer_game_common.h:38
IndustrySpec::behaviour
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Definition: industrytype.h:123
ResetObjects
void ResetObjects()
This function initialize the spec arrays of objects.
Definition: newgrf_object.cpp:121
EngineInfo::retire_early
int8_t retire_early
Number of years early to retire vehicle.
Definition: engine_type.h:156
TileLayoutRegisters::sprite
uint8_t sprite
Register specifying a signed offset for the sprite.
Definition: newgrf_commons.h:93
RoadTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:142
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:300
CurrencySpec::separator
std::string separator
The thousands separator for this currency.
Definition: currency.h:76
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:124
RailVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:48
NewGRFClass::Get
static NewGRFClass * Get(Tid cls_id)
Get a particular class.
Definition: newgrf_class_func.h:98
Map::LogY
static uint LogY()
Logarithm of the map size along the y side.
Definition: map_func.h:261
InitializeGRFSpecial
static void InitializeGRFSpecial()
Initialize the TTDPatch flags.
Definition: newgrf.cpp:8594
BridgeSpec::avail_year
TimerGameCalendar::Year avail_year
the year where it becomes available
Definition: bridge.h:43
MemSetT
void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
DataHandler
bool(* DataHandler)(size_t, ByteReader *)
Type of callback function for binary nodes.
Definition: newgrf.cpp:8289
GRFIdentifier::grfid
uint32_t grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:84
RandomizedSpriteGroup::lowest_randbit
byte lowest_randbit
Look for this in the per-object randomized bitmask:
Definition: newgrf_spritegroup.h:199
ActivateOldShore
static void ActivateOldShore()
Relocates the old shore sprites at new positions.
Definition: newgrf.cpp:9687
AircraftVehicleInfo::passenger_capacity
uint16_t passenger_capacity
Passenger capacity (persons).
Definition: engine_type.h:109
BridgeSpec::material
StringID material
the string that contains the bridge description
Definition: bridge.h:50
TileLayoutRegisters::flags
TileLayoutFlags flags
Flags defining which members are valid and to be used.
Definition: newgrf_commons.h:91
AirportSpec::depot_table
const HangarTileTable * depot_table
gives the position of the depots on the airports
Definition: newgrf_airport.h:105
GRFConfig::num_params
uint8_t num_params
Number of used parameters.
Definition: newgrf_config.h:168
SkipUnknownInfo
static bool SkipUnknownInfo(ByteReader *buf, byte type)
Try to skip the current node and all subnodes (if it's a branch node).
Definition: newgrf.cpp:8481
LanguagePackHeader::GetCaseIndex
uint8_t GetCaseIndex(const char *case_str) const
Get the index for the given case.
Definition: language.h:81
newgrf_canal.h
TimerGameConst< struct Calendar >::ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: timer_game_common.h:163
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_LVL_BASE.
Definition: tile_type.h:18
IgnoreTownHouseProperty
static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
Ignore a house property.
Definition: newgrf.cpp:2303
RoadStopDrawMode
RoadStopDrawMode
Different draw modes to disallow rendering of some parts of the stop or road.
Definition: newgrf_roadstop.h:58
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
ROADTYPE_TRAM
@ ROADTYPE_TRAM
Trams.
Definition: road_type.h:28
TileLayoutRegisters::child
uint8_t child[2]
Registers for signed offsets for the position of child sprites.
Definition: newgrf_commons.h:99
VehicleSettings::never_expire_vehicles
bool never_expire_vehicles
never expire vehicles
Definition: settings_type.h:531
OverrideManagerBase::Add
void Add(uint16_t local_id, uint32_t grfid, uint entity_type)
Since the entity IDs defined by the GRF file does not necessarily correlate to those used by the game...
Definition: newgrf_commons.cpp:62
HouseSpec
Definition: house.h:98
config.h
GetNewgrfCurrencyIdConverted
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id)
Will return the ottd's index correspondence to the ttdpatch's id.
Definition: currency.cpp:115
GrfProcessingState::SpriteSet::num_sprites
uint num_sprites
Number of sprites in the set.
Definition: newgrf.cpp:92
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:24
RoadVehicleInfo::weight
uint8_t weight
Weight in 1/4t units.
Definition: engine_type.h:122
PROP_SHIP_COST_FACTOR
@ PROP_SHIP_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:43
ChangeInfoResult
ChangeInfoResult
Possible return values for the FeatureChangeInfo functions.
Definition: newgrf.cpp:978
engine_base.h
IndustryProductionSpriteGroup::cargo_output
CargoID cargo_output[INDUSTRY_NUM_OUTPUTS]
Which output cargoes to add to (only cb version 2)
Definition: newgrf_spritegroup.h:277
SpriteGroupCargo::SG_DEFAULT_NA
static constexpr CargoID SG_DEFAULT_NA
Used only by stations and roads when no more-specific cargo matches.
Definition: newgrf_cargo.h:25
IgnoreRoadStopProperty
static ChangeInfoResult IgnoreRoadStopProperty(uint prop, ByteReader *buf)
Ignore properties for roadstops.
Definition: newgrf.cpp:4765
BridgeChangeInfo
static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
Define properties for bridges.
Definition: newgrf.cpp:2192
RailTypeInfo::flags
RailTypeFlags flags
Bit mask of rail type flags.
Definition: rail.h:211
fontcache.h
_object_mngr
ObjectOverrideManager _object_mngr
The override manager for our objects.
RandomAccessFile::ReadDword
uint32_t ReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: random_access_file.cpp:128
HouseZones
HouseZones
Definition: house.h:71
ShipVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:71
ReadDWordAsString
static std::string ReadDWordAsString(ByteReader *reader)
Helper to read a DWord worth of bytes from the reader and to return it as a valid string.
Definition: newgrf.cpp:2661
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:90
RailTypeChangeInfo
static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for railtypes.
Definition: newgrf.cpp:4238
Engine::grf_prop
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:77
RAILVEH_SINGLEHEAD
@ RAILVEH_SINGLEHEAD
indicates a "standalone" locomotive
Definition: engine_type.h:27
GRFFile::GetParam
uint32_t GetParam(uint number) const
Get GRF Parameter with range checking.
Definition: newgrf.h:155
IndustryTileSpecialFlags
IndustryTileSpecialFlags
Flags for miscellaneous industry tile specialities.
Definition: industrytype.h:86
IndustrySpec::check_proc
byte check_proc
Index to a procedure to check for conflicting circumstances.
Definition: industrytype.h:111
ReadGRFSpriteOffsets
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Definition: spritecache.cpp:553
SB
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
RailVehicleInfo::running_cost
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition: engine_type.h:51
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:168
GetRailTypeByLabel
RailType GetRailTypeByLabel(RailTypeLabel label, bool allow_alternate_labels)
Get the rail type for a given label.
Definition: rail.cpp:311
NEW_INDUSTRYTILEOFFSET
static const IndustryGfx NEW_INDUSTRYTILEOFFSET
original number of tiles
Definition: industry_type.h:32
newgrf_industries.h
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
EconomySettings::inflation
bool inflation
disable inflation
Definition: settings_type.h:539
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition: timer_game_calendar.h:34
TAE_NONE
@ TAE_NONE
Cargo has no effect.
Definition: cargotype.h:26
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:620
GrfProcessingState::IsValidSpriteSet
bool IsValidSpriteSet(byte feature, uint set) const
Check whether a specific set is defined.
Definition: newgrf.cpp:165
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:627
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:202
EngineID
uint16_t EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
TLF_PALETTE_REG_FLAGS
@ TLF_PALETTE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the palette, even if it is no action-1 palet...
Definition: newgrf_commons.h:64
TLF_SPRITE
@ TLF_SPRITE
Add signed offset to sprite from register TileLayoutRegisters::sprite.
Definition: newgrf_commons.h:36
ClearTemporaryNewGRFData
static void ClearTemporaryNewGRFData(GRFFile *gf)
Reset all NewGRFData that was used only while processing data.
Definition: newgrf.cpp:425
EngineInfo::climates
byte climates
Climates supported by the engine.
Definition: engine_type.h:150
TLF_PALETTE
@ TLF_PALETTE
Add signed offset to palette from register TileLayoutRegisters::palette.
Definition: newgrf_commons.h:37
PTYPE_UINT_ENUM
@ PTYPE_UINT_ENUM
The parameter allows a range of numbers, each of which can have a special name.
Definition: newgrf_config.h:121
AirportSpec::nof_depots
byte nof_depots
the number of hangar tiles in this airport
Definition: newgrf_airport.h:106
_grm_cargoes
static uint32_t _grm_cargoes[NUM_CARGO *2]
Contains the GRF ID of the owner of a cargo if it has been reserved.
Definition: newgrf.cpp:360
PROP_AIRCRAFT_PASSENGER_CAPACITY
@ PROP_AIRCRAFT_PASSENGER_CAPACITY
Passenger Capacity.
Definition: newgrf_properties.h:52
PROP_SHIP_SPEED
@ PROP_SHIP_SPEED
Max. speed: 1 unit = 1/3.2 mph = 0.5 km-ish/h.
Definition: newgrf_properties.h:44
ClearSnowLine
void ClearSnowLine()
Clear the variable snow line table and free the memory.
Definition: landscape.cpp:643
HouseSpec::random_colour
Colours random_colour[4]
4 "random" colours
Definition: house.h:116
ResetRoadTypes
void ResetRoadTypes()
Reset all road type information to its default values.
Definition: road_cmd.cpp:67
AirportTileSpec::callback_mask
uint8_t callback_mask
Bitmask telling which grf callback is set.
Definition: newgrf_airporttiles.h:71
GRFPalette
GRFPalette
Information that can/has to be stored about a GRF's palette.
Definition: newgrf_config.h:59
StationSpec::callback_mask
byte callback_mask
Bitmask of station callbacks that have to be called.
Definition: newgrf_station.h:157
PROP_ROADVEH_POWER
@ PROP_ROADVEH_POWER
Power in 10 HP.
Definition: newgrf_properties.h:36
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
RandomizedSpriteGroup
Definition: newgrf_spritegroup.h:190
NUM_ORIGINAL_CARGO
static const CargoID NUM_ORIGINAL_CARGO
Original number of cargo types.
Definition: cargo_type.h:67
IndustrySpec::name
StringID name
Displayed name of the industry.
Definition: industrytype.h:125
ChangeGRFParamDefault
static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PARAM'->param_num->'DFLT' to set the default value.
Definition: newgrf.cpp:8277
IndustryBehaviour
IndustryBehaviour
Various industry behaviours mostly to represent original TTD specialities.
Definition: industrytype.h:59
PROP_TRAIN_COST_FACTOR
@ PROP_TRAIN_COST_FACTOR
Purchase cost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:26
IndustrySpec::new_industry_text
StringID new_industry_text
Message appearing when the industry is built.
Definition: industrytype.h:126
StationSpec::disallowed_lengths
byte disallowed_lengths
Bitmask of platform lengths available for the station.
Definition: newgrf_station.h:137
_misc_grf_features
byte _misc_grf_features
Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E.
Definition: newgrf.cpp:76
RailVehicleInfo::capacity
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition: engine_type.h:54
IndustryProductionSpriteGroup::cargo_input
CargoID cargo_input[INDUSTRY_NUM_INPUTS]
Which input cargoes to take from (only cb version 2)
Definition: newgrf_spritegroup.h:274
DefineGotoLabel
static void DefineGotoLabel(ByteReader *buf)
Action 0x10 - Define goto label.
Definition: newgrf.cpp:7808
TPE_PASSENGERS
@ TPE_PASSENGERS
Cargo behaves passenger-like for production.
Definition: cargotype.h:39
ByteReader
Class to read from a NewGRF file.
Definition: newgrf.cpp:214
LoadGRFSound
static void LoadGRFSound(size_t offs, SoundEntry *sound)
Load a sound from a file.
Definition: newgrf.cpp:7857
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
TTDPStringIDToOTTDStringIDMapping
static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
Perform a mapping from TTDPatch's string IDs to OpenTTD's string IDs, but only for the ones we are aw...
Definition: newgrf.cpp:486
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:319
PROP_AIRCRAFT_SPEED
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
Definition: newgrf_properties.h:50
CanalProperties
Canal properties local to the NewGRF.
Definition: newgrf.h:39
CargoSpec::town_production_multiplier
uint16_t town_production_multiplier
Town production multipler, if commanded by TownProductionEffect.
Definition: cargotype.h:85
ResetBridges
void ResetBridges()
Reset the data been eventually changed by the grf loaded.
Definition: tunnelbridge_cmd.cpp:86
Utf8Decode
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:438
AllowedSubtags::data
DataHandler data
Callback function for a binary node, only valid if type == 'B'.
Definition: newgrf.cpp:8360
AirportTileTable::ti
TileIndexDiffC ti
Tile offset from the top-most airport tile.
Definition: newgrf_airport.h:26
NUM_CARGO
static const CargoID NUM_CARGO
Maximum number of cargo types in a game.
Definition: cargo_type.h:68
EngineInfo::string_id
StringID string_id
Default name of engine.
Definition: engine_type.h:157
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition: engine_type.h:100
GetLanguage
const LanguageMetadata * GetLanguage(byte newgrflangid)
Get the language with the given NewGRF language ID.
Definition: strings.cpp:2041
RailTypeFlags
RailTypeFlags
Railtype flags.
Definition: rail.h:35
TileLayoutRegisters::max_sprite_offset
uint16_t max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset)
Definition: newgrf_commons.h:95
AirportSpec::table
const AirportTileTable *const * table
list of the tiles composing the airport
Definition: newgrf_airport.h:102
HangarTileTable
A list of all hangar tiles in an airport.
Definition: newgrf_airport.h:91
DrawTileSeqStruct::delta_x
int8_t delta_x
0x80 is sequence terminator
Definition: sprite.h:26
CreateGroupFromGroupID
static const SpriteGroup * CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16_t spriteid)
Helper function to either create a callback or a result sprite group.
Definition: newgrf.cpp:5155
PROP_TRAIN_POWER
@ PROP_TRAIN_POWER
Power in hp (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:22
AirportTileSpec::Get
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
Definition: newgrf_airporttiles.cpp:37
HouseSpec::min_year
TimerGameCalendar::Year min_year
introduction year of the house
Definition: house.h:100
TownHouseChangeInfo
static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
Define properties for houses.
Definition: newgrf.cpp:2370
HouseSpec::remove_rating_decrease
uint16_t remove_rating_decrease
rating decrease if removed
Definition: house.h:105
TAE_MAIL
@ TAE_MAIL
Cargo behaves mail-like.
Definition: cargotype.h:28
IndustryOverrideManager::SetEntitySpec
void SetEntitySpec(IndustrySpec *inds)
Method to install the new industry data in its proper slot The slot assignment is internal of this me...
Definition: newgrf_commons.cpp:243
PROP_TRAIN_CARGO_AGE_PERIOD
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:30
ResetIndustries
void ResetIndustries()
This function initialize the spec arrays of both industry and industry tiles.
Definition: industry_cmd.cpp:80
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
ChangeGRFPalette
static bool ChangeGRFPalette(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PALS' to set the number of valid parameters.
Definition: newgrf.cpp:8120
LoadFontGlyph
static void LoadFontGlyph(ByteReader *buf)
Action 0x12.
Definition: newgrf.cpp:7977
PROP_ROADVEH_RUNNING_COST_FACTOR
@ PROP_ROADVEH_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:33
SPR_TRACKS_FOR_SLOPES_BASE
static const SpriteID SPR_TRACKS_FOR_SLOPES_BASE
Sprites for 'highlighting' tracks on sloped land.
Definition: sprites.h:198
ResultSpriteGroup
Definition: newgrf_spritegroup.h:236
GetCargoTranslation
CargoID GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:79
IndustryTileSpec::anim_next
byte anim_next
Next frame in an animation.
Definition: industrytype.h:159
IndustryTileSpec
Defines the data structure of each individual tile of an industry.
Definition: industrytype.h:154
GRFLoadedFeatures
Definition: newgrf.h:177
TLF_DRAWING_FLAGS
@ TLF_DRAWING_FLAGS
Flags which are still required after loading the GRF.
Definition: newgrf_commons.h:52
TLF_PALETTE_VAR10
@ TLF_PALETTE_VAR10
Resolve palette with a specific value in variable 10.
Definition: newgrf_commons.h:47
InitRailTypes
void InitRailTypes()
Resolve sprites of custom rail types.
Definition: rail_cmd.cpp:130
CurrencySpec::prefix
std::string prefix
Prefix to apply when formatting money in this currency.
Definition: currency.h:78
CC_MAIL
@ CC_MAIL
Mail.
Definition: cargotype.h:54
RailTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: rail.h:179
RoadVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:120
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
DisableGrf
static GRFError * DisableGrf(StringID message=STR_NULL, GRFConfig *config=nullptr)
Disable a GRF.
Definition: newgrf.cpp:436
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition: newgrf_airporttiles.h:74
TLF_SPRITE_REG_FLAGS
@ TLF_SPRITE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the sprite, even if it is no action-1 sprite...
Definition: newgrf_commons.h:61
InitRoadTypes
void InitRoadTypes()
Resolve sprites of custom road types.
Definition: road_cmd.cpp:114
RailTypeInfo::acceleration_type
uint8_t acceleration_type
Acceleration type of this rail type.
Definition: rail.h:226
RoadTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: road.h:106
GrfProcessingState::skip_sprites
int skip_sprites
Number of pseudo sprites to skip before processing the next one. (-1 to skip to end of file)
Definition: newgrf.cpp:110
RailTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: rail.h:180
OpenCachedSpriteFile
SpriteFile & OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
Open/get the SpriteFile that is cached for use in the sprite cache.
Definition: spritecache.cpp:84
ResetCustomStations
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8683
HZ_ZON1
@ HZ_ZON1
0..4 1,2,4,8,10 which town zones the building can be built in, Zone1 been the further suburb
Definition: house.h:73
TLF_SPRITE_VAR10
@ TLF_SPRITE_VAR10
Resolve sprite with a specific value in variable 10.
Definition: newgrf_commons.h:46
PROP_AIRCRAFT_RANGE
@ PROP_AIRCRAFT_RANGE
Aircraft range.
Definition: newgrf_properties.h:55
EconomySettings::allow_town_roads
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Definition: settings_type.h:555
GRFFile::cargo_map
std::array< uint8_t, NUM_CARGO > cargo_map
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:130
BuildLinkStatsLegend
void BuildLinkStatsLegend()
Populate legend table for the link stat view.
Definition: smallmap_gui.cpp:216
ChangeGRFParamDescription
static bool ChangeGRFParamDescription(byte langid, const char *str)
Callback function for 'INFO'->'PARAM'->param_num->'DESC' to set the description of a parameter.
Definition: newgrf.cpp:8210
IndustrySpec::input_cargo_multiplier
uint16_t input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes)
Definition: industrytype.h:120
RoadTypeInfo::introduction_required_roadtypes
RoadTypes introduction_required_roadtypes
Bitmask of roadtypes that are required for this roadtype to be introduced at a given introduction_dat...
Definition: road.h:172
ReadSpriteLayout
static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
Read a spritelayout from the GRF.
Definition: newgrf.cpp:848
GetCargoIDByLabel
CargoID GetCargoIDByLabel(CargoLabel cl)
Get the cargo ID by cargo label.
Definition: cargotype.cpp:115
TileIndexDiffC::x
int16_t x
The x value of the coordinate.
Definition: map_type.h:32
newgrf_cargo.h
SetYearEngineAgingStops
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:655
GRFFile::railtype_list
std::vector< RailTypeLabel > railtype_list
Railtype translation table.
Definition: newgrf.h:132
AirportSpec::catchment
byte catchment
catchment area of this airport
Definition: newgrf_airport.h:110
RandomizedSpriteGroup::groups
std::vector< const SpriteGroup * > groups
Take the group with appropriate index:
Definition: newgrf_spritegroup.h:201
StationSpec::cargo_triggers
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
Definition: newgrf_station.h:155
ObjectSpec::clear_cost_multiplier
uint8_t clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_object.h:70
SpriteGroup
Definition: newgrf_spritegroup.h:57
GRFLabel
Definition: newgrf.h:98
SkipAct12
static void SkipAct12(ByteReader *buf)
Action 0x12 (SKIP)
Definition: newgrf.cpp:8008
SPR_ONEWAY_BASE
static const SpriteID SPR_ONEWAY_BASE
One way road sprites.
Definition: sprites.h:293
HouseSpec::grf_prop
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:114
AddStringForMapping
static void AddStringForMapping(StringID source, StringID *target)
Record a static StringID for getting translated later.
Definition: newgrf.cpp:473
CargoSpec::multiplier
uint16_t multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:77
ResetGenericCallbacks
void ResetGenericCallbacks()
Reset all generic feature callback sprite groups.
Definition: newgrf_generic.cpp:94
Action5Type
Information about a single action 5 type.
Definition: newgrf.cpp:6388
_currency_specs
CurrencySpec _currency_specs[CURRENCY_END]
Array of currencies used by the system.
Definition: currency.cpp:76
EngineInfo::base_intro
TimerGameCalendar::Date base_intro
Basic date of engine introduction (without random parts).
Definition: engine_type.h:145
NamePart::id
byte id
If probability bit 7 is set.
Definition: newgrf_townname.h:20
LanguageMap::Mapping::newgrf_id
byte newgrf_id
NewGRF's internal ID for a case/gender.
Definition: newgrf_text.h:56
StationSpec::wires
byte wires
Bitmask of base tiles (0 - 7) which should contain elrail wires.
Definition: newgrf_station.h:162
TAE_PASSENGERS
@ TAE_PASSENGERS
Cargo behaves passenger-like.
Definition: cargotype.h:27
AddGRFTextToList
static void AddGRFTextToList(GRFTextList &list, byte langid, const std::string &text_to_add)
Add a new text to a GRFText list.
Definition: newgrf_text.cpp:485
EngineInfo::lifelength
TimerGameCalendar::Year lifelength
Lifetime of a single vehicle.
Definition: engine_type.h:146
RoadStopSpec::cargo_triggers
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
Definition: newgrf_roadstop.h:139
SetEngineGRF
void SetEngineGRF(EngineID engine, const GRFFile *file)
Tie a GRFFile entry to an engine, to allow us to retrieve GRF parameters etc during a game.
Definition: newgrf_engine.cpp:71
OrderSettings::gradual_loading
bool gradual_loading
load vehicles gradually
Definition: settings_type.h:507
Action5Type::min_sprites
uint16_t min_sprites
If the Action5 contains less sprites, the whole block will be ignored.
Definition: newgrf.cpp:6391
GCF_STATIC
@ GCF_STATIC
GRF file is used statically (can be used in any MP game)
Definition: newgrf_config.h:25
NewGRFSpriteLayout::Allocate
void Allocate(uint num_sprites)
Allocate a spritelayout for num_sprites building sprites.
Definition: newgrf_commons.cpp:603
IndustryLifeType
IndustryLifeType
Available types of industry lifetimes.
Definition: industrytype.h:26
GRFFile
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:107
ObjectSpec::cls_id
ObjectClassID cls_id
The class to which this spec belongs.
Definition: newgrf_object.h:64
PROP_TRAIN_USER_DATA
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
Definition: newgrf_properties.h:29
ShipVehicleInfo::ocean_speed_frac
byte ocean_speed_frac
Fraction of maximum speed for ocean tiles.
Definition: engine_type.h:77
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:56
IgnoreIndustryTileProperty
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
Ignore an industry tile property.
Definition: newgrf.cpp:3185
StationSpec::blocked
byte blocked
Bitmask of base tiles (0 - 7) which are blocked to trains.
Definition: newgrf_station.h:163
debug.h
OverrideManagerBase::GetID
virtual uint16_t GetID(uint16_t grf_local_id, uint32_t grfid) const
Return the ID (if ever available) of a previously inserted entity.
Definition: newgrf_commons.cpp:90
_grm_engines
static uint32_t _grm_engines[256]
Contains the GRF ID of the owner of a vehicle if it has been reserved.
Definition: newgrf.cpp:357
TileLayoutSpriteGroup
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition: newgrf_spritegroup.h:259
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:98
BridgeSpec::max_length
uint16_t max_length
the maximum length (not counting start and end tile)
Definition: bridge.h:45
PROP_ROADVEH_WEIGHT
@ PROP_ROADVEH_WEIGHT
Weight in 1/4 t.
Definition: newgrf_properties.h:37
SPR_TRAMWAY_BASE
static const SpriteID SPR_TRAMWAY_BASE
Tramway sprites.
Definition: sprites.h:272
engine_func.h
AddGenericCallback
void AddGenericCallback(uint8_t feature, const GRFFile *file, const SpriteGroup *group)
Add a generic feature callback sprite group to the appropriate feature list.
Definition: newgrf_generic.cpp:108
AirportTileSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_airporttiles.h:69
EC_MONORAIL
@ EC_MONORAIL
Mono rail engine.
Definition: engine_type.h:37
GRFError::data
std::string data
Additional data for message and custom_message.
Definition: newgrf_config.h:113
WaterFeature::group
const SpriteGroup * group
Sprite group to start resolving.
Definition: newgrf_canal.h:23
CargoSpec::classes
uint16_t classes
Classes of this cargo type.
Definition: cargotype.h:78
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition: timer_game_calendar.h:32
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition: rail_type.h:34
DrawTileSeqStruct
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition: sprite.h:25
TileLayoutRegisters::palette_var10
uint8_t palette_var10
Value for variable 10 when resolving the palette.
Definition: newgrf_commons.h:102
ObjectSpec::flags
ObjectFlags flags
Flags/settings related to the object.
Definition: newgrf_object.h:73
RoadTypeChangeInfo
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
Define properties for roadtypes.
Definition: newgrf.cpp:4456
HouseOverrideManager::SetEntitySpec
void SetEntitySpec(const HouseSpec *hs)
Install the specs into the HouseSpecs array It will find itself the proper slot on which it will go.
Definition: newgrf_commons.cpp:159
ObjectSpec::views
uint8_t views
The number of views.
Definition: newgrf_object.h:76
StringIDMapping::grfid
uint32_t grfid
Source NewGRF.
Definition: newgrf.cpp:461
GRFFile::grf_features
uint32_t grf_features
Bitset of GrfSpecFeature the grf uses.
Definition: newgrf.h:148
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
SNOW_LINE_MONTHS
static const uint SNOW_LINE_MONTHS
Number of months in the snow line table.
Definition: landscape.h:16
CargoSpec::town_acceptance_effect
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:83
ReadSpriteLayoutRegisters
static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
Preprocess the TileLayoutFlags and read register modifiers from the GRF.
Definition: newgrf.cpp:795
GRFP_BLT_MASK
@ GRFP_BLT_MASK
Bitmask to only get the blitter information.
Definition: newgrf_config.h:78
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition: bitmath_func.hpp:194
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103