OpenTTD Source: src/newgrf.cpp Source File

OpenTTD Source 13.2.1

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 <stdarg.h>
13
14 #include "debug.h"
15 #include "fileio_func.h"
16 #include "engine_func.h"
17 #include "engine_base.h"
18 #include "bridge.h"
19 #include "town.h"
20 #include "newgrf_engine.h"
21 #include "newgrf_text.h"
22 #include "fontcache.h"
23 #include "currency.h"
24 #include "landscape.h"
25 #include "newgrf_cargo.h"
26 #include "newgrf_house.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_station.h"
29 #include "industrytype.h"
30 #include "industry_map.h"
31 #include "newgrf_canal.h"
32 #include "newgrf_townname.h"
33 #include "newgrf_industries.h"
34 #include "newgrf_airporttiles.h"
35 #include "newgrf_airport.h"
36 #include "newgrf_object.h"
37 #include "rev.h"
38 #include "fios.h"
39 #include "strings_func.h"
40 #include "date_func.h"
41 #include "string_func.h"
42 #include "network/core/config.h"
43 #include <map>
44 #include "smallmap_gui.h"
45 #include "genworld.h"
46 #include "error.h"
47 #include "vehicle_func.h"
48 #include "language.h"
49 #include "vehicle_base.h"
50 #include "road.h"
51
52 #include "table/strings.h"
53 #include "table/build_industry.h"
54
55 #include "safeguards.h"
56
57 /* TTDPatch extended GRF format codec
58 * (c) Petr Baudis 2004 (GPL'd)
59 * Changes by Florian octo Forster are (c) by the OpenTTD development team.
60 *
61 * Contains portions of documentation by TTDPatch team.
62 * Thanks especially to Josef Drexler for the documentation as well as a lot
63 * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
64 * served as subject to the initial testing of this codec. */
65
67 static std::vector<GRFFile *> _grf_files;
68
69 const std::vector<GRFFile *> &GetAllGRFFiles()
70 {
71 return _grf_files;
72 }
73
75 byte _misc_grf_features = 0;
76
78 static uint32 _ttdpatch_flags[8];
79
81 GRFLoadedFeatures _loaded_newgrf_features;
82
83 static const uint MAX_SPRITEGROUP = UINT8_MAX;
84
86 struct GrfProcessingState {
87 private:
89 struct SpriteSet {
90 SpriteID sprite;
91 uint num_sprites;
92 };
93
95 std::map<uint, SpriteSet> spritesets[GSF_END];
96
97 public:
98 /* Global state */
99 GrfLoadingStage stage;
100 SpriteID spriteid;
101
102 /* Local state in the file */
103 SpriteFile *file;
104 GRFFile *grffile;
105 GRFConfig *grfconfig;
106 uint32 nfo_line;
107
108 /* Kind of return values when processing certain actions */
109 int skip_sprites;
110
111 /* Currently referenceable spritegroups */
112 const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
113
115 void ClearDataForNextFile()
116 {
117 this->nfo_line = 0;
118 this->skip_sprites = 0;
119
120 for (uint i = 0; i < GSF_END; i++) {
121 this->spritesets[i].clear();
122 }
123
124 memset(this->spritegroups, 0, sizeof(this->spritegroups));
125 }
126
135 void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
136 {
137 assert(feature < GSF_END);
138 for (uint i = 0; i < numsets; i++) {
139 SpriteSet &set = this->spritesets[feature][first_set + i];
140 set.sprite = first_sprite + i * numents;
141 set.num_sprites = numents;
142 }
143 }
144
151 bool HasValidSpriteSets(byte feature) const
152 {
153 assert(feature < GSF_END);
154 return !this->spritesets[feature].empty();
155 }
156
164 bool IsValidSpriteSet(byte feature, uint set) const
165 {
166 assert(feature < GSF_END);
167 return this->spritesets[feature].find(set) != this->spritesets[feature].end();
168 }
169
176 SpriteID GetSprite(byte feature, uint set) const
177 {
178 assert(IsValidSpriteSet(feature, set));
179 return this->spritesets[feature].find(set)->second.sprite;
180 }
181
188 uint GetNumEnts(byte feature, uint set) const
189 {
190 assert(IsValidSpriteSet(feature, set));
191 return this->spritesets[feature].find(set)->second.num_sprites;
192 }
193 };
194
195 static GrfProcessingState _cur;
196
197
204 template <VehicleType T>
205 static inline bool IsValidNewGRFImageIndex(uint8 image_index)
206 {
207 return image_index == 0xFD || IsValidImageIndex<T>(image_index);
208 }
209
210 class OTTDByteReaderSignal { };
211
213 class ByteReader {
214 protected:
215 byte *data;
216 byte *end;
217
218 public:
219 ByteReader(byte *data, byte *end) : data(data), end(end) { }
220
221 inline byte *ReadBytes(size_t size)
222 {
223 if (data + size >= end) {
224 /* Put data at the end, as would happen if every byte had been individually read. */
225 data = end;
226 throw OTTDByteReaderSignal();
227 }
228
229 byte *ret = data;
230 data += size;
231 return ret;
232 }
233
234 inline byte ReadByte()
235 {
236 if (data < end) return *(data)++;
237 throw OTTDByteReaderSignal();
238 }
239
240 uint16 ReadWord()
241 {
242 uint16 val = ReadByte();
243 return val | (ReadByte() << 8);
244 }
245
246 uint16 ReadExtendedByte()
247 {
248 uint16 val = ReadByte();
249 return val == 0xFF ? ReadWord() : val;
250 }
251
252 uint32 ReadDWord()
253 {
254 uint32 val = ReadWord();
255 return val | (ReadWord() << 16);
256 }
257
258 uint32 ReadVarSize(byte size)
259 {
260 switch (size) {
261 case 1: return ReadByte();
262 case 2: return ReadWord();
263 case 4: return ReadDWord();
264 default:
265 NOT_REACHED();
266 return 0;
267 }
268 }
269
270 const char *ReadString()
271 {
272 char *string = reinterpret_cast<char *>(data);
273 size_t string_length = ttd_strnlen(string, Remaining());
274
275 if (string_length == Remaining()) {
276 /* String was not NUL terminated, so make sure it is now. */
277 string[string_length - 1] = '\0';
278 grfmsg(7, "String was not terminated with a zero byte.");
279 } else {
280 /* Increase the string length to include the NUL byte. */
281 string_length++;
282 }
283 Skip(string_length);
284
285 return string;
286 }
287
288 inline size_t Remaining() const
289 {
290 return end - data;
291 }
292
293 inline bool HasData(size_t count = 1) const
294 {
295 return data + count <= end;
296 }
297
298 inline byte *Data()
299 {
300 return data;
301 }
302
303 inline void Skip(size_t len)
304 {
305 data += len;
306 /* It is valid to move the buffer to exactly the end of the data,
307 * as there may not be any more data read. */
308 if (data > end) throw OTTDByteReaderSignal();
309 }
310 };
311
312 typedef void (*SpecialSpriteHandler)(ByteReader *buf);
313
314 static const uint NUM_STATIONS_PER_GRF = 255;
315
317 struct GRFTempEngineData {
319 enum Refittability {
320 UNSET = 0,
321 EMPTY,
322 NONEMPTY,
323 };
324
325 uint16 cargo_allowed;
326 uint16 cargo_disallowed;
327 RailTypeLabel railtypelabel;
328 uint8 roadtramtype;
329 const GRFFile *defaultcargo_grf;
330 Refittability refittability;
331 uint8 rv_max_speed;
332 CargoTypes ctt_include_mask;
333 CargoTypes ctt_exclude_mask;
334
339 void UpdateRefittability(bool non_empty)
340 {
341 if (non_empty) {
342 this->refittability = NONEMPTY;
343 } else if (this->refittability == UNSET) {
344 this->refittability = EMPTY;
345 }
346 }
347 };
348
349 static GRFTempEngineData *_gted;
350
355 static uint32 _grm_engines[256];
356
358 static uint32 _grm_cargoes[NUM_CARGO * 2];
359
360 struct GRFLocation {
361 uint32 grfid;
362 uint32 nfoline;
363
364 GRFLocation(uint32 grfid, uint32 nfoline) : grfid(grfid), nfoline(nfoline) { }
365
366 bool operator<(const GRFLocation &other) const
367 {
368 return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
369 }
370
371 bool operator == (const GRFLocation &other) const
372 {
373 return this->grfid == other.grfid && this->nfoline == other.nfoline;
374 }
375 };
376
377 static std::map<GRFLocation, SpriteID> _grm_sprites;
378 typedef std::map<GRFLocation, byte*> GRFLineToSpriteOverride;
379 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
380
391 void CDECL grfmsg(int severity, const char *str, ...)
392 {
393 char buf[1024];
394 va_list va;
395
396 va_start(va, str);
397 vseprintf(buf, lastof(buf), str, va);
398 va_end(va);
399
400 Debug(grf, severity, "[{}:{}] {}", _cur.grfconfig->filename, _cur.nfo_line, buf);
401 }
402
408 static GRFFile *GetFileByGRFID(uint32 grfid)
409 {
410 for (GRFFile * const file : _grf_files) {
411 if (file->grfid == grfid) return file;
412 }
413 return nullptr;
414 }
415
421 static GRFFile *GetFileByFilename(const char *filename)
422 {
423 for (GRFFile * const file : _grf_files) {
424 if (strcmp(file->filename, filename) == 0) return file;
425 }
426 return nullptr;
427 }
428
430 static void ClearTemporaryNewGRFData(GRFFile *gf)
431 {
432 gf->labels.clear();
433 }
434
441 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
442 {
443 GRFFile *file;
444 if (config != nullptr) {
445 file = GetFileByGRFID(config->ident.grfid);
446 } else {
447 config = _cur.grfconfig;
448 file = _cur.grffile;
449 }
450
451 config->status = GCS_DISABLED;
452 if (file != nullptr) ClearTemporaryNewGRFData(file);
453 if (config == _cur.grfconfig) _cur.skip_sprites = -1;
454
455 if (message != STR_NULL) {
456 delete config->error;
457 config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, message);
458 if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
459 }
460
461 return config->error;
462 }
463
467 struct StringIDMapping {
468 uint32 grfid;
469 StringID source;
470 StringID *target;
471 };
472 typedef std::vector<StringIDMapping> StringIDMappingVector;
473 static StringIDMappingVector _string_to_grf_mapping;
474
480 static void AddStringForMapping(StringID source, StringID *target)
481 {
482 *target = STR_UNDEFINED;
483 _string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
484 }
485
493 static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
494 {
495 /* StringID table for TextIDs 0x4E->0x6D */
496 static const StringID units_volume[] = {
497 STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
498 STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
499 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
500 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
501 STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
502 STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
503 STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
504 STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
505 };
506
507 /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
508 assert(!IsInsideMM(str, 0xD000, 0xD7FF));
509
510 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
511 static_assert(stringend - stringid == end - begin); \
512 if (str >= begin && str <= end) return str + (stringid - begin)
513
514 /* We have some changes in our cargo strings, resulting in some missing. */
515 TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
516 TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
517 if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
518 TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
519 TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
520 TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
521
522 /* Map building names according to our lang file changes. There are several
523 * ranges of house ids, all of which need to be remapped to allow newgrfs
524 * to use original house names. */
525 TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
526 TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
527 TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
528
529 /* Same thing for industries */
530 TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
531 TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
532 TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
533 TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
534 TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
535
536 switch (str) {
537 case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
538 case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
539 case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
540 }
541 #undef TEXTID_TO_STRINGID
542
543 if (str == STR_NULL) return STR_EMPTY;
544
545 Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
546
547 return STR_EMPTY;
548 }
549
557 StringID MapGRFStringID(uint32 grfid, StringID str)
558 {
559 if (IsInsideMM(str, 0xD800, 0x10000)) {
560 /* General text provided by NewGRF.
561 * In the specs this is called the 0xDCxx range (misc persistent texts),
562 * but we meanwhile extended the range to 0xD800-0xFFFF.
563 * Note: We are not involved in the "persistent" business, since we do not store
564 * any NewGRF strings in savegames. */
565 return GetGRFStringID(grfid, str);
566 } else if (IsInsideMM(str, 0xD000, 0xD800)) {
567 /* Callback text provided by NewGRF.
568 * In the specs this is called the 0xD0xx range (misc graphics texts).
569 * These texts can be returned by various callbacks.
570 *
571 * Due to how TTDP implements the GRF-local- to global-textid translation
572 * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
573 * We do not care about that difference and just mask out the 0x400 bit.
574 */
575 str &= ~0x400;
576 return GetGRFStringID(grfid, str);
577 } else {
578 /* The NewGRF wants to include/reference an original TTD string.
579 * Try our best to find an equivalent one. */
580 return TTDPStringIDToOTTDStringIDMapping(str);
581 }
582 }
583
584 static std::map<uint32, uint32> _grf_id_overrides;
585
591 static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
592 {
593 _grf_id_overrides[source_grfid] = target_grfid;
594 grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
595 }
596
605 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access = false)
606 {
607 /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
608 * them use the same engine slots. */
609 uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
610 if (_settings_game.vehicle.dynamic_engines) {
611 /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
612 scope_grfid = file->grfid;
613 uint32 override = _grf_id_overrides[file->grfid];
614 if (override != 0) {
615 scope_grfid = override;
616 const GRFFile *grf_match = GetFileByGRFID(override);
617 if (grf_match == nullptr) {
618 grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
619 } else {
620 grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
621 }
622 }
623
624 /* Check if the engine is registered in the override manager */
625 EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
626 if (engine != INVALID_ENGINE) {
627 Engine *e = Engine::Get(engine);
628 if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
629 return e;
630 }
631 }
632
633 /* Check if there is an unreserved slot */
634 EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
635 if (engine != INVALID_ENGINE) {
636 Engine *e = Engine::Get(engine);
637
638 if (e->grf_prop.grffile == nullptr) {
639 e->grf_prop.grffile = file;
640 grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
641 }
642
643 /* Reserve the engine slot */
644 if (!static_access) {
645 EngineIDMapping *eid = _engine_mngr.data() + engine;
646 eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
647 }
648
649 return e;
650 }
651
652 if (static_access) return nullptr;
653
654 if (!Engine::CanAllocateItem()) {
655 grfmsg(0, "Can't allocate any more engines");
656 return nullptr;
657 }
658
659 size_t engine_pool_size = Engine::GetPoolSize();
660
661 /* ... it's not, so create a new one based off an existing engine */
662 Engine *e = new Engine(type, internal_id);
663 e->grf_prop.grffile = file;
664
665 /* Reserve the engine slot */
666 assert(_engine_mngr.size() == e->index);
667 _engine_mngr.push_back({
668 scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
669 internal_id,
670 type,
671 std::min<uint8>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
672 });
673
674 if (engine_pool_size != Engine::GetPoolSize()) {
675 /* Resize temporary engine data ... */
676 _gted = ReallocT(_gted, Engine::GetPoolSize());
677
678 /* and blank the new block. */
679 size_t len = (Engine::GetPoolSize() - engine_pool_size) * sizeof(*_gted);
680 memset(_gted + engine_pool_size, 0, len);
681 }
682 if (type == VEH_TRAIN) {
683 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
684 }
685
686 grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
687
688 return e;
689 }
690
701 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
702 {
703 uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
704 if (_settings_game.vehicle.dynamic_engines) {
705 scope_grfid = file->grfid;
706 uint32 override = _grf_id_overrides[file->grfid];
707 if (override != 0) scope_grfid = override;
708 }
709
710 return _engine_mngr.GetID(type, internal_id, scope_grfid);
711 }
712
717 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
718 {
719 if (HasBit(grf_sprite->pal, 14)) {
720 ClrBit(grf_sprite->pal, 14);
721 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
722 }
723
724 if (HasBit(grf_sprite->sprite, 14)) {
725 ClrBit(grf_sprite->sprite, 14);
726 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
727 }
728
729 if (HasBit(grf_sprite->sprite, 15)) {
730 ClrBit(grf_sprite->sprite, 15);
731 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
732 }
733 }
734
748 static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16 *max_sprite_offset = nullptr, uint16 *max_palette_offset = nullptr)
749 {
750 grf_sprite->sprite = buf->ReadWord();
751 grf_sprite->pal = buf->ReadWord();
752 TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
753
754 MapSpriteMappingRecolour(grf_sprite);
755
756 bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
757 ClrBit(grf_sprite->pal, 15);
758 if (custom_sprite) {
759 /* Use sprite from Action 1 */
760 uint index = GB(grf_sprite->sprite, 0, 14);
761 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
762 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d", index);
763 grf_sprite->sprite = SPR_IMG_QUERY;
764 grf_sprite->pal = PAL_NONE;
765 } else {
766 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
767 if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
768 SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
769 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
770 }
771 } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
772 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
773 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
774 return flags;
775 }
776
777 if (flags & TLF_CUSTOM_PALETTE) {
778 /* Use palette from Action 1 */
779 uint index = GB(grf_sprite->pal, 0, 14);
780 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
781 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d for 'palette'", index);
782 grf_sprite->pal = PAL_NONE;
783 } else {
784 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
785 if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
786 SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
787 SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
788 }
789 } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
790 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
791 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
792 return flags;
793 }
794
795 return flags;
796 }
797
806 static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
807 {
808 if (!(flags & TLF_DRAWING_FLAGS)) return;
809
810 if (dts->registers == nullptr) dts->AllocateRegisters();
811 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
812 regs.flags = flags & TLF_DRAWING_FLAGS;
813
814 if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
815 if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
816 if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
817
818 if (is_parent) {
819 if (flags & TLF_BB_XY_OFFSET) {
820 regs.delta.parent[0] = buf->ReadByte();
821 regs.delta.parent[1] = buf->ReadByte();
822 }
823 if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
824 } else {
825 if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
826 if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
827 }
828
829 if (flags & TLF_SPRITE_VAR10) {
830 regs.sprite_var10 = buf->ReadByte();
831 if (regs.sprite_var10 > TLR_MAX_VAR10) {
832 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.sprite_var10, TLR_MAX_VAR10);
833 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
834 return;
835 }
836 }
837
838 if (flags & TLF_PALETTE_VAR10) {
839 regs.palette_var10 = buf->ReadByte();
840 if (regs.palette_var10 > TLR_MAX_VAR10) {
841 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.palette_var10, TLR_MAX_VAR10);
842 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
843 return;
844 }
845 }
846 }
847
859 static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
860 {
861 bool has_flags = HasBit(num_building_sprites, 6);
862 ClrBit(num_building_sprites, 6);
863 TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
864 if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
865 dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
866
867 uint16 *max_sprite_offset = AllocaM(uint16, num_building_sprites + 1);
868 uint16 *max_palette_offset = AllocaM(uint16, num_building_sprites + 1);
869 MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
870 MemSetT(max_palette_offset, 0, num_building_sprites + 1);
871
872 /* Groundsprite */
873 TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
874 if (_cur.skip_sprites < 0) return true;
875
876 if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
877 grfmsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x%x for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
878 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
879 return true;
880 }
881
882 ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
883 if (_cur.skip_sprites < 0) return true;
884
885 for (uint i = 0; i < num_building_sprites; i++) {
886 DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
887
888 flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
889 if (_cur.skip_sprites < 0) return true;
890
891 if (flags & ~valid_flags) {
892 grfmsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x%x", flags & ~valid_flags);
893 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
894 return true;
895 }
896
897 seq->delta_x = buf->ReadByte();
898 seq->delta_y = buf->ReadByte();
899
900 if (!no_z_position) seq->delta_z = buf->ReadByte();
901
902 if (seq->IsParentSprite()) {
903 seq->size_x = buf->ReadByte();
904 seq->size_y = buf->ReadByte();
905 seq->size_z = buf->ReadByte();
906 }
907
908 ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
909 if (_cur.skip_sprites < 0) return true;
910 }
911
912 /* Check if the number of sprites per spriteset is consistent */
913 bool is_consistent = true;
914 dts->consistent_max_offset = 0;
915 for (uint i = 0; i < num_building_sprites + 1; i++) {
916 if (max_sprite_offset[i] > 0) {
917 if (dts->consistent_max_offset == 0) {
918 dts->consistent_max_offset = max_sprite_offset[i];
919 } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
920 is_consistent = false;
921 break;
922 }
923 }
924 if (max_palette_offset[i] > 0) {
925 if (dts->consistent_max_offset == 0) {
926 dts->consistent_max_offset = max_palette_offset[i];
927 } else if (dts->consistent_max_offset != max_palette_offset[i]) {
928 is_consistent = false;
929 break;
930 }
931 }
932 }
933
934 /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
935 assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
936
937 if (!is_consistent || dts->registers != nullptr) {
938 dts->consistent_max_offset = 0;
939 if (dts->registers == nullptr) dts->AllocateRegisters();
940
941 for (uint i = 0; i < num_building_sprites + 1; i++) {
942 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
943 regs.max_sprite_offset = max_sprite_offset[i];
944 regs.max_palette_offset = max_palette_offset[i];
945 }
946 }
947
948 return false;
949 }
950
954 static CargoTypes TranslateRefitMask(uint32 refit_mask)
955 {
956 CargoTypes result = 0;
957 for (uint8 bit : SetBitIterator(refit_mask)) {
958 CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
959 if (cargo != CT_INVALID) SetBit(result, cargo);
960 }
961 return result;
962 }
963
971 static void ConvertTTDBasePrice(uint32 base_pointer, const char *error_location, Price *index)
972 {
973 /* Special value for 'none' */
974 if (base_pointer == 0) {
975 *index = INVALID_PRICE;
976 return;
977 }
978
979 static const uint32 start = 0x4B34;
980 static const uint32 size = 6;
981
982 if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
983 grfmsg(1, "%s: Unsupported running cost base 0x%04X, ignoring", error_location, base_pointer);
984 return;
985 }
986
987 *index = (Price)((base_pointer - start) / size);
988 }
989
991 enum ChangeInfoResult {
992 CIR_SUCCESS,
993 CIR_DISABLED,
994 CIR_UNHANDLED,
995 CIR_UNKNOWN,
996 CIR_INVALID_ID,
997 };
998
999 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader *buf);
1000
1008 static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
1009 {
1010 switch (prop) {
1011 case 0x00: // Introduction date
1012 ei->base_intro = buf->ReadWord() + DAYS_TILL_ORIGINAL_BASE_YEAR;
1013 break;
1014
1015 case 0x02: // Decay speed
1016 ei->decay_speed = buf->ReadByte();
1017 break;
1018
1019 case 0x03: // Vehicle life
1020 ei->lifelength = buf->ReadByte();
1021 break;
1022
1023 case 0x04: // Model life
1024 ei->base_life = buf->ReadByte();
1025 break;
1026
1027 case 0x06: // Climates available
1028 ei->climates = buf->ReadByte();
1029 break;
1030
1031 case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1032 /* Amount of cargo loaded during a vehicle's "loading tick" */
1033 ei->load_amount = buf->ReadByte();
1034 break;
1035
1036 default:
1037 return CIR_UNKNOWN;
1038 }
1039
1040 return CIR_SUCCESS;
1041 }
1042
1051 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1052 {
1053 ChangeInfoResult ret = CIR_SUCCESS;
1054
1055 for (int i = 0; i < numinfo; i++) {
1056 Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1057 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1058
1059 EngineInfo *ei = &e->info;
1060 RailVehicleInfo *rvi = &e->u.rail;
1061
1062 switch (prop) {
1063 case 0x05: { // Track type
1064 uint8 tracktype = buf->ReadByte();
1065
1066 if (tracktype < _cur.grffile->railtype_list.size()) {
1067 _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1068 break;
1069 }
1070
1071 switch (tracktype) {
1072 case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_ELECTRIC_LABEL : RAILTYPE_RAIL_LABEL; break;
1073 case 1: _gted[e->index].railtypelabel = RAILTYPE_MONO_LABEL; break;
1074 case 2: _gted[e->index].railtypelabel = RAILTYPE_MAGLEV_LABEL; break;
1075 default:
1076 grfmsg(1, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring", tracktype);
1077 break;
1078 }
1079 break;
1080 }
1081
1082 case 0x08: // AI passenger service
1083 /* Tells the AI that this engine is designed for
1084 * passenger services and shouldn't be used for freight. */
1085 rvi->ai_passenger_only = buf->ReadByte();
1086 break;
1087
1088 case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1089 uint16 speed = buf->ReadWord();
1090 if (speed == 0xFFFF) speed = 0;
1091
1092 rvi->max_speed = speed;
1093 break;
1094 }
1095
1096 case PROP_TRAIN_POWER: // 0x0B Power
1097 rvi->power = buf->ReadWord();
1098
1099 /* Set engine / wagon state based on power */
1100 if (rvi->power != 0) {
1101 if (rvi->railveh_type == RAILVEH_WAGON) {
1102 rvi->railveh_type = RAILVEH_SINGLEHEAD;
1103 }
1104 } else {
1105 rvi->railveh_type = RAILVEH_WAGON;
1106 }
1107 break;
1108
1109 case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1110 rvi->running_cost = buf->ReadByte();
1111 break;
1112
1113 case 0x0E: // Running cost base
1114 ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1115 break;
1116
1117 case 0x12: { // Sprite ID
1118 uint8 spriteid = buf->ReadByte();
1119 uint8 orig_spriteid = spriteid;
1120
1121 /* TTD sprite IDs point to a location in a 16bit array, but we use it
1122 * as an array index, so we need it to be half the original value. */
1123 if (spriteid < 0xFD) spriteid >>= 1;
1124
1125 if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1126 rvi->image_index = spriteid;
1127 } else {
1128 grfmsg(1, "RailVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1129 rvi->image_index = 0;
1130 }
1131 break;
1132 }
1133
1134 case 0x13: { // Dual-headed
1135 uint8 dual = buf->ReadByte();
1136
1137 if (dual != 0) {
1138 rvi->railveh_type = RAILVEH_MULTIHEAD;
1139 } else {
1140 rvi->railveh_type = rvi->power == 0 ?
1141 RAILVEH_WAGON : RAILVEH_SINGLEHEAD;
1142 }
1143 break;
1144 }
1145
1146 case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1147 rvi->capacity = buf->ReadByte();
1148 break;
1149
1150 case 0x15: { // Cargo type
1151 _gted[e->index].defaultcargo_grf = _cur.grffile;
1152 uint8 ctype = buf->ReadByte();
1153
1154 if (ctype == 0xFF) {
1155 /* 0xFF is specified as 'use first refittable' */
1156 ei->cargo_type = CT_INVALID;
1157 } else if (_cur.grffile->grf_version >= 8) {
1158 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1159 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1160 } else if (ctype < NUM_CARGO) {
1161 /* Use untranslated cargo. */
1162 ei->cargo_type = ctype;
1163 } else {
1164 ei->cargo_type = CT_INVALID;
1165 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1166 }
1167 break;
1168 }
1169
1170 case PROP_TRAIN_WEIGHT: // 0x16 Weight
1171 SB(rvi->weight, 0, 8, buf->ReadByte());
1172 break;
1173
1174 case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1175 rvi->cost_factor = buf->ReadByte();
1176 break;
1177
1178 case 0x18: // AI rank
1179 grfmsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1180 buf->ReadByte();
1181 break;
1182
1183 case 0x19: { // Engine traction type
1184 /* What do the individual numbers mean?
1185 * 0x00 .. 0x07: Steam
1186 * 0x08 .. 0x27: Diesel
1187 * 0x28 .. 0x31: Electric
1188 * 0x32 .. 0x37: Monorail
1189 * 0x38 .. 0x41: Maglev
1190 */
1191 uint8 traction = buf->ReadByte();
1192 EngineClass engclass;
1193
1194 if (traction <= 0x07) {
1195 engclass = EC_STEAM;
1196 } else if (traction <= 0x27) {
1197 engclass = EC_DIESEL;
1198 } else if (traction <= 0x31) {
1199 engclass = EC_ELECTRIC;
1200 } else if (traction <= 0x37) {
1201 engclass = EC_MONORAIL;
1202 } else if (traction <= 0x41) {
1203 engclass = EC_MAGLEV;
1204 } else {
1205 break;
1206 }
1207
1208 if (_cur.grffile->railtype_list.size() == 0) {
1209 /* Use traction type to select between normal and electrified
1210 * rail only when no translation list is in place. */
1211 if (_gted[e->index].railtypelabel == RAILTYPE_RAIL_LABEL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_ELECTRIC_LABEL;
1212 if (_gted[e->index].railtypelabel == RAILTYPE_ELECTRIC_LABEL && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_RAIL_LABEL;
1213 }
1214
1215 rvi->engclass = engclass;
1216 break;
1217 }
1218
1219 case 0x1A: // Alter purchase list sort order
1220 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1221 break;
1222
1223 case 0x1B: // Powered wagons power bonus
1224 rvi->pow_wag_power = buf->ReadWord();
1225 break;
1226
1227 case 0x1C: // Refit cost
1228 ei->refit_cost = buf->ReadByte();
1229 break;
1230
1231 case 0x1D: { // Refit cargo
1232 uint32 mask = buf->ReadDWord();
1233 _gted[e->index].UpdateRefittability(mask != 0);
1234 ei->refit_mask = TranslateRefitMask(mask);
1235 _gted[e->index].defaultcargo_grf = _cur.grffile;
1236 break;
1237 }
1238
1239 case 0x1E: // Callback
1240 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1241 break;
1242
1243 case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1244 rvi->tractive_effort = buf->ReadByte();
1245 break;
1246
1247 case 0x20: // Air drag
1248 rvi->air_drag = buf->ReadByte();
1249 break;
1250
1251 case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1252 rvi->shorten_factor = buf->ReadByte();
1253 break;
1254
1255 case 0x22: // Visual effect
1256 rvi->visual_effect = buf->ReadByte();
1257 /* Avoid accidentally setting visual_effect to the default value
1258 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1259 if (rvi->visual_effect == VE_DEFAULT) {
1260 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1261 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1262 }
1263 break;
1264
1265 case 0x23: // Powered wagons weight bonus
1266 rvi->pow_wag_weight = buf->ReadByte();
1267 break;
1268
1269 case 0x24: { // High byte of vehicle weight
1270 byte weight = buf->ReadByte();
1271
1272 if (weight > 4) {
1273 grfmsg(2, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring", weight << 8);
1274 } else {
1275 SB(rvi->weight, 8, 8, weight);
1276 }
1277 break;
1278 }
1279
1280 case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1281 rvi->user_def_data = buf->ReadByte();
1282 break;
1283
1284 case 0x26: // Retire vehicle early
1285 ei->retire_early = buf->ReadByte();
1286 break;
1287
1288 case 0x27: // Miscellaneous flags
1289 ei->misc_flags = buf->ReadByte();
1290 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1291 break;
1292
1293 case 0x28: // Cargo classes allowed
1294 _gted[e->index].cargo_allowed = buf->ReadWord();
1295 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1296 _gted[e->index].defaultcargo_grf = _cur.grffile;
1297 break;
1298
1299 case 0x29: // Cargo classes disallowed
1300 _gted[e->index].cargo_disallowed = buf->ReadWord();
1301 _gted[e->index].UpdateRefittability(false);
1302 break;
1303
1304 case 0x2A: // Long format introduction date (days since year 0)
1305 ei->base_intro = buf->ReadDWord();
1306 break;
1307
1308 case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1309 ei->cargo_age_period = buf->ReadWord();
1310 break;
1311
1312 case 0x2C: // CTT refit include list
1313 case 0x2D: { // CTT refit exclude list
1314 uint8 count = buf->ReadByte();
1315 _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1316 if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1317 CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1318 ctt = 0;
1319 while (count--) {
1320 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1321 if (ctype == CT_INVALID) continue;
1322 SetBit(ctt, ctype);
1323 }
1324 break;
1325 }
1326
1327 case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1328 rvi->curve_speed_mod = buf->ReadWord();
1329 break;
1330
1331 case 0x2F: // Engine variant
1332 ei->variant_id = buf->ReadWord();
1333 break;
1334
1335 case 0x30: // Extra miscellaneous flags
1336 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1337 break;
1338
1339 case 0x31: // Callback additional mask
1340 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1341 break;
1342
1343 default:
1344 ret = CommonVehicleChangeInfo(ei, prop, buf);
1345 break;
1346 }
1347 }
1348
1349 return ret;
1350 }
1351
1360 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1361 {
1362 ChangeInfoResult ret = CIR_SUCCESS;
1363
1364 for (int i = 0; i < numinfo; i++) {
1365 Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1366 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1367
1368 EngineInfo *ei = &e->info;
1369 RoadVehicleInfo *rvi = &e->u.road;
1370
1371 switch (prop) {
1372 case 0x05: // Road/tram type
1373 /* RoadTypeLabel is looked up later after the engine's road/tram
1374 * flag is set, however 0 means the value has not been set. */
1375 _gted[e->index].roadtramtype = buf->ReadByte() + 1;
1376 break;
1377
1378 case 0x08: // Speed (1 unit is 0.5 kmh)
1379 rvi->max_speed = buf->ReadByte();
1380 break;
1381
1382 case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1383 rvi->running_cost = buf->ReadByte();
1384 break;
1385
1386 case 0x0A: // Running cost base
1387 ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1388 break;
1389
1390 case 0x0E: { // Sprite ID
1391 uint8 spriteid = buf->ReadByte();
1392 uint8 orig_spriteid = spriteid;
1393
1394 /* cars have different custom id in the GRF file */
1395 if (spriteid == 0xFF) spriteid = 0xFD;
1396
1397 if (spriteid < 0xFD) spriteid >>= 1;
1398
1399 if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1400 rvi->image_index = spriteid;
1401 } else {
1402 grfmsg(1, "RoadVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1403 rvi->image_index = 0;
1404 }
1405 break;
1406 }
1407
1408 case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1409 rvi->capacity = buf->ReadByte();
1410 break;
1411
1412 case 0x10: { // Cargo type
1413 _gted[e->index].defaultcargo_grf = _cur.grffile;
1414 uint8 ctype = buf->ReadByte();
1415
1416 if (ctype == 0xFF) {
1417 /* 0xFF is specified as 'use first refittable' */
1418 ei->cargo_type = CT_INVALID;
1419 } else if (_cur.grffile->grf_version >= 8) {
1420 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1421 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1422 } else if (ctype < NUM_CARGO) {
1423 /* Use untranslated cargo. */
1424 ei->cargo_type = ctype;
1425 } else {
1426 ei->cargo_type = CT_INVALID;
1427 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1428 }
1429 break;
1430 }
1431
1432 case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1433 rvi->cost_factor = buf->ReadByte();
1434 break;
1435
1436 case 0x12: // SFX
1437 rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1438 break;
1439
1440 case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1441 rvi->power = buf->ReadByte();
1442 break;
1443
1444 case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1445 rvi->weight = buf->ReadByte();
1446 break;
1447
1448 case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1449 _gted[e->index].rv_max_speed = buf->ReadByte();
1450 break;
1451
1452 case 0x16: { // Cargoes available for refitting
1453 uint32 mask = buf->ReadDWord();
1454 _gted[e->index].UpdateRefittability(mask != 0);
1455 ei->refit_mask = TranslateRefitMask(mask);
1456 _gted[e->index].defaultcargo_grf = _cur.grffile;
1457 break;
1458 }
1459
1460 case 0x17: // Callback mask
1461 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1462 break;
1463
1464 case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1465 rvi->tractive_effort = buf->ReadByte();
1466 break;
1467
1468 case 0x19: // Air drag
1469 rvi->air_drag = buf->ReadByte();
1470 break;
1471
1472 case 0x1A: // Refit cost
1473 ei->refit_cost = buf->ReadByte();
1474 break;
1475
1476 case 0x1B: // Retire vehicle early
1477 ei->retire_early = buf->ReadByte();
1478 break;
1479
1480 case 0x1C: // Miscellaneous flags
1481 ei->misc_flags = buf->ReadByte();
1482 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1483 break;
1484
1485 case 0x1D: // Cargo classes allowed
1486 _gted[e->index].cargo_allowed = buf->ReadWord();
1487 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1488 _gted[e->index].defaultcargo_grf = _cur.grffile;
1489 break;
1490
1491 case 0x1E: // Cargo classes disallowed
1492 _gted[e->index].cargo_disallowed = buf->ReadWord();
1493 _gted[e->index].UpdateRefittability(false);
1494 break;
1495
1496 case 0x1F: // Long format introduction date (days since year 0)
1497 ei->base_intro = buf->ReadDWord();
1498 break;
1499
1500 case 0x20: // Alter purchase list sort order
1501 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1502 break;
1503
1504 case 0x21: // Visual effect
1505 rvi->visual_effect = buf->ReadByte();
1506 /* Avoid accidentally setting visual_effect to the default value
1507 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1508 if (rvi->visual_effect == VE_DEFAULT) {
1509 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1510 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1511 }
1512 break;
1513
1514 case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1515 ei->cargo_age_period = buf->ReadWord();
1516 break;
1517
1518 case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1519 rvi->shorten_factor = buf->ReadByte();
1520 break;
1521
1522 case 0x24: // CTT refit include list
1523 case 0x25: { // CTT refit exclude list
1524 uint8 count = buf->ReadByte();
1525 _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1526 if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1527 CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1528 ctt = 0;
1529 while (count--) {
1530 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1531 if (ctype == CT_INVALID) continue;
1532 SetBit(ctt, ctype);
1533 }
1534 break;
1535 }
1536
1537 case 0x26: // Engine variant
1538 ei->variant_id = buf->ReadWord();
1539 break;
1540
1541 case 0x27: // Extra miscellaneous flags
1542 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1543 break;
1544
1545 case 0x28: // Callback additional mask
1546 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1547 break;
1548
1549 default:
1550 ret = CommonVehicleChangeInfo(ei, prop, buf);
1551 break;
1552 }
1553 }
1554
1555 return ret;
1556 }
1557
1566 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1567 {
1568 ChangeInfoResult ret = CIR_SUCCESS;
1569
1570 for (int i = 0; i < numinfo; i++) {
1571 Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1572 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1573
1574 EngineInfo *ei = &e->info;
1575 ShipVehicleInfo *svi = &e->u.ship;
1576
1577 switch (prop) {
1578 case 0x08: { // Sprite ID
1579 uint8 spriteid = buf->ReadByte();
1580 uint8 orig_spriteid = spriteid;
1581
1582 /* ships have different custom id in the GRF file */
1583 if (spriteid == 0xFF) spriteid = 0xFD;
1584
1585 if (spriteid < 0xFD) spriteid >>= 1;
1586
1587 if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1588 svi->image_index = spriteid;
1589 } else {
1590 grfmsg(1, "ShipVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1591 svi->image_index = 0;
1592 }
1593 break;
1594 }
1595
1596 case 0x09: // Refittable
1597 svi->old_refittable = (buf->ReadByte() != 0);
1598 break;
1599
1600 case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1601 svi->cost_factor = buf->ReadByte();
1602 break;
1603
1604 case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h)
1605 svi->max_speed = buf->ReadByte();
1606 break;
1607
1608 case 0x0C: { // Cargo type
1609 _gted[e->index].defaultcargo_grf = _cur.grffile;
1610 uint8 ctype = buf->ReadByte();
1611
1612 if (ctype == 0xFF) {
1613 /* 0xFF is specified as 'use first refittable' */
1614 ei->cargo_type = CT_INVALID;
1615 } else if (_cur.grffile->grf_version >= 8) {
1616 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1617 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1618 } else if (ctype < NUM_CARGO) {
1619 /* Use untranslated cargo. */
1620 ei->cargo_type = ctype;
1621 } else {
1622 ei->cargo_type = CT_INVALID;
1623 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1624 }
1625 break;
1626 }
1627
1628 case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1629 svi->capacity = buf->ReadWord();
1630 break;
1631
1632 case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1633 svi->running_cost = buf->ReadByte();
1634 break;
1635
1636 case 0x10: // SFX
1637 svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1638 break;
1639
1640 case 0x11: { // Cargoes available for refitting
1641 uint32 mask = buf->ReadDWord();
1642 _gted[e->index].UpdateRefittability(mask != 0);
1643 ei->refit_mask = TranslateRefitMask(mask);
1644 _gted[e->index].defaultcargo_grf = _cur.grffile;
1645 break;
1646 }
1647
1648 case 0x12: // Callback mask
1649 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1650 break;
1651
1652 case 0x13: // Refit cost
1653 ei->refit_cost = buf->ReadByte();
1654 break;
1655
1656 case 0x14: // Ocean speed fraction
1657 svi->ocean_speed_frac = buf->ReadByte();
1658 break;
1659
1660 case 0x15: // Canal speed fraction
1661 svi->canal_speed_frac = buf->ReadByte();
1662 break;
1663
1664 case 0x16: // Retire vehicle early
1665 ei->retire_early = buf->ReadByte();
1666 break;
1667
1668 case 0x17: // Miscellaneous flags
1669 ei->misc_flags = buf->ReadByte();
1670 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1671 break;
1672
1673 case 0x18: // Cargo classes allowed
1674 _gted[e->index].cargo_allowed = buf->ReadWord();
1675 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1676 _gted[e->index].defaultcargo_grf = _cur.grffile;
1677 break;
1678
1679 case 0x19: // Cargo classes disallowed
1680 _gted[e->index].cargo_disallowed = buf->ReadWord();
1681 _gted[e->index].UpdateRefittability(false);
1682 break;
1683
1684 case 0x1A: // Long format introduction date (days since year 0)
1685 ei->base_intro = buf->ReadDWord();
1686 break;
1687
1688 case 0x1B: // Alter purchase list sort order
1689 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1690 break;
1691
1692 case 0x1C: // Visual effect
1693 svi->visual_effect = buf->ReadByte();
1694 /* Avoid accidentally setting visual_effect to the default value
1695 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1696 if (svi->visual_effect == VE_DEFAULT) {
1697 assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1698 SB(svi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1699 }
1700 break;
1701
1702 case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1703 ei->cargo_age_period = buf->ReadWord();
1704 break;
1705
1706 case 0x1E: // CTT refit include list
1707 case 0x1F: { // CTT refit exclude list
1708 uint8 count = buf->ReadByte();
1709 _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1710 if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1711 CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1712 ctt = 0;
1713 while (count--) {
1714 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1715 if (ctype == CT_INVALID) continue;
1716 SetBit(ctt, ctype);
1717 }
1718 break;
1719 }
1720
1721 case 0x20: // Engine variant
1722 ei->variant_id = buf->ReadWord();
1723 break;
1724
1725 case 0x21: // Extra miscellaneous flags
1726 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1727 break;
1728
1729 case 0x22: // Callback additional mask
1730 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1731 break;
1732
1733 default:
1734 ret = CommonVehicleChangeInfo(ei, prop, buf);
1735 break;
1736 }
1737 }
1738
1739 return ret;
1740 }
1741
1750 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1751 {
1752 ChangeInfoResult ret = CIR_SUCCESS;
1753
1754 for (int i = 0; i < numinfo; i++) {
1755 Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1756 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1757
1758 EngineInfo *ei = &e->info;
1759 AircraftVehicleInfo *avi = &e->u.air;
1760
1761 switch (prop) {
1762 case 0x08: { // Sprite ID
1763 uint8 spriteid = buf->ReadByte();
1764 uint8 orig_spriteid = spriteid;
1765
1766 /* aircraft have different custom id in the GRF file */
1767 if (spriteid == 0xFF) spriteid = 0xFD;
1768
1769 if (spriteid < 0xFD) spriteid >>= 1;
1770
1771 if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1772 avi->image_index = spriteid;
1773 } else {
1774 grfmsg(1, "AircraftVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1775 avi->image_index = 0;
1776 }
1777 break;
1778 }
1779
1780 case 0x09: // Helicopter
1781 if (buf->ReadByte() == 0) {
1782 avi->subtype = AIR_HELI;
1783 } else {
1784 SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1785 }
1786 break;
1787
1788 case 0x0A: // Large
1789 SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1790 break;
1791
1792 case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1793 avi->cost_factor = buf->ReadByte();
1794 break;
1795
1796 case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1797 avi->max_speed = (buf->ReadByte() * 128) / 10;
1798 break;
1799
1800 case 0x0D: // Acceleration
1801 avi->acceleration = buf->ReadByte();
1802 break;
1803
1804 case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1805 avi->running_cost = buf->ReadByte();
1806 break;
1807
1808 case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1809 avi->passenger_capacity = buf->ReadWord();
1810 break;
1811
1812 case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1813 avi->mail_capacity = buf->ReadByte();
1814 break;
1815
1816 case 0x12: // SFX
1817 avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1818 break;
1819
1820 case 0x13: { // Cargoes available for refitting
1821 uint32 mask = buf->ReadDWord();
1822 _gted[e->index].UpdateRefittability(mask != 0);
1823 ei->refit_mask = TranslateRefitMask(mask);
1824 _gted[e->index].defaultcargo_grf = _cur.grffile;
1825 break;
1826 }
1827
1828 case 0x14: // Callback mask
1829 SB(ei->callback_mask, 0, 8, buf->ReadByte());
1830 break;
1831
1832 case 0x15: // Refit cost
1833 ei->refit_cost = buf->ReadByte();
1834 break;
1835
1836 case 0x16: // Retire vehicle early
1837 ei->retire_early = buf->ReadByte();
1838 break;
1839
1840 case 0x17: // Miscellaneous flags
1841 ei->misc_flags = buf->ReadByte();
1842 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1843 break;
1844
1845 case 0x18: // Cargo classes allowed
1846 _gted[e->index].cargo_allowed = buf->ReadWord();
1847 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1848 _gted[e->index].defaultcargo_grf = _cur.grffile;
1849 break;
1850
1851 case 0x19: // Cargo classes disallowed
1852 _gted[e->index].cargo_disallowed = buf->ReadWord();
1853 _gted[e->index].UpdateRefittability(false);
1854 break;
1855
1856 case 0x1A: // Long format introduction date (days since year 0)
1857 ei->base_intro = buf->ReadDWord();
1858 break;
1859
1860 case 0x1B: // Alter purchase list sort order
1861 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1862 break;
1863
1864 case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1865 ei->cargo_age_period = buf->ReadWord();
1866 break;
1867
1868 case 0x1D: // CTT refit include list
1869 case 0x1E: { // CTT refit exclude list
1870 uint8 count = buf->ReadByte();
1871 _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1872 if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1873 CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1874 ctt = 0;
1875 while (count--) {
1876 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1877 if (ctype == CT_INVALID) continue;
1878 SetBit(ctt, ctype);
1879 }
1880 break;
1881 }
1882
1883 case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1884 avi->max_range = buf->ReadWord();
1885 break;
1886
1887 case 0x20: // Engine variant
1888 ei->variant_id = buf->ReadWord();
1889 break;
1890
1891 case 0x21: // Extra miscellaneous flags
1892 ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1893 break;
1894
1895 case 0x22: // Callback additional mask
1896 SB(ei->callback_mask, 8, 8, buf->ReadByte());
1897 break;
1898
1899 default:
1900 ret = CommonVehicleChangeInfo(ei, prop, buf);
1901 break;
1902 }
1903 }
1904
1905 return ret;
1906 }
1907
1916 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
1917 {
1918 ChangeInfoResult ret = CIR_SUCCESS;
1919
1920 if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1921 grfmsg(1, "StationChangeInfo: Station %u is invalid, max %u, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1922 return CIR_INVALID_ID;
1923 }
1924
1925 /* Allocate station specs if necessary */
1926 if (_cur.grffile->stations == nullptr) _cur.grffile->stations = CallocT<StationSpec*>(NUM_STATIONS_PER_GRF);
1927
1928 for (int i = 0; i < numinfo; i++) {
1929 StationSpec *statspec = _cur.grffile->stations[stid + i];
1930
1931 /* Check that the station we are modifying is defined. */
1932 if (statspec == nullptr && prop != 0x08) {
1933 grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
1934 return CIR_INVALID_ID;
1935 }
1936
1937 switch (prop) {
1938 case 0x08: { // Class ID
1939 StationSpec **spec = &_cur.grffile->stations[stid + i];
1940
1941 /* Property 0x08 is special; it is where the station is allocated */
1942 if (*spec == nullptr) *spec = new StationSpec();
1943
1944 /* Swap classid because we read it in BE meaning WAYP or DFLT */
1945 uint32 classid = buf->ReadDWord();
1946 (*spec)->cls_id = StationClass::Allocate(BSWAP32(classid));
1947 break;
1948 }
1949
1950 case 0x09: { // Define sprite layout
1951 uint16 tiles = buf->ReadExtendedByte();
1952 statspec->renderdata.clear(); // delete earlier loaded stuff
1953 statspec->renderdata.reserve(tiles);
1954
1955 for (uint t = 0; t < tiles; t++) {
1956 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1957 dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1958
1959 if (buf->HasData(4) && *(uint32*)buf->Data() == 0) {
1960 buf->Skip(4);
1961 extern const DrawTileSprites _station_display_datas_rail[8];
1962 dts->Clone(&_station_display_datas_rail[t % 8]);
1963 continue;
1964 }
1965
1966 ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1967 /* On error, bail out immediately. Temporary GRF data was already freed */
1968 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1969
1970 static std::vector<DrawTileSeqStruct> tmp_layout;
1971 tmp_layout.clear();
1972 for (;;) {
1973 /* no relative bounding box support */
1974 DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1975 MemSetT(&dtss, 0);
1976
1977 dtss.delta_x = buf->ReadByte();
1978 if (dtss.IsTerminator()) break;
1979 dtss.delta_y = buf->ReadByte();
1980 dtss.delta_z = buf->ReadByte();
1981 dtss.size_x = buf->ReadByte();
1982 dtss.size_y = buf->ReadByte();
1983 dtss.size_z = buf->ReadByte();
1984
1985 ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1986 /* On error, bail out immediately. Temporary GRF data was already freed */
1987 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1988 }
1989 dts->Clone(tmp_layout.data());
1990 }
1991
1992 /* Number of layouts must be even, alternating X and Y */
1993 if (statspec->renderdata.size() & 1) {
1994 grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
1995 statspec->renderdata.pop_back();
1996 }
1997 break;
1998 }
1999
2000 case 0x0A: { // Copy sprite layout
2001 byte srcid = buf->ReadByte();
2002 const StationSpec *srcstatspec = srcid >= NUM_STATIONS_PER_GRF ? nullptr : _cur.grffile->stations[srcid];
2003
2004 if (srcstatspec == nullptr) {
2005 grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy sprite layout to %u.", srcid, stid + i);
2006 continue;
2007 }
2008
2009 statspec->renderdata.clear(); // delete earlier loaded stuff
2010 statspec->renderdata.reserve(srcstatspec->renderdata.size());
2011
2012 for (const auto &it : srcstatspec->renderdata) {
2013 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2014 dts->Clone(&it);
2015 }
2016 break;
2017 }
2018
2019 case 0x0B: // Callback mask
2020 statspec->callback_mask = buf->ReadByte();
2021 break;
2022
2023 case 0x0C: // Disallowed number of platforms
2024 statspec->disallowed_platforms = buf->ReadByte();
2025 break;
2026
2027 case 0x0D: // Disallowed platform lengths
2028 statspec->disallowed_lengths = buf->ReadByte();
2029 break;
2030
2031 case 0x0E: // Define custom layout
2032 while (buf->HasData()) {
2033 byte length = buf->ReadByte();
2034 byte number = buf->ReadByte();
2035
2036 if (length == 0 || number == 0) break;
2037
2038 if (statspec->layouts.size() < length) statspec->layouts.resize(length);
2039 if (statspec->layouts[length - 1].size() < number) statspec->layouts[length - 1].resize(number);
2040
2041 const byte *layout = buf->ReadBytes(length * number);
2042 statspec->layouts[length - 1][number - 1].assign(layout, layout + length * number);
2043
2044 /* Validate tile values are only the permitted 00, 02, 04 and 06. */
2045 for (auto &tile : statspec->layouts[length - 1][number - 1]) {
2046 if ((tile & 6) != tile) {
2047 grfmsg(1, "StationChangeInfo: Invalid tile %u in layout %ux%u", tile, length, number);
2048 tile &= 6;
2049 }
2050 }
2051 }
2052 break;
2053
2054 case 0x0F: { // Copy custom layout
2055 byte srcid = buf->ReadByte();
2056 const StationSpec *srcstatspec = srcid >= NUM_STATIONS_PER_GRF ? nullptr : _cur.grffile->stations[srcid];
2057
2058 if (srcstatspec == nullptr) {
2059 grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy tile layout to %u.", srcid, stid + i);
2060 continue;
2061 }
2062
2063 statspec->layouts = srcstatspec->layouts;
2064 break;
2065 }
2066
2067 case 0x10: // Little/lots cargo threshold
2068 statspec->cargo_threshold = buf->ReadWord();
2069 break;
2070
2071 case 0x11: // Pylon placement
2072 statspec->pylons = buf->ReadByte();
2073 break;
2074
2075 case 0x12: // Cargo types for random triggers
2076 if (_cur.grffile->grf_version >= 7) {
2077 statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
2078 } else {
2079 statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
2080 }
2081 break;
2082
2083 case 0x13: // General flags
2084 statspec->flags = buf->ReadByte();
2085 break;
2086
2087 case 0x14: // Overhead wire placement
2088 statspec->wires = buf->ReadByte();
2089 break;
2090
2091 case 0x15: // Blocked tiles
2092 statspec->blocked = buf->ReadByte();
2093 break;
2094
2095 case 0x16: // Animation info
2096 statspec->animation.frames = buf->ReadByte();
2097 statspec->animation.status = buf->ReadByte();
2098 break;
2099
2100 case 0x17: // Animation speed
2101 statspec->animation.speed = buf->ReadByte();
2102 break;
2103
2104 case 0x18: // Animation triggers
2105 statspec->animation.triggers = buf->ReadWord();
2106 break;
2107
2108 case 0x1A: { // Advanced sprite layout
2109 uint16 tiles = buf->ReadExtendedByte();
2110 statspec->renderdata.clear(); // delete earlier loaded stuff
2111 statspec->renderdata.reserve(tiles);
2112
2113 for (uint t = 0; t < tiles; t++) {
2114 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2115 uint num_building_sprites = buf->ReadByte();
2116 /* On error, bail out immediately. Temporary GRF data was already freed */
2117 if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2118 }
2119
2120 /* Number of layouts must be even, alternating X and Y */
2121 if (statspec->renderdata.size() & 1) {
2122 grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
2123 statspec->renderdata.pop_back();
2124 }
2125 break;
2126 }
2127
2128 default:
2129 ret = CIR_UNKNOWN;
2130 break;
2131 }
2132 }
2133
2134 return ret;
2135 }
2136
2145 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
2146 {
2147 ChangeInfoResult ret = CIR_SUCCESS;
2148
2149 if (id + numinfo > CF_END) {
2150 grfmsg(1, "CanalChangeInfo: Canal feature 0x%02X is invalid, max %u, ignoring", id + numinfo, CF_END);
2151 return CIR_INVALID_ID;
2152 }
2153
2154 for (int i = 0; i < numinfo; i++) {
2155 CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2156
2157 switch (prop) {
2158 case 0x08:
2159 cp->callback_mask = buf->ReadByte();
2160 break;
2161
2162 case 0x09:
2163 cp->flags = buf->ReadByte();
2164 break;
2165
2166 default:
2167 ret = CIR_UNKNOWN;
2168 break;
2169 }
2170 }
2171
2172 return ret;
2173 }
2174
2183 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
2184 {
2185 ChangeInfoResult ret = CIR_SUCCESS;
2186
2187 if (brid + numinfo > MAX_BRIDGES) {
2188 grfmsg(1, "BridgeChangeInfo: Bridge %u is invalid, max %u, ignoring", brid + numinfo, MAX_BRIDGES);
2189 return CIR_INVALID_ID;
2190 }
2191
2192 for (int i = 0; i < numinfo; i++) {
2193 BridgeSpec *bridge = &_bridge[brid + i];
2194
2195 switch (prop) {
2196 case 0x08: { // Year of availability
2197 /* We treat '0' as always available */
2198 byte year = buf->ReadByte();
2199 bridge->avail_year = (year > 0 ? ORIGINAL_BASE_YEAR + year : 0);
2200 break;
2201 }
2202
2203 case 0x09: // Minimum length
2204 bridge->min_length = buf->ReadByte();
2205 break;
2206
2207 case 0x0A: // Maximum length
2208 bridge->max_length = buf->ReadByte();
2209 if (bridge->max_length > 16) bridge->max_length = UINT16_MAX;
2210 break;
2211
2212 case 0x0B: // Cost factor
2213 bridge->price = buf->ReadByte();
2214 break;
2215
2216 case 0x0C: // Maximum speed
2217 bridge->speed = buf->ReadWord();
2218 if (bridge->speed == 0) bridge->speed = UINT16_MAX;
2219 break;
2220
2221 case 0x0D: { // Bridge sprite tables
2222 byte tableid = buf->ReadByte();
2223 byte numtables = buf->ReadByte();
2224
2225 if (bridge->sprite_table == nullptr) {
2226 /* Allocate memory for sprite table pointers and zero out */
2227 bridge->sprite_table = CallocT<PalSpriteID*>(7);
2228 }
2229
2230 for (; numtables-- != 0; tableid++) {
2231 if (tableid >= 7) { // skip invalid data
2232 grfmsg(1, "BridgeChangeInfo: Table %d >= 7, skipping", tableid);
2233 for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
2234 continue;
2235 }
2236
2237 if (bridge->sprite_table[tableid] == nullptr) {
2238 bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2239 }
2240
2241 for (byte sprite = 0; sprite < 32; sprite++) {
2242 SpriteID image = buf->ReadWord();
2243 PaletteID pal = buf->ReadWord();
2244
2245 bridge->sprite_table[tableid][sprite].sprite = image;
2246 bridge->sprite_table[tableid][sprite].pal = pal;
2247
2248 MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2249 }
2250 }
2251 break;
2252 }
2253
2254 case 0x0E: // Flags; bit 0 - disable far pillars
2255 bridge->flags = buf->ReadByte();
2256 break;
2257
2258 case 0x0F: // Long format year of availability (year since year 0)
2259 bridge->avail_year = Clamp(buf->ReadDWord(), MIN_YEAR, MAX_YEAR);
2260 break;
2261
2262 case 0x10: { // purchase string
2263 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2264 if (newone != STR_UNDEFINED) bridge->material = newone;
2265 break;
2266 }
2267
2268 case 0x11: // description of bridge with rails or roads
2269 case 0x12: {
2270 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2271 if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2272 break;
2273 }
2274
2275 case 0x13: // 16 bits cost multiplier
2276 bridge->price = buf->ReadWord();
2277 break;
2278
2279 default:
2280 ret = CIR_UNKNOWN;
2281 break;
2282 }
2283 }
2284
2285 return ret;
2286 }
2287
2294 static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
2295 {
2296 ChangeInfoResult ret = CIR_SUCCESS;
2297
2298 switch (prop) {
2299 case 0x09:
2300 case 0x0B:
2301 case 0x0C:
2302 case 0x0D:
2303 case 0x0E:
2304 case 0x0F:
2305 case 0x11:
2306 case 0x14:
2307 case 0x15:
2308 case 0x16:
2309 case 0x18:
2310 case 0x19:
2311 case 0x1A:
2312 case 0x1B:
2313 case 0x1C:
2314 case 0x1D:
2315 case 0x1F:
2316 buf->ReadByte();
2317 break;
2318
2319 case 0x0A:
2320 case 0x10:
2321 case 0x12:
2322 case 0x13:
2323 case 0x21:
2324 case 0x22:
2325 buf->ReadWord();
2326 break;
2327
2328 case 0x1E:
2329 buf->ReadDWord();
2330 break;
2331
2332 case 0x17:
2333 for (uint j = 0; j < 4; j++) buf->ReadByte();
2334 break;
2335
2336 case 0x20: {
2337 byte count = buf->ReadByte();
2338 for (byte j = 0; j < count; j++) buf->ReadByte();
2339 break;
2340 }
2341
2342 case 0x23:
2343 buf->Skip(buf->ReadByte() * 2);
2344 break;
2345
2346 default:
2347 ret = CIR_UNKNOWN;
2348 break;
2349 }
2350 return ret;
2351 }
2352
2361 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
2362 {
2363 ChangeInfoResult ret = CIR_SUCCESS;
2364
2365 if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2366 grfmsg(1, "TownHouseChangeInfo: Too many houses loaded (%u), max (%u). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2367 return CIR_INVALID_ID;
2368 }
2369
2370 /* Allocate house specs if they haven't been allocated already. */
2371 if (_cur.grffile->housespec == nullptr) {
2372 _cur.grffile->housespec = CallocT<HouseSpec*>(NUM_HOUSES_PER_GRF);
2373 }
2374
2375 for (int i = 0; i < numinfo; i++) {
2376 HouseSpec *housespec = _cur.grffile->housespec[hid + i];
2377
2378 if (prop != 0x08 && housespec == nullptr) {
2379 /* If the house property 08 is not yet set, ignore this property */
2380 ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2381 if (cir > ret) ret = cir;
2382 continue;
2383 }
2384
2385 switch (prop) {
2386 case 0x08: { // Substitute building type, and definition of a new house
2387 HouseSpec **house = &_cur.grffile->housespec[hid + i];
2388 byte subs_id = buf->ReadByte();
2389
2390 if (subs_id == 0xFF) {
2391 /* Instead of defining a new house, a substitute house id
2392 * of 0xFF disables the old house with the current id. */
2393 HouseSpec::Get(hid + i)->enabled = false;
2394 continue;
2395 } else if (subs_id >= NEW_HOUSE_OFFSET) {
2396 /* The substitute id must be one of the original houses. */
2397 grfmsg(2, "TownHouseChangeInfo: Attempt to use new house %u as substitute house for %u. Ignoring.", subs_id, hid + i);
2398 continue;
2399 }
2400
2401 /* Allocate space for this house. */
2402 if (*house == nullptr) *house = CallocT<HouseSpec>(1);
2403
2404 housespec = *house;
2405
2406 MemCpyT(housespec, HouseSpec::Get(subs_id));
2407
2408 housespec->enabled = true;
2409 housespec->grf_prop.local_id = hid + i;
2410 housespec->grf_prop.subst_id = subs_id;
2411 housespec->grf_prop.grffile = _cur.grffile;
2412 housespec->random_colour[0] = 0x04; // those 4 random colours are the base colour
2413 housespec->random_colour[1] = 0x08; // for all new houses
2414 housespec->random_colour[2] = 0x0C; // they stand for red, blue, orange and green
2415 housespec->random_colour[3] = 0x06;
2416
2417 /* Make sure that the third cargo type is valid in this
2418 * climate. This can cause problems when copying the properties
2419 * of a house that accepts food, where the new house is valid
2420 * in the temperate climate. */
2421 if (!CargoSpec::Get(housespec->accepts_cargo[2])->IsValid()) {
2422 housespec->cargo_acceptance[2] = 0;
2423 }
2424 break;
2425 }
2426
2427 case 0x09: // Building flags
2428 housespec->building_flags = (BuildingFlags)buf->ReadByte();
2429 break;
2430
2431 case 0x0A: { // Availability years
2432 uint16 years = buf->ReadWord();
2433 housespec->min_year = GB(years, 0, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2434 housespec->max_year = GB(years, 8, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2435 break;
2436 }
2437
2438 case 0x0B: // Population
2439 housespec->population = buf->ReadByte();
2440 break;
2441
2442 case 0x0C: // Mail generation multiplier
2443 housespec->mail_generation = buf->ReadByte();
2444 break;
2445
2446 case 0x0D: // Passenger acceptance
2447 case 0x0E: // Mail acceptance
2448 housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
2449 break;
2450
2451 case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2452 int8 goods = buf->ReadByte();
2453
2454 /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2455 * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2456 CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_CANDY : CT_GOODS) :
2457 ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_FIZZY_DRINKS : CT_FOOD);
2458
2459 /* Make sure the cargo type is valid in this climate. */
2460 if (!CargoSpec::Get(cid)->IsValid()) goods = 0;
2461
2462 housespec->accepts_cargo[2] = cid;
2463 housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2464 break;
2465 }
2466
2467 case 0x10: // Local authority rating decrease on removal
2468 housespec->remove_rating_decrease = buf->ReadWord();
2469 break;
2470
2471 case 0x11: // Removal cost multiplier
2472 housespec->removal_cost = buf->ReadByte();
2473 break;
2474
2475 case 0x12: // Building name ID
2476 AddStringForMapping(buf->ReadWord(), &housespec->building_name);
2477 break;
2478
2479 case 0x13: // Building availability mask
2480 housespec->building_availability = (HouseZones)buf->ReadWord();
2481 break;
2482
2483 case 0x14: // House callback mask
2484 housespec->callback_mask |= buf->ReadByte();
2485 break;
2486
2487 case 0x15: { // House override byte
2488 byte override = buf->ReadByte();
2489
2490 /* The house being overridden must be an original house. */
2491 if (override >= NEW_HOUSE_OFFSET) {
2492 grfmsg(2, "TownHouseChangeInfo: Attempt to override new house %u with house id %u. Ignoring.", override, hid + i);
2493 continue;
2494 }
2495
2496 _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2497 break;
2498 }
2499
2500 case 0x16: // Periodic refresh multiplier
2501 housespec->processing_time = std::min<byte>(buf->ReadByte(), 63u);
2502 break;
2503
2504 case 0x17: // Four random colours to use
2505 for (uint j = 0; j < 4; j++) housespec->random_colour[j] = buf->ReadByte();
2506 break;
2507
2508 case 0x18: // Relative probability of appearing
2509 housespec->probability = buf->ReadByte();
2510 break;
2511
2512 case 0x19: // Extra flags
2513 housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
2514 break;
2515
2516 case 0x1A: // Animation frames
2517 housespec->animation.frames = buf->ReadByte();
2518 housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2519 SB(housespec->animation.frames, 7, 1, 0);
2520 break;
2521
2522 case 0x1B: // Animation speed
2523 housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
2524 break;
2525
2526 case 0x1C: // Class of the building type
2527 housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
2528 break;
2529
2530 case 0x1D: // Callback mask part 2
2531 housespec->callback_mask |= (buf->ReadByte() << 8);
2532 break;
2533
2534 case 0x1E: { // Accepted cargo types
2535 uint32 cargotypes = buf->ReadDWord();
2536
2537 /* Check if the cargo types should not be changed */
2538 if (cargotypes == 0xFFFFFFFF) break;
2539
2540 for (uint j = 0; j < 3; j++) {
2541 /* Get the cargo number from the 'list' */
2542 uint8 cargo_part = GB(cargotypes, 8 * j, 8);
2543 CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2544
2545 if (cargo == CT_INVALID) {
2546 /* Disable acceptance of invalid cargo type */
2547 housespec->cargo_acceptance[j] = 0;
2548 } else {
2549 housespec->accepts_cargo[j] = cargo;
2550 }
2551 }
2552 break;
2553 }
2554
2555 case 0x1F: // Minimum life span
2556 housespec->minimum_life = buf->ReadByte();
2557 break;
2558
2559 case 0x20: { // Cargo acceptance watch list
2560 byte count = buf->ReadByte();
2561 for (byte j = 0; j < count; j++) {
2562 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2563 if (cargo != CT_INVALID) SetBit(housespec->watched_cargoes, cargo);
2564 }
2565 break;
2566 }
2567
2568 case 0x21: // long introduction year
2569 housespec->min_year = buf->ReadWord();
2570 break;
2571
2572 case 0x22: // long maximum year
2573 housespec->max_year = buf->ReadWord();
2574 break;
2575
2576 case 0x23: { // variable length cargo types accepted
2577 uint count = buf->ReadByte();
2578 if (count > lengthof(housespec->accepts_cargo)) {
2579 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2580 error->param_value[1] = prop;
2581 return CIR_DISABLED;
2582 }
2583 /* Always write the full accepts_cargo array, and check each index for being inside the
2584 * provided data. This ensures all values are properly initialized, and also avoids
2585 * any risks of array overrun. */
2586 for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2587 if (i < count) {
2588 housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2589 housespec->cargo_acceptance[i] = buf->ReadByte();
2590 } else {
2591 housespec->accepts_cargo[i] = CT_INVALID;
2592 housespec->cargo_acceptance[i] = 0;
2593 }
2594 }
2595 break;
2596 }
2597
2598 default:
2599 ret = CIR_UNKNOWN;
2600 break;
2601 }
2602 }
2603
2604 return ret;
2605 }
2606
2613 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32 grfid, uint8 language_id)
2614 {
2615 /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2616 const GRFFile *grffile = GetFileByGRFID(grfid);
2617 return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
2618 }
2619
2629 template <typename T>
2630 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
2631 {
2632 if (gvid != 0) {
2633 grfmsg(1, "LoadTranslationTable: %s translation table must start at zero", name);
2634 return CIR_INVALID_ID;
2635 }
2636
2637 translation_table.clear();
2638 for (int i = 0; i < numinfo; i++) {
2639 uint32 item = buf->ReadDWord();
2640 translation_table.push_back(BSWAP32(item));
2641 }
2642
2643 return CIR_SUCCESS;
2644 }
2645
2652 static std::string ReadDWordAsString(ByteReader *reader)
2653 {
2654 char output[5];
2655 for (int i = 0; i < 4; i++) output[i] = reader->ReadByte();
2656 output[4] = '\0';
2657 StrMakeValidInPlace(output, lastof(output));
2658
2659 return std::string(output);
2660 }
2661
2670 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2671 {
2672 /* Properties which are handled as a whole */
2673 switch (prop) {
2674 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2675 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2676
2677 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2678 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2679
2680 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2681 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2682
2683 case 0x17: // Tram 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->tramtype_list, "Tram type");
2685
2686 default:
2687 break;
2688 }
2689
2690 /* Properties which are handled per item */
2691 ChangeInfoResult ret = CIR_SUCCESS;
2692 for (int i = 0; i < numinfo; i++) {
2693 switch (prop) {
2694 case 0x08: { // Cost base factor
2695 int factor = buf->ReadByte();
2696 uint price = gvid + i;
2697
2698 if (price < PR_END) {
2699 _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2700 } else {
2701 grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
2702 }
2703 break;
2704 }
2705
2706 case 0x0A: { // Currency display names
2707 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2708 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2709
2710 if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2711 _currency_specs[curidx].name = newone;
2712 }
2713 break;
2714 }
2715
2716 case 0x0B: { // Currency multipliers
2717 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2718 uint32 rate = buf->ReadDWord();
2719
2720 if (curidx < CURRENCY_END) {
2721 /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2722 * which OTTD does not. For this reason, divide grf value by 1000,
2723 * to be compatible */
2724 _currency_specs[curidx].rate = rate / 1000;
2725 } else {
2726 grfmsg(1, "GlobalVarChangeInfo: Currency multipliers %d out of range, ignoring", curidx);
2727 }
2728 break;
2729 }
2730
2731 case 0x0C: { // Currency options
2732 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2733 uint16 options = buf->ReadWord();
2734
2735 if (curidx < CURRENCY_END) {
2736 _currency_specs[curidx].separator.clear();
2737 _currency_specs[curidx].separator.push_back(GB(options, 0, 8));
2738 /* By specifying only one bit, we prevent errors,
2739 * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2740 _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2741 } else {
2742 grfmsg(1, "GlobalVarChangeInfo: Currency option %d out of range, ignoring", curidx);
2743 }
2744 break;
2745 }
2746
2747 case 0x0D: { // Currency prefix symbol
2748 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2749 std::string prefix = ReadDWordAsString(buf);
2750
2751 if (curidx < CURRENCY_END) {
2752 _currency_specs[curidx].prefix = prefix;
2753 } else {
2754 grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2755 }
2756 break;
2757 }
2758
2759 case 0x0E: { // Currency suffix symbol
2760 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2761 std::string suffix = ReadDWordAsString(buf);
2762
2763 if (curidx < CURRENCY_END) {
2764 _currency_specs[curidx].suffix = suffix;
2765 } else {
2766 grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2767 }
2768 break;
2769 }
2770
2771 case 0x0F: { // Euro introduction dates
2772 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2773 Year year_euro = buf->ReadWord();
2774
2775 if (curidx < CURRENCY_END) {
2776 _currency_specs[curidx].to_euro = year_euro;
2777 } else {
2778 grfmsg(1, "GlobalVarChangeInfo: Euro intro date %d out of range, ignoring", curidx);
2779 }
2780 break;
2781 }
2782
2783 case 0x10: // Snow line height table
2784 if (numinfo > 1 || IsSnowLineSet()) {
2785 grfmsg(1, "GlobalVarChangeInfo: The snowline can only be set once (%d)", numinfo);
2786 } else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2787 grfmsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table (" PRINTF_SIZE ")", buf->Remaining());
2788 } else {
2789 byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2790
2791 for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2792 for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2793 table[i][j] = buf->ReadByte();
2794 if (_cur.grffile->grf_version >= 8) {
2795 if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2796 } else {
2797 if (table[i][j] >= 128) {
2798 /* no snow */
2799 table[i][j] = 0xFF;
2800 } else {
2801 table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2802 }
2803 }
2804 }
2805 }
2806 SetSnowLine(table);
2807 }
2808 break;
2809
2810 case 0x11: // GRF match for engine allocation
2811 /* This is loaded during the reservation stage, so just skip it here. */
2812 /* Each entry is 8 bytes. */
2813 buf->Skip(8);
2814 break;
2815
2816 case 0x13: // Gender translation table
2817 case 0x14: // Case translation table
2818 case 0x15: { // Plural form translation
2819 uint curidx = gvid + i; // The current index, i.e. language.
2820 const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2821 if (lang == nullptr) {
2822 grfmsg(1, "GlobalVarChangeInfo: Language %d is not known, ignoring", curidx);
2823 /* Skip over the data. */
2824 if (prop == 0x15) {
2825 buf->ReadByte();
2826 } else {
2827 while (buf->ReadByte() != 0) {
2828 buf->ReadString();
2829 }
2830 }
2831 break;
2832 }
2833
2834 if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
2835
2836 if (prop == 0x15) {
2837 uint plural_form = buf->ReadByte();
2838 if (plural_form >= LANGUAGE_MAX_PLURAL) {
2839 grfmsg(1, "GlobalVarChanceInfo: Plural form %d is out of range, ignoring", plural_form);
2840 } else {
2841 _cur.grffile->language_map[curidx].plural_form = plural_form;
2842 }
2843 break;
2844 }
2845
2846 byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
2847 while (newgrf_id != 0) {
2848 const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
2849
2850 /* We'll just ignore the UTF8 identifier character. This is (fairly)
2851 * safe as OpenTTD's strings gender/cases are usually in ASCII which
2852 * is just a subset of UTF8, or they need the bigger UTF8 characters
2853 * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2854 WChar c;
2855 size_t len = Utf8Decode(&c, name);
2856 if (c == NFO_UTF8_IDENTIFIER) name += len;
2857
2858 LanguageMap::Mapping map;
2859 map.newgrf_id = newgrf_id;
2860 if (prop == 0x13) {
2861 map.openttd_id = lang->GetGenderIndex(name);
2862 if (map.openttd_id >= MAX_NUM_GENDERS) {
2863 grfmsg(1, "GlobalVarChangeInfo: Gender name %s is not known, ignoring", name);
2864 } else {
2865 _cur.grffile->language_map[curidx].gender_map.push_back(map);
2866 }
2867 } else {
2868 map.openttd_id = lang->GetCaseIndex(name);
2869 if (map.openttd_id >= MAX_NUM_CASES) {
2870 grfmsg(1, "GlobalVarChangeInfo: Case name %s is not known, ignoring", name);
2871 } else {
2872 _cur.grffile->language_map[curidx].case_map.push_back(map);
2873 }
2874 }
2875 newgrf_id = buf->ReadByte();
2876 }
2877 break;
2878 }
2879
2880 default:
2881 ret = CIR_UNKNOWN;
2882 break;
2883 }
2884 }
2885
2886 return ret;
2887 }
2888
2889 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2890 {
2891 /* Properties which are handled as a whole */
2892 switch (prop) {
2893 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2894 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2895
2896 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2897 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2898
2899 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2900 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2901
2902 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2903 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2904
2905 default:
2906 break;
2907 }
2908
2909 /* Properties which are handled per item */
2910 ChangeInfoResult ret = CIR_SUCCESS;
2911 for (int i = 0; i < numinfo; i++) {
2912 switch (prop) {
2913 case 0x08: // Cost base factor
2914 case 0x15: // Plural form translation
2915 buf->ReadByte();
2916 break;
2917
2918 case 0x0A: // Currency display names
2919 case 0x0C: // Currency options
2920 case 0x0F: // Euro introduction dates
2921 buf->ReadWord();
2922 break;
2923
2924 case 0x0B: // Currency multipliers
2925 case 0x0D: // Currency prefix symbol
2926 case 0x0E: // Currency suffix symbol
2927 buf->ReadDWord();
2928 break;
2929
2930 case 0x10: // Snow line height table
2931 buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2932 break;
2933
2934 case 0x11: { // GRF match for engine allocation
2935 uint32 s = buf->ReadDWord();
2936 uint32 t = buf->ReadDWord();
2937 SetNewGRFOverride(s, t);
2938 break;
2939 }
2940
2941 case 0x13: // Gender translation table
2942 case 0x14: // Case translation table
2943 while (buf->ReadByte() != 0) {
2944 buf->ReadString();
2945 }
2946 break;
2947
2948 default:
2949 ret = CIR_UNKNOWN;
2950 break;
2951 }
2952 }
2953
2954 return ret;
2955 }
2956
2957
2966 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
2967 {
2968 ChangeInfoResult ret = CIR_SUCCESS;
2969
2970 if (cid + numinfo > NUM_CARGO) {
2971 grfmsg(2, "CargoChangeInfo: Cargo type %d out of range (max %d)", cid + numinfo, NUM_CARGO - 1);
2972 return CIR_INVALID_ID;
2973 }
2974
2975 for (int i = 0; i < numinfo; i++) {
2976 CargoSpec *cs = CargoSpec::Get(cid + i);
2977
2978 switch (prop) {
2979 case 0x08: // Bit number of cargo
2980 cs->bitnum = buf->ReadByte();
2981 if (cs->IsValid()) {
2982 cs->grffile = _cur.grffile;
2983 SetBit(_cargo_mask, cid + i);
2984 } else {
2985 ClrBit(_cargo_mask, cid + i);
2986 }
2987 break;
2988
2989 case 0x09: // String ID for cargo type name
2990 AddStringForMapping(buf->ReadWord(), &cs->name);
2991 break;
2992
2993 case 0x0A: // String for 1 unit of cargo
2994 AddStringForMapping(buf->ReadWord(), &cs->name_single);
2995 break;
2996
2997 case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
2998 case 0x1B: // String for cargo units
2999 /* String for units of cargo. This is different in OpenTTD
3000 * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
3001 * Property 1B is used to set OpenTTD's behaviour. */
3002 AddStringForMapping(buf->ReadWord(), &cs->units_volume);
3003 break;
3004
3005 case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
3006 case 0x1C: // String for any amount of cargo
3007 /* Strings for an amount of cargo. This is different in OpenTTD
3008 * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
3009 * Property 1C is used to set OpenTTD's behaviour. */
3010 AddStringForMapping(buf->ReadWord(), &cs->quantifier);
3011 break;
3012
3013 case 0x0D: // String for two letter cargo abbreviation
3014 AddStringForMapping(buf->ReadWord(), &cs->abbrev);
3015 break;
3016
3017 case 0x0E: // Sprite ID for cargo icon
3018 cs->sprite = buf->ReadWord();
3019 break;
3020
3021 case 0x0F: // Weight of one unit of cargo
3022 cs->weight = buf->ReadByte();
3023 break;
3024
3025 case 0x10: // Used for payment calculation
3026 cs->transit_days[0] = buf->ReadByte();
3027 break;
3028
3029 case 0x11: // Used for payment calculation
3030 cs->transit_days[1] = buf->ReadByte();
3031 break;
3032
3033 case 0x12: // Base cargo price
3034 cs->initial_payment = buf->ReadDWord();
3035 break;
3036
3037 case 0x13: // Colour for station rating bars
3038 cs->rating_colour = buf->ReadByte();
3039 break;
3040
3041 case 0x14: // Colour for cargo graph
3042 cs->legend_colour = buf->ReadByte();
3043 break;
3044
3045 case 0x15: // Freight status
3046 cs->is_freight = (buf->ReadByte() != 0);
3047 break;
3048
3049 case 0x16: // Cargo classes
3050 cs->classes = buf->ReadWord();
3051 break;
3052
3053 case 0x17: // Cargo label
3054 cs->label = buf->ReadDWord();
3055 cs->label = BSWAP32(cs->label);
3056 break;
3057
3058 case 0x18: { // Town growth substitute type
3059 uint8 substitute_type = buf->ReadByte();
3060
3061 switch (substitute_type) {
3062 case 0x00: cs->town_effect = TE_PASSENGERS; break;
3063 case 0x02: cs->town_effect = TE_MAIL; break;
3064 case 0x05: cs->town_effect = TE_GOODS; break;
3065 case 0x09: cs->town_effect = TE_WATER; break;
3066 case 0x0B: cs->town_effect = TE_FOOD; break;
3067 default:
3068 grfmsg(1, "CargoChangeInfo: Unknown town growth substitute value %d, setting to none.", substitute_type);
3069 FALLTHROUGH;
3070 case 0xFF: cs->town_effect = TE_NONE; break;
3071 }
3072 break;
3073 }
3074
3075 case 0x19: // Town growth coefficient
3076 buf->ReadWord();
3077 break;
3078
3079 case 0x1A: // Bitmask of callbacks to use
3080 cs->callback_mask = buf->ReadByte();
3081 break;
3082
3083 case 0x1D: // Vehicle capacity muliplier
3084 cs->multiplier = std::max<uint16>(1u, buf->ReadWord());
3085 break;
3086
3087 default:
3088 ret = CIR_UNKNOWN;
3089 break;
3090 }
3091 }
3092
3093 return ret;
3094 }
3095
3096
3105 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
3106 {
3107 ChangeInfoResult ret = CIR_SUCCESS;
3108
3109 if (_cur.grffile->sound_offset == 0) {
3110 grfmsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3111 return CIR_INVALID_ID;
3112 }
3113
3114 if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3115 grfmsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect (%u), max (%u). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3116 return CIR_INVALID_ID;
3117 }
3118
3119 for (int i = 0; i < numinfo; i++) {
3120 SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3121
3122 switch (prop) {
3123 case 0x08: // Relative volume
3124 sound->volume = buf->ReadByte();
3125 break;
3126
3127 case 0x09: // Priority
3128 sound->priority = buf->ReadByte();
3129 break;
3130
3131 case 0x0A: { // Override old sound
3132 SoundID orig_sound = buf->ReadByte();
3133
3134 if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3135 grfmsg(1, "SoundEffectChangeInfo: Original sound %d not defined (max %d)", orig_sound, ORIGINAL_SAMPLE_COUNT);
3136 } else {
3137 SoundEntry *old_sound = GetSound(orig_sound);
3138
3139 /* Literally copy the data of the new sound over the original */
3140 *old_sound = *sound;
3141 }
3142 break;
3143 }
3144
3145 default:
3146 ret = CIR_UNKNOWN;
3147 break;
3148 }
3149 }
3150
3151 return ret;
3152 }
3153
3160 static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
3161 {
3162 ChangeInfoResult ret = CIR_SUCCESS;
3163
3164 switch (prop) {
3165 case 0x09:
3166 case 0x0D:
3167 case 0x0E:
3168 case 0x10:
3169 case 0x11:
3170 case 0x12:
3171 buf->ReadByte();
3172 break;
3173
3174 case 0x0A:
3175 case 0x0B:
3176 case 0x0C:
3177 case 0x0F:
3178 buf->ReadWord();
3179 break;
3180
3181 case 0x13:
3182 buf->Skip(buf->ReadByte() * 2);
3183 break;
3184
3185 default:
3186 ret = CIR_UNKNOWN;
3187 break;
3188 }
3189 return ret;
3190 }
3191
3200 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
3201 {
3202 ChangeInfoResult ret = CIR_SUCCESS;
3203
3204 if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3205 grfmsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded (%u), max (%u). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3206 return CIR_INVALID_ID;
3207 }
3208
3209 /* Allocate industry tile specs if they haven't been allocated already. */
3210 if (_cur.grffile->indtspec == nullptr) {
3211 _cur.grffile->indtspec = CallocT<IndustryTileSpec*>(NUM_INDUSTRYTILES_PER_GRF);
3212 }
3213
3214 for (int i = 0; i < numinfo; i++) {
3215 IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i];
3216
3217 if (prop != 0x08 && tsp == nullptr) {
3218 ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf);
3219 if (cir > ret) ret = cir;
3220 continue;
3221 }
3222
3223 switch (prop) {
3224 case 0x08: { // Substitute industry tile type
3225 IndustryTileSpec **tilespec = &_cur.grffile->indtspec[indtid + i];
3226 byte subs_id = buf->ReadByte();
3227
3228 if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3229 /* The substitute id must be one of the original industry tile. */
3230 grfmsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile %u as substitute industry tile for %u. Ignoring.", subs_id, indtid + i);
3231 continue;
3232 }
3233
3234 /* Allocate space for this industry. */
3235 if (*tilespec == nullptr) {
3236 *tilespec = CallocT<IndustryTileSpec>(1);
3237 tsp = *tilespec;
3238
3239 memcpy(tsp, &_industry_tile_specs[subs_id], sizeof(_industry_tile_specs[subs_id]));
3240 tsp->enabled = true;
3241
3242 /* A copied tile should not have the animation infos copied too.
3243 * The anim_state should be left untouched, though
3244 * It is up to the author to animate them */
3245 tsp->anim_production = INDUSTRYTILE_NOANIM;
3246 tsp->anim_next = INDUSTRYTILE_NOANIM;
3247
3248 tsp->grf_prop.local_id = indtid + i;
3249 tsp->grf_prop.subst_id = subs_id;
3250 tsp->grf_prop.grffile = _cur.grffile;
3251 _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3252 }
3253 break;
3254 }
3255
3256 case 0x09: { // Industry tile override
3257 byte ovrid = buf->ReadByte();
3258
3259 /* The industry being overridden must be an original industry. */
3260 if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3261 grfmsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile %u with industry tile id %u. Ignoring.", ovrid, indtid + i);
3262 continue;
3263 }
3264
3265 _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3266 break;
3267 }
3268
3269 case 0x0A: // Tile acceptance
3270 case 0x0B:
3271 case 0x0C: {
3272 uint16 acctp = buf->ReadWord();
3273 tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3274 tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3275 break;
3276 }
3277
3278 case 0x0D: // Land shape flags
3279 tsp->slopes_refused = (Slope)buf->ReadByte();
3280 break;
3281
3282 case 0x0E: // Callback mask
3283 tsp->callback_mask = buf->ReadByte();
3284 break;
3285
3286 case 0x0F: // Animation information
3287 tsp->animation.frames = buf->ReadByte();
3288 tsp->animation.status = buf->ReadByte();
3289 break;
3290
3291 case 0x10: // Animation speed
3292 tsp->animation.speed = buf->ReadByte();
3293 break;
3294
3295 case 0x11: // Triggers for callback 25
3296 tsp->animation.triggers = buf->ReadByte();
3297 break;
3298
3299 case 0x12: // Special flags
3300 tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
3301 break;
3302
3303 case 0x13: { // variable length cargo acceptance
3304 byte num_cargoes = buf->ReadByte();
3305 if (num_cargoes > lengthof(tsp->acceptance)) {
3306 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3307 error->param_value[1] = prop;
3308 return CIR_DISABLED;
3309 }
3310 for (uint i = 0; i < lengthof(tsp->acceptance); i++) {
3311 if (i < num_cargoes) {
3312 tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3313 /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3314 tsp->acceptance[i] = (int8)buf->ReadByte();
3315 } else {
3316 tsp->accepts_cargo[i] = CT_INVALID;
3317 tsp->acceptance[i] = 0;
3318 }
3319 }
3320 break;
3321 }
3322
3323 default:
3324 ret = CIR_UNKNOWN;
3325 break;
3326 }
3327 }
3328
3329 return ret;
3330 }
3331
3338 static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
3339 {
3340 ChangeInfoResult ret = CIR_SUCCESS;
3341
3342 switch (prop) {
3343 case 0x09:
3344 case 0x0B:
3345 case 0x0F:
3346 case 0x12:
3347 case 0x13:
3348 case 0x14:
3349 case 0x17:
3350 case 0x18:
3351 case 0x19:
3352 case 0x21:
3353 case 0x22:
3354 buf->ReadByte();
3355 break;
3356
3357 case 0x0C:
3358 case 0x0D:
3359 case 0x0E:
3360 case 0x10:
3361 case 0x1B:
3362 case 0x1F:
3363 case 0x24:
3364 buf->ReadWord();
3365 break;
3366
3367 case 0x11:
3368 case 0x1A:
3369 case 0x1C:
3370 case 0x1D:
3371 case 0x1E:
3372 case 0x20:
3373 case 0x23:
3374 buf->ReadDWord();
3375 break;
3376
3377 case 0x0A: {
3378 byte num_table = buf->ReadByte();
3379 for (byte j = 0; j < num_table; j++) {
3380 for (uint k = 0;; k++) {
3381 byte x = buf->ReadByte();
3382 if (x == 0xFE && k == 0) {
3383 buf->ReadByte();
3384 buf->ReadByte();
3385 break;
3386 }
3387
3388 byte y = buf->ReadByte();
3389 if (x == 0 && y == 0x80) break;
3390
3391 byte gfx = buf->ReadByte();
3392 if (gfx == 0xFE) buf->ReadWord();
3393 }
3394 }
3395 break;
3396 }
3397
3398 case 0x16:
3399 for (byte j = 0; j < 3; j++) buf->ReadByte();
3400 break;
3401
3402 case 0x15:
3403 case 0x25:
3404 case 0x26:
3405 case 0x27:
3406 buf->Skip(buf->ReadByte());
3407 break;
3408
3409 case 0x28: {
3410 int num_inputs = buf->ReadByte();
3411 int num_outputs = buf->ReadByte();
3412 buf->Skip(num_inputs * num_outputs * 2);
3413 break;
3414 }
3415
3416 default:
3417 ret = CIR_UNKNOWN;
3418 break;
3419 }
3420 return ret;
3421 }
3422
3428 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3429 {
3430 const size_t size = layout.size();
3431 if (size == 0) return false;
3432
3433 for (size_t i = 0; i < size - 1; i++) {
3434 for (size_t j = i + 1; j < size; j++) {
3435 if (layout[i].ti.x == layout[j].ti.x &&
3436 layout[i].ti.y == layout[j].ti.y) {
3437 return false;
3438 }
3439 }
3440 }
3441
3442 bool have_regular_tile = false;
3443 for (size_t i = 0; i < size; i++) {
3444 if (layout[i].gfx != GFX_WATERTILE_SPECIALCHECK) {
3445 have_regular_tile = true;
3446 break;
3447 }
3448 }
3449
3450 return have_regular_tile;
3451 }
3452
3461 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
3462 {
3463 ChangeInfoResult ret = CIR_SUCCESS;
3464
3465 if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3466 grfmsg(1, "IndustriesChangeInfo: Too many industries loaded (%u), max (%u). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3467 return CIR_INVALID_ID;
3468 }
3469
3470 /* Allocate industry specs if they haven't been allocated already. */
3471 if (_cur.grffile->industryspec == nullptr) {
3472 _cur.grffile->industryspec = CallocT<IndustrySpec*>(NUM_INDUSTRYTYPES_PER_GRF);
3473 }
3474
3475 for (int i = 0; i < numinfo; i++) {
3476 IndustrySpec *indsp = _cur.grffile->industryspec[indid + i];
3477
3478 if (prop != 0x08 && indsp == nullptr) {
3479 ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3480 if (cir > ret) ret = cir;
3481 continue;
3482 }
3483
3484 switch (prop) {
3485 case 0x08: { // Substitute industry type
3486 IndustrySpec **indspec = &_cur.grffile->industryspec[indid + i];
3487 byte subs_id = buf->ReadByte();
3488
3489 if (subs_id == 0xFF) {
3490 /* Instead of defining a new industry, a substitute industry id
3491 * of 0xFF disables the old industry with the current id. */
3492 _industry_specs[indid + i].enabled = false;
3493 continue;
3494 } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3495 /* The substitute id must be one of the original industry. */
3496 grfmsg(2, "_industry_specs: Attempt to use new industry %u as substitute industry for %u. Ignoring.", subs_id, indid + i);
3497 continue;
3498 }
3499
3500 /* Allocate space for this industry.
3501 * Only need to do it once. If ever it is called again, it should not
3502 * do anything */
3503 if (*indspec == nullptr) {
3504 *indspec = new IndustrySpec;
3505 indsp = *indspec;
3506
3507 *indsp = _origin_industry_specs[subs_id];
3508 indsp->enabled = true;
3509 indsp->grf_prop.local_id = indid + i;
3510 indsp->grf_prop.subst_id = subs_id;
3511 indsp->grf_prop.grffile = _cur.grffile;
3512 /* If the grf industry needs to check its surrounding upon creation, it should
3513 * rely on callbacks, not on the original placement functions */
3514 indsp->check_proc = CHECK_NOTHING;
3515 }
3516 break;
3517 }
3518
3519 case 0x09: { // Industry type override
3520 byte ovrid = buf->ReadByte();
3521
3522 /* The industry being overridden must be an original industry. */
3523 if (ovrid >= NEW_INDUSTRYOFFSET) {
3524 grfmsg(2, "IndustriesChangeInfo: Attempt to override new industry %u with industry id %u. Ignoring.", ovrid, indid + i);
3525 continue;
3526 }
3527 indsp->grf_prop.override = ovrid;
3528 _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3529 break;
3530 }
3531
3532 case 0x0A: { // Set industry layout(s)
3533 byte new_num_layouts = buf->ReadByte();
3534 uint32 definition_size = buf->ReadDWord();
3535 uint32 bytes_read = 0;
3536 std::vector<IndustryTileLayout> new_layouts;
3537 IndustryTileLayout layout;
3538
3539 for (byte j = 0; j < new_num_layouts; j++) {
3540 layout.clear();
3541
3542 for (uint k = 0;; k++) {
3543 if (bytes_read >= definition_size) {
3544 grfmsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry %u.", indid);
3545 /* Avoid warning twice */
3546 definition_size = UINT32_MAX;
3547 }
3548
3549 layout.push_back(IndustryTileLayoutTile{});
3550 IndustryTileLayoutTile &it = layout.back();
3551
3552 it.ti.x = buf->ReadByte(); // Offsets from northermost tile
3553 ++bytes_read;
3554
3555 if (it.ti.x == 0xFE && k == 0) {
3556 /* This means we have to borrow the layout from an old industry */
3557 IndustryType type = buf->ReadByte();
3558 byte laynbr = buf->ReadByte();
3559 bytes_read += 2;
3560
3561 if (type >= lengthof(_origin_industry_specs)) {
3562 grfmsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry %u", indid);
3563 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3564 return CIR_DISABLED;
3565 }
3566 if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3567 grfmsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry %u", indid);
3568 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3569 return CIR_DISABLED;
3570 }
3571 layout = _origin_industry_specs[type].layouts[laynbr];
3572 break;
3573 }
3574
3575 it.ti.y = buf->ReadByte(); // Or table definition finalisation
3576 ++bytes_read;
3577
3578 if (it.ti.x == 0 && it.ti.y == 0x80) {
3579 /* Terminator, remove and finish up */
3580 layout.pop_back();
3581 break;
3582 }
3583
3584 it.gfx = buf->ReadByte();
3585 ++bytes_read;
3586
3587 if (it.gfx == 0xFE) {
3588 /* Use a new tile from this GRF */
3589 int local_tile_id = buf->ReadWord();
3590 bytes_read += 2;
3591
3592 /* Read the ID from the _industile_mngr. */
3593 int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3594
3595 if (tempid == INVALID_INDUSTRYTILE) {
3596 grfmsg(2, "IndustriesChangeInfo: Attempt to use industry tile %u with industry id %u, not yet defined. Ignoring.", local_tile_id, indid);
3597 } else {
3598 /* Declared as been valid, can be used */
3599 it.gfx = tempid;
3600 }
3601 } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
3602 it.ti.x = (int8)GB(it.ti.x, 0, 8);
3603 it.ti.y = (int8)GB(it.ti.y, 0, 8);
3604
3605 /* When there were only 256x256 maps, TileIndex was a uint16 and
3606 * it.ti was just a TileIndexDiff that was added to it.
3607 * As such negative "x" values were shifted into the "y" position.
3608 * x = -1, y = 1 -> x = 255, y = 0
3609 * Since GRF version 8 the position is interpreted as pair of independent int8.
3610 * For GRF version < 8 we need to emulate the old shifting behaviour.
3611 */
3612 if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3613 }
3614 }
3615
3616 if (!ValidateIndustryLayout(layout)) {
3617 /* The industry layout was not valid, so skip this one. */
3618 grfmsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id %u. Ignoring", indid);
3619 new_num_layouts--;
3620 j--;
3621 } else {
3622 new_layouts.push_back(layout);
3623 }
3624 }
3625
3626 /* Install final layout construction in the industry spec */
3627 indsp->layouts = new_layouts;
3628 break;
3629 }
3630
3631 case 0x0B: // Industry production flags
3632 indsp->life_type = (IndustryLifeType)buf->ReadByte();
3633 break;
3634
3635 case 0x0C: // Industry closure message
3636 AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
3637 break;
3638
3639 case 0x0D: // Production increase message
3640 AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
3641 break;
3642
3643 case 0x0E: // Production decrease message
3644 AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
3645 break;
3646
3647 case 0x0F: // Fund cost multiplier
3648 indsp->cost_multiplier = buf->ReadByte();
3649 break;
3650
3651 case 0x10: // Production cargo types
3652 for (byte j = 0; j < 2; j++) {
3653 indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3654 }
3655 break;
3656
3657 case 0x11: // Acceptance cargo types
3658 for (byte j = 0; j < 3; j++) {
3659 indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3660 }
3661 buf->ReadByte(); // Unnused, eat it up
3662 break;
3663
3664 case 0x12: // Production multipliers
3665 case 0x13:
3666 indsp->production_rate[prop - 0x12] = buf->ReadByte();
3667 break;
3668
3669 case 0x14: // Minimal amount of cargo distributed
3670 indsp->minimal_cargo = buf->ReadByte();
3671 break;
3672
3673 case 0x15: { // Random sound effects
3674 indsp->number_of_sounds = buf->ReadByte();
3675 uint8 *sounds = MallocT<uint8>(indsp->number_of_sounds);
3676
3677 try {
3678 for (uint8 j = 0; j < indsp->number_of_sounds; j++) {
3679 sounds[j] = buf->ReadByte();
3680 }
3681 } catch (...) {
3682 free(sounds);
3683 throw;
3684 }
3685
3686 if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3687 free(indsp->random_sounds);
3688 }
3689 indsp->random_sounds = sounds;
3690 SetBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS);
3691 break;
3692 }
3693
3694 case 0x16: // Conflicting industry types
3695 for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
3696 break;
3697
3698 case 0x17: // Probability in random game
3699 indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
3700 break;
3701
3702 case 0x18: // Probability during gameplay
3703 indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
3704 break;
3705
3706 case 0x19: // Map colour
3707 indsp->map_colour = buf->ReadByte();
3708 break;
3709
3710 case 0x1A: // Special industry flags to define special behavior
3711 indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
3712 break;
3713
3714 case 0x1B: // New industry text ID
3715 AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
3716 break;
3717
3718 case 0x1C: // Input cargo multipliers for the three input cargo types
3719 case 0x1D:
3720 case 0x1E: {
3721 uint32 multiples = buf->ReadDWord();
3722 indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3723 indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3724 break;
3725 }
3726
3727 case 0x1F: // Industry name
3728 AddStringForMapping(buf->ReadWord(), &indsp->name);
3729 break;
3730
3731 case 0x20: // Prospecting success chance
3732 indsp->prospecting_chance = buf->ReadDWord();
3733 break;
3734
3735 case 0x21: // Callback mask
3736 case 0x22: { // Callback additional mask
3737 byte aflag = buf->ReadByte();
3738 SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3739 break;
3740 }
3741
3742 case 0x23: // removal cost multiplier
3743 indsp->removal_cost_multiplier = buf->ReadDWord();
3744 break;
3745
3746 case 0x24: { // name for nearby station
3747 uint16 str = buf->ReadWord();
3748 if (str == 0) {
3749 indsp->station_name = STR_NULL;
3750 } else {
3751 AddStringForMapping(str, &indsp->station_name);
3752 }
3753 break;
3754 }
3755
3756 case 0x25: { // variable length produced cargoes
3757 byte num_cargoes = buf->ReadByte();
3758 if (num_cargoes > lengthof(indsp->produced_cargo)) {
3759 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3760 error->param_value[1] = prop;
3761 return CIR_DISABLED;
3762 }
3763 for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
3764 if (i < num_cargoes) {
3765 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3766 indsp->produced_cargo[i] = cargo;
3767 } else {
3768 indsp->produced_cargo[i] = CT_INVALID;
3769 }
3770 }
3771 break;
3772 }
3773
3774 case 0x26: { // variable length accepted cargoes
3775 byte num_cargoes = buf->ReadByte();
3776 if (num_cargoes > lengthof(indsp->accepts_cargo)) {
3777 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3778 error->param_value[1] = prop;
3779 return CIR_DISABLED;
3780 }
3781 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3782 if (i < num_cargoes) {
3783 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3784 indsp->accepts_cargo[i] = cargo;
3785 } else {
3786 indsp->accepts_cargo[i] = CT_INVALID;
3787 }
3788 }
3789 break;
3790 }
3791
3792 case 0x27: { // variable length production rates
3793 byte num_cargoes = buf->ReadByte();
3794 if (num_cargoes > lengthof(indsp->production_rate)) {
3795 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3796 error->param_value[1] = prop;
3797 return CIR_DISABLED;
3798 }
3799 for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3800 if (i < num_cargoes) {
3801 indsp->production_rate[i] = buf->ReadByte();
3802 } else {
3803 indsp->production_rate[i] = 0;
3804 }
3805 }
3806 break;
3807 }
3808
3809 case 0x28: { // variable size input/output production multiplier table
3810 byte num_inputs = buf->ReadByte();
3811 byte num_outputs = buf->ReadByte();
3812 if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
3813 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3814 error->param_value[1] = prop;
3815 return CIR_DISABLED;
3816 }
3817 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3818 for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
3819 uint16 mult = 0;
3820 if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
3821 indsp->input_cargo_multiplier[i][j] = mult;
3822 }
3823 }
3824 break;
3825 }
3826
3827 default:
3828 ret = CIR_UNKNOWN;
3829 break;
3830 }
3831 }
3832
3833 return ret;
3834 }
3835
3841 static void DuplicateTileTable(AirportSpec *as)
3842 {
3843 AirportTileTable **table_list = MallocT<AirportTileTable*>(as->num_table);
3844 for (int i = 0; i < as->num_table; i++) {
3845 uint num_tiles = 1;
3846 const AirportTileTable *it = as->table[0];
3847 do {
3848 num_tiles++;
3849 } while ((++it)->ti.x != -0x80);
3850 table_list[i] = MallocT<AirportTileTable>(num_tiles);
3851 MemCpyT(table_list[i], as->table[i], num_tiles);
3852 }
3853 as->table = table_list;
3854 HangarTileTable *depot_table = MallocT<HangarTileTable>(as->nof_depots);
3855 MemCpyT(depot_table, as->depot_table, as->nof_depots);
3856 as->depot_table = depot_table;
3857 Direction *rotation = MallocT<Direction>(as->num_table);
3858 MemCpyT(rotation, as->rotation, as->num_table);
3859 as->rotation = rotation;
3860 }
3861
3870 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
3871 {
3872 ChangeInfoResult ret = CIR_SUCCESS;
3873
3874 if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3875 grfmsg(1, "AirportChangeInfo: Too many airports, trying id (%u), max (%u). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3876 return CIR_INVALID_ID;
3877 }
3878
3879 /* Allocate industry specs if they haven't been allocated already. */
3880 if (_cur.grffile->airportspec == nullptr) {
3881 _cur.grffile->airportspec = CallocT<AirportSpec*>(NUM_AIRPORTS_PER_GRF);
3882 }
3883
3884 for (int i = 0; i < numinfo; i++) {
3885 AirportSpec *as = _cur.grffile->airportspec[airport + i];
3886
3887 if (as == nullptr && prop != 0x08 && prop != 0x09) {
3888 grfmsg(2, "AirportChangeInfo: Attempt to modify undefined airport %u, ignoring", airport + i);
3889 return CIR_INVALID_ID;
3890 }
3891
3892 switch (prop) {
3893 case 0x08: { // Modify original airport
3894 byte subs_id = buf->ReadByte();
3895
3896 if (subs_id == 0xFF) {
3897 /* Instead of defining a new airport, an airport id
3898 * of 0xFF disables the old airport with the current id. */
3899 AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3900 continue;
3901 } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3902 /* The substitute id must be one of the original airports. */
3903 grfmsg(2, "AirportChangeInfo: Attempt to use new airport %u as substitute airport for %u. Ignoring.", subs_id, airport + i);
3904 continue;
3905 }
3906
3907 AirportSpec **spec = &_cur.grffile->airportspec[airport + i];
3908 /* Allocate space for this airport.
3909 * Only need to do it once. If ever it is called again, it should not
3910 * do anything */
3911 if (*spec == nullptr) {
3912 *spec = MallocT<AirportSpec>(1);
3913 as = *spec;
3914
3915 memcpy(as, AirportSpec::GetWithoutOverride(subs_id), sizeof(*as));
3916 as->enabled = true;
3917 as->grf_prop.local_id = airport + i;
3918 as->grf_prop.subst_id = subs_id;
3919 as->grf_prop.grffile = _cur.grffile;
3920 /* override the default airport */
3921 _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3922 /* Create a copy of the original tiletable so it can be freed later. */
3923 DuplicateTileTable(as);
3924 }
3925 break;
3926 }
3927
3928 case 0x0A: { // Set airport layout
3929 byte old_num_table = as->num_table;
3930 free(as->rotation);
3931 as->num_table = buf->ReadByte(); // Number of layaouts
3932 as->rotation = MallocT<Direction>(as->num_table);
3933 uint32 defsize = buf->ReadDWord(); // Total size of the definition
3934 AirportTileTable **tile_table = CallocT<AirportTileTable*>(as->num_table); // Table with tiles to compose the airport
3935 AirportTileTable *att = CallocT<AirportTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
3936 int size;
3937 const AirportTileTable *copy_from;
3938 try {
3939 for (byte j = 0; j < as->num_table; j++) {
3940 const_cast<Direction&>(as->rotation[j]) = (Direction)buf->ReadByte();
3941 for (int k = 0;; k++) {
3942 att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3943 att[k].ti.y = buf->ReadByte();
3944
3945 if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
3946 /* Not the same terminator. The one we are using is rather
3947 * x = -80, y = 0 . So, adjust it. */
3948 att[k].ti.x = -0x80;
3949 att[k].ti.y = 0;
3950 att[k].gfx = 0;
3951
3952 size = k + 1;
3953 copy_from = att;
3954 break;
3955 }
3956
3957 att[k].gfx = buf->ReadByte();
3958
3959 if (att[k].gfx == 0xFE) {
3960 /* Use a new tile from this GRF */
3961 int local_tile_id = buf->ReadWord();
3962
3963 /* Read the ID from the _airporttile_mngr. */
3964 uint16 tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3965
3966 if (tempid == INVALID_AIRPORTTILE) {
3967 grfmsg(2, "AirportChangeInfo: Attempt to use airport tile %u with airport id %u, not yet defined. Ignoring.", local_tile_id, airport + i);
3968 } else {
3969 /* Declared as been valid, can be used */
3970 att[k].gfx = tempid;
3971 }
3972 } else if (att[k].gfx == 0xFF) {
3973 att[k].ti.x = (int8)GB(att[k].ti.x, 0, 8);
3974 att[k].ti.y = (int8)GB(att[k].ti.y, 0, 8);
3975 }
3976
3977 if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
3978 as->size_x = std::max<byte>(as->size_x, att[k].ti.y + 1);
3979 as->size_y = std::max<byte>(as->size_y, att[k].ti.x + 1);
3980 } else {
3981 as->size_x = std::max<byte>(as->size_x, att[k].ti.x + 1);
3982 as->size_y = std::max<byte>(as->size_y, att[k].ti.y + 1);
3983 }
3984 }
3985 tile_table[j] = CallocT<AirportTileTable>(size);
3986 memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
3987 }
3988 /* Free old layouts in the airport spec */
3989 for (int j = 0; j < old_num_table; j++) {
3990 /* remove the individual layouts */
3991 free(as->table[j]);
3992 }
3993 free(as->table);
3994 /* Install final layout construction in the airport spec */
3995 as->table = tile_table;
3996 free(att);
3997 } catch (...) {
3998 for (int i = 0; i < as->num_table; i++) {
3999 free(tile_table[i]);
4000 }
4001 free(tile_table);
4002 free(att);
4003 throw;
4004 }
4005 break;
4006 }
4007
4008 case 0x0C:
4009 as->min_year = buf->ReadWord();
4010 as->max_year = buf->ReadWord();
4011 if (as->max_year == 0xFFFF) as->max_year = MAX_YEAR;
4012 break;
4013
4014 case 0x0D:
4015 as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
4016 break;
4017
4018 case 0x0E:
4019 as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
4020 break;
4021
4022 case 0x0F:
4023 as->noise_level = buf->ReadByte();
4024 break;
4025
4026 case 0x10:
4027 AddStringForMapping(buf->ReadWord(), &as->name);
4028 break;
4029
4030 case 0x11: // Maintenance cost factor
4031 as->maintenance_cost = buf->ReadWord();
4032 break;
4033
4034 default:
4035 ret = CIR_UNKNOWN;
4036 break;
4037 }
4038 }
4039
4040 return ret;
4041 }
4042
4049 static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
4050 {
4051 ChangeInfoResult ret = CIR_SUCCESS;
4052
4053 switch (prop) {
4054 case 0x0B:
4055 case 0x0C:
4056 case 0x0D:
4057 case 0x12:
4058 case 0x14:
4059 case 0x16:
4060 case 0x17:
4061 buf->ReadByte();
4062 break;
4063
4064 case 0x09:
4065 case 0x0A:
4066 case 0x10:
4067 case 0x11:
4068 case 0x13:
4069 case 0x15:
4070 buf->ReadWord();
4071 break;
4072
4073 case 0x08:
4074 case 0x0E:
4075 case 0x0F:
4076 buf->ReadDWord();
4077 break;
4078
4079 default:
4080 ret = CIR_UNKNOWN;
4081 break;
4082 }
4083
4084 return ret;
4085 }
4086
4095 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4096 {
4097 ChangeInfoResult ret = CIR_SUCCESS;
4098
4099 if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4100 grfmsg(1, "ObjectChangeInfo: Too many objects loaded (%u), max (%u). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4101 return CIR_INVALID_ID;
4102 }
4103
4104 /* Allocate object specs if they haven't been allocated already. */
4105 if (_cur.grffile->objectspec == nullptr) {
4106 _cur.grffile->objectspec = CallocT<ObjectSpec*>(NUM_OBJECTS_PER_GRF);
4107 }
4108
4109 for (int i = 0; i < numinfo; i++) {
4110 ObjectSpec *spec = _cur.grffile->objectspec[id + i];
4111
4112 if (prop != 0x08 && spec == nullptr) {
4113 /* If the object property 08 is not yet set, ignore this property */
4114 ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4115 if (cir > ret) ret = cir;
4116 continue;
4117 }
4118
4119 switch (prop) {
4120 case 0x08: { // Class ID
4121 ObjectSpec **ospec = &_cur.grffile->objectspec[id + i];
4122
4123 /* Allocate space for this object. */
4124 if (*ospec == nullptr) {
4125 *ospec = CallocT<ObjectSpec>(1);
4126 (*ospec)->views = 1; // Default for NewGRFs that don't set it.
4127 (*ospec)->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
4128 }
4129
4130 /* Swap classid because we read it in BE. */
4131 uint32 classid = buf->ReadDWord();
4132 (*ospec)->cls_id = ObjectClass::Allocate(BSWAP32(classid));
4133 (*ospec)->enabled = true;
4134 break;
4135 }
4136
4137 case 0x09: { // Class name
4138 ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
4139 AddStringForMapping(buf->ReadWord(), &objclass->name);
4140 break;
4141 }
4142
4143 case 0x0A: // Object name
4144 AddStringForMapping(buf->ReadWord(), &spec->name);
4145 break;
4146
4147 case 0x0B: // Climate mask
4148 spec->climate = buf->ReadByte();
4149 break;
4150
4151 case 0x0C: // Size
4152 spec->size = buf->ReadByte();
4153 if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4154 grfmsg(0, "ObjectChangeInfo: Invalid object size requested (0x%x) for object id %u. Ignoring.", spec->size, id + i);
4155 spec->size = OBJECT_SIZE_1X1;
4156 }
4157 break;
4158
4159 case 0x0D: // Build cost multipler
4160 spec->build_cost_multiplier = buf->ReadByte();
4161 spec->clear_cost_multiplier = spec->build_cost_multiplier;
4162 break;
4163
4164 case 0x0E: // Introduction date
4165 spec->introduction_date = buf->ReadDWord();
4166 break;
4167
4168 case 0x0F: // End of life
4169 spec->end_of_life_date = buf->ReadDWord();
4170 break;
4171
4172 case 0x10: // Flags
4173 spec->flags = (ObjectFlags)buf->ReadWord();
4174 _loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
4175 break;
4176
4177 case 0x11: // Animation info
4178 spec->animation.frames = buf->ReadByte();
4179 spec->animation.status = buf->ReadByte();
4180 break;
4181
4182 case 0x12: // Animation speed
4183 spec->animation.speed = buf->ReadByte();
4184 break;
4185
4186 case 0x13: // Animation triggers
4187 spec->animation.triggers = buf->ReadWord();
4188 break;
4189
4190 case 0x14: // Removal cost multiplier
4191 spec->clear_cost_multiplier = buf->ReadByte();
4192 break;
4193
4194 case 0x15: // Callback mask
4195 spec->callback_mask = buf->ReadWord();
4196 break;
4197
4198 case 0x16: // Building height
4199 spec->height = buf->ReadByte();
4200 break;
4201
4202 case 0x17: // Views
4203 spec->views = buf->ReadByte();
4204 if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4205 grfmsg(2, "ObjectChangeInfo: Invalid number of views (%u) for object id %u. Ignoring.", spec->views, id + i);
4206 spec->views = 1;
4207 }
4208 break;
4209
4210 case 0x18: // Amount placed on 256^2 map on map creation
4211 spec->generate_amount = buf->ReadByte();
4212 break;
4213
4214 default:
4215 ret = CIR_UNKNOWN;
4216 break;
4217 }
4218 }
4219
4220 return ret;
4221 }
4222
4231 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4232 {
4233 ChangeInfoResult ret = CIR_SUCCESS;
4234
4235 extern RailtypeInfo _railtypes[RAILTYPE_END];
4236
4237 if (id + numinfo > RAILTYPE_END) {
4238 grfmsg(1, "RailTypeChangeInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4239 return CIR_INVALID_ID;
4240 }
4241
4242 for (int i = 0; i < numinfo; i++) {
4243 RailType rt = _cur.grffile->railtype_map[id + i];
4244 if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4245
4246 RailtypeInfo *rti = &_railtypes[rt];
4247
4248 switch (prop) {
4249 case 0x08: // Label of rail type
4250 /* Skipped here as this is loaded during reservation stage. */
4251 buf->ReadDWord();
4252 break;
4253
4254 case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4255 uint16 str = buf->ReadWord();
4256 AddStringForMapping(str, &rti->strings.toolbar_caption);
4257 if (_cur.grffile->grf_version < 8) {
4258 AddStringForMapping(str, &rti->strings.name);
4259 }
4260 break;
4261 }
4262
4263 case 0x0A: // Menu text of railtype
4264 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4265 break;
4266
4267 case 0x0B: // Build window caption
4268 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4269 break;
4270
4271 case 0x0C: // Autoreplace text
4272 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4273 break;
4274
4275 case 0x0D: // New locomotive text
4276 AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
4277 break;
4278
4279 case 0x0E: // Compatible railtype list
4280 case 0x0F: // Powered railtype list
4281 case 0x18: // Railtype list required for date introduction
4282 case 0x19: // Introduced railtype list
4283 {
4284 /* Rail type compatibility bits are added to the existing bits
4285 * to allow multiple GRFs to modify compatibility with the
4286 * default rail types. */
4287 int n = buf->ReadByte();
4288 for (int j = 0; j != n; j++) {
4289 RailTypeLabel label = buf->ReadDWord();
4290 RailType rt = GetRailTypeByLabel(BSWAP32(label), false);
4291 if (rt != INVALID_RAILTYPE) {
4292 switch (prop) {
4293 case 0x0F: SetBit(rti->powered_railtypes, rt); FALLTHROUGH; // Powered implies compatible.
4294 case 0x0E: SetBit(rti->compatible_railtypes, rt); break;
4295 case 0x18: SetBit(rti->introduction_required_railtypes, rt); break;
4296 case 0x19: SetBit(rti->introduces_railtypes, rt); break;
4297 }
4298 }
4299 }
4300 break;
4301 }
4302
4303 case 0x10: // Rail Type flags
4304 rti->flags = (RailTypeFlags)buf->ReadByte();
4305 break;
4306
4307 case 0x11: // Curve speed advantage
4308 rti->curve_speed = buf->ReadByte();
4309 break;
4310
4311 case 0x12: // Station graphic
4312 rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
4313 break;
4314
4315 case 0x13: // Construction cost factor
4316 rti->cost_multiplier = buf->ReadWord();
4317 break;
4318
4319 case 0x14: // Speed limit
4320 rti->max_speed = buf->ReadWord();
4321 break;
4322
4323 case 0x15: // Acceleration model
4324 rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
4325 break;
4326
4327 case 0x16: // Map colour
4328 rti->map_colour = buf->ReadByte();
4329 break;
4330
4331 case 0x17: // Introduction date
4332 rti->introduction_date = buf->ReadDWord();
4333 break;
4334
4335 case 0x1A: // Sort order
4336 rti->sorting_order = buf->ReadByte();
4337 break;
4338
4339 case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4340 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4341 break;
4342
4343 case 0x1C: // Maintenance cost factor
4344 rti->maintenance_multiplier = buf->ReadWord();
4345 break;
4346
4347 case 0x1D: // Alternate rail type label list
4348 /* Skipped here as this is loaded during reservation stage. */
4349 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4350 break;
4351
4352 default:
4353 ret = CIR_UNKNOWN;
4354 break;
4355 }
4356 }
4357
4358 return ret;
4359 }
4360
4361 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4362 {
4363 ChangeInfoResult ret = CIR_SUCCESS;
4364
4365 extern RailtypeInfo _railtypes[RAILTYPE_END];
4366
4367 if (id + numinfo > RAILTYPE_END) {
4368 grfmsg(1, "RailTypeReserveInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4369 return CIR_INVALID_ID;
4370 }
4371
4372 for (int i = 0; i < numinfo; i++) {
4373 switch (prop) {
4374 case 0x08: // Label of rail type
4375 {
4376 RailTypeLabel rtl = buf->ReadDWord();
4377 rtl = BSWAP32(rtl);
4378
4379 RailType rt = GetRailTypeByLabel(rtl, false);
4380 if (rt == INVALID_RAILTYPE) {
4381 /* Set up new rail type */
4382 rt = AllocateRailType(rtl);
4383 }
4384
4385 _cur.grffile->railtype_map[id + i] = rt;
4386 break;
4387 }
4388
4389 case 0x09: // Toolbar caption of railtype
4390 case 0x0A: // Menu text
4391 case 0x0B: // Build window caption
4392 case 0x0C: // Autoreplace text
4393 case 0x0D: // New loco
4394 case 0x13: // Construction cost
4395 case 0x14: // Speed limit
4396 case 0x1B: // Name of railtype
4397 case 0x1C: // Maintenance cost factor
4398 buf->ReadWord();
4399 break;
4400
4401 case 0x1D: // Alternate rail type label list
4402 if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4403 int n = buf->ReadByte();
4404 for (int j = 0; j != n; j++) {
4405 _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4406 }
4407 break;
4408 }
4409 grfmsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type %u because no label was set", id + i);
4410 FALLTHROUGH;
4411
4412 case 0x0E: // Compatible railtype list
4413 case 0x0F: // Powered railtype list
4414 case 0x18: // Railtype list required for date introduction
4415 case 0x19: // Introduced railtype list
4416 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4417 break;
4418
4419 case 0x10: // Rail Type flags
4420 case 0x11: // Curve speed advantage
4421 case 0x12: // Station graphic
4422 case 0x15: // Acceleration model
4423 case 0x16: // Map colour
4424 case 0x1A: // Sort order
4425 buf->ReadByte();
4426 break;
4427
4428 case 0x17: // Introduction date
4429 buf->ReadDWord();
4430 break;
4431
4432 default:
4433 ret = CIR_UNKNOWN;
4434 break;
4435 }
4436 }
4437
4438 return ret;
4439 }
4440
4449 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4450 {
4451 ChangeInfoResult ret = CIR_SUCCESS;
4452
4453 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4454 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4455
4456 if (id + numinfo > ROADTYPE_END) {
4457 grfmsg(1, "RoadTypeChangeInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4458 return CIR_INVALID_ID;
4459 }
4460
4461 for (int i = 0; i < numinfo; i++) {
4462 RoadType rt = type_map[id + i];
4463 if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4464
4465 RoadTypeInfo *rti = &_roadtypes[rt];
4466
4467 switch (prop) {
4468 case 0x08: // Label of road type
4469 /* Skipped here as this is loaded during reservation stage. */
4470 buf->ReadDWord();
4471 break;
4472
4473 case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4474 uint16 str = buf->ReadWord();
4475 AddStringForMapping(str, &rti->strings.toolbar_caption);
4476 break;
4477 }
4478
4479 case 0x0A: // Menu text of roadtype
4480 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4481 break;
4482
4483 case 0x0B: // Build window caption
4484 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4485 break;
4486
4487 case 0x0C: // Autoreplace text
4488 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4489 break;
4490
4491 case 0x0D: // New engine text
4492 AddStringForMapping(buf->ReadWord(), &rti->strings.new_engine);
4493 break;
4494
4495 case 0x0F: // Powered roadtype list
4496 case 0x18: // Roadtype list required for date introduction
4497 case 0x19: { // Introduced roadtype list
4498 /* Road type compatibility bits are added to the existing bits
4499 * to allow multiple GRFs to modify compatibility with the
4500 * default road types. */
4501 int n = buf->ReadByte();
4502 for (int j = 0; j != n; j++) {
4503 RoadTypeLabel label = buf->ReadDWord();
4504 RoadType rt = GetRoadTypeByLabel(BSWAP32(label), false);
4505 if (rt != INVALID_ROADTYPE) {
4506 switch (prop) {
4507 case 0x0F: SetBit(rti->powered_roadtypes, rt); break;
4508 case 0x18: SetBit(rti->introduction_required_roadtypes, rt); break;
4509 case 0x19: SetBit(rti->introduces_roadtypes, rt); break;
4510 }
4511 }
4512 }
4513 break;
4514 }
4515
4516 case 0x10: // Road Type flags
4517 rti->flags = (RoadTypeFlags)buf->ReadByte();
4518 break;
4519
4520 case 0x13: // Construction cost factor
4521 rti->cost_multiplier = buf->ReadWord();
4522 break;
4523
4524 case 0x14: // Speed limit
4525 rti->max_speed = buf->ReadWord();
4526 break;
4527
4528 case 0x16: // Map colour
4529 rti->map_colour = buf->ReadByte();
4530 break;
4531
4532 case 0x17: // Introduction date
4533 rti->introduction_date = buf->ReadDWord();
4534 break;
4535
4536 case 0x1A: // Sort order
4537 rti->sorting_order = buf->ReadByte();
4538 break;
4539
4540 case 0x1B: // Name of roadtype
4541 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4542 break;
4543
4544 case 0x1C: // Maintenance cost factor
4545 rti->maintenance_multiplier = buf->ReadWord();
4546 break;
4547
4548 case 0x1D: // Alternate road type label list
4549 /* Skipped here as this is loaded during reservation stage. */
4550 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4551 break;
4552
4553 default:
4554 ret = CIR_UNKNOWN;
4555 break;
4556 }
4557 }
4558
4559 return ret;
4560 }
4561
4562 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4563 {
4564 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4565 }
4566
4567 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4568 {
4569 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4570 }
4571
4572
4573 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4574 {
4575 ChangeInfoResult ret = CIR_SUCCESS;
4576
4577 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4578 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4579
4580 if (id + numinfo > ROADTYPE_END) {
4581 grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4582 return CIR_INVALID_ID;
4583 }
4584
4585 for (int i = 0; i < numinfo; i++) {
4586 switch (prop) {
4587 case 0x08: { // Label of road type
4588 RoadTypeLabel rtl = buf->ReadDWord();
4589 rtl = BSWAP32(rtl);
4590
4591 RoadType rt = GetRoadTypeByLabel(rtl, false);
4592 if (rt == INVALID_ROADTYPE) {
4593 /* Set up new road type */
4594 rt = AllocateRoadType(rtl, rtt);
4595 } else if (GetRoadTramType(rt) != rtt) {
4596 grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid type (road/tram), ignoring", id + numinfo);
4597 return CIR_INVALID_ID;
4598 }
4599
4600 type_map[id + i] = rt;
4601 break;
4602 }
4603 case 0x09: // Toolbar caption of roadtype
4604 case 0x0A: // Menu text
4605 case 0x0B: // Build window caption
4606 case 0x0C: // Autoreplace text
4607 case 0x0D: // New loco
4608 case 0x13: // Construction cost
4609 case 0x14: // Speed limit
4610 case 0x1B: // Name of roadtype
4611 case 0x1C: // Maintenance cost factor
4612 buf->ReadWord();
4613 break;
4614
4615 case 0x1D: // Alternate road type label list
4616 if (type_map[id + i] != INVALID_ROADTYPE) {
4617 int n = buf->ReadByte();
4618 for (int j = 0; j != n; j++) {
4619 _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4620 }
4621 break;
4622 }
4623 grfmsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type %u because no label was set", id + i);
4624 /* FALL THROUGH */
4625
4626 case 0x0F: // Powered roadtype list
4627 case 0x18: // Roadtype list required for date introduction
4628 case 0x19: // Introduced roadtype list
4629 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4630 break;
4631
4632 case 0x10: // Road Type flags
4633 case 0x16: // Map colour
4634 case 0x1A: // Sort order
4635 buf->ReadByte();
4636 break;
4637
4638 case 0x17: // Introduction date
4639 buf->ReadDWord();
4640 break;
4641
4642 default:
4643 ret = CIR_UNKNOWN;
4644 break;
4645 }
4646 }
4647
4648 return ret;
4649 }
4650
4651 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4652 {
4653 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4654 }
4655
4656 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4657 {
4658 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4659 }
4660
4661 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader *buf)
4662 {
4663 ChangeInfoResult ret = CIR_SUCCESS;
4664
4665 if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4666 grfmsg(1, "AirportTileChangeInfo: Too many airport tiles loaded (%u), max (%u). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4667 return CIR_INVALID_ID;
4668 }
4669
4670 /* Allocate airport tile specs if they haven't been allocated already. */
4671 if (_cur.grffile->airtspec == nullptr) {
4672 _cur.grffile->airtspec = CallocT<AirportTileSpec*>(NUM_AIRPORTTILES_PER_GRF);
4673 }
4674
4675 for (int i = 0; i < numinfo; i++) {
4676 AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i];
4677
4678 if (prop != 0x08 && tsp == nullptr) {
4679 grfmsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile %u. Ignoring.", airtid + i);
4680 return CIR_INVALID_ID;
4681 }
4682
4683 switch (prop) {
4684 case 0x08: { // Substitute airport tile type
4685 AirportTileSpec **tilespec = &_cur.grffile->airtspec[airtid + i];
4686 byte subs_id = buf->ReadByte();
4687
4688 if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4689 /* The substitute id must be one of the original airport tiles. */
4690 grfmsg(2, "AirportTileChangeInfo: Attempt to use new airport tile %u as substitute airport tile for %u. Ignoring.", subs_id, airtid + i);
4691 continue;
4692 }
4693
4694 /* Allocate space for this airport tile. */
4695 if (*tilespec == nullptr) {
4696 *tilespec = CallocT<AirportTileSpec>(1);
4697 tsp = *tilespec;
4698
4699 memcpy(tsp, AirportTileSpec::Get(subs_id), sizeof(AirportTileSpec));
4700 tsp->enabled = true;
4701
4702 tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
4703
4704 tsp->grf_prop.local_id = airtid + i;
4705 tsp->grf_prop.subst_id = subs_id;
4706 tsp->grf_prop.grffile = _cur.grffile;
4707 _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4708 }
4709 break;
4710 }
4711
4712 case 0x09: { // Airport tile override
4713 byte override = buf->ReadByte();
4714
4715 /* The airport tile being overridden must be an original airport tile. */
4716 if (override >= NEW_AIRPORTTILE_OFFSET) {
4717 grfmsg(2, "AirportTileChangeInfo: Attempt to override new airport tile %u with airport tile id %u. Ignoring.", override, airtid + i);
4718 continue;
4719 }
4720
4721 _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4722 break;
4723 }
4724
4725 case 0x0E: // Callback mask
4726 tsp->callback_mask = buf->ReadByte();
4727 break;
4728
4729 case 0x0F: // Animation information
4730 tsp->animation.frames = buf->ReadByte();
4731 tsp->animation.status = buf->ReadByte();
4732 break;
4733
4734 case 0x10: // Animation speed
4735 tsp->animation.speed = buf->ReadByte();
4736 break;
4737
4738 case 0x11: // Animation triggers
4739 tsp->animation.triggers = buf->ReadByte();
4740 break;
4741
4742 default:
4743 ret = CIR_UNKNOWN;
4744 break;
4745 }
4746 }
4747
4748 return ret;
4749 }
4750
4751 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8 feature, uint8 property)
4752 {
4753 switch (cir) {
4754 default: NOT_REACHED();
4755
4756 case CIR_DISABLED:
4757 /* Error has already been printed; just stop parsing */
4758 return true;
4759
4760 case CIR_SUCCESS:
4761 return false;
4762
4763 case CIR_UNHANDLED:
4764 grfmsg(1, "%s: Ignoring property 0x%02X of feature 0x%02X (not implemented)", caller, property, feature);
4765 return false;
4766
4767 case CIR_UNKNOWN:
4768 grfmsg(0, "%s: Unknown property 0x%02X of feature 0x%02X, disabling", caller, property, feature);
4769 FALLTHROUGH;
4770
4771 case CIR_INVALID_ID: {
4772 /* No debug message for an invalid ID, as it has already been output */
4773 GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4774 if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4775 return true;
4776 }
4777 }
4778 }
4779
4780 /* Action 0x00 */
4781 static void FeatureChangeInfo(ByteReader *buf)
4782 {
4783 /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4784 *
4785 * B feature
4786 * B num-props how many properties to change per vehicle/station
4787 * B num-info how many vehicles/stations to change
4788 * E id ID of first vehicle/station to change, if num-info is
4789 * greater than one, this one and the following
4790 * vehicles/stations will be changed
4791 * B property what property to change, depends on the feature
4792 * V new-info new bytes of info (variable size; depends on properties) */
4793
4794 static const VCI_Handler handler[] = {
4795 /* GSF_TRAINS */ RailVehicleChangeInfo,
4796 /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4797 /* GSF_SHIPS */ ShipVehicleChangeInfo,
4798 /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4799 /* GSF_STATIONS */ StationChangeInfo,
4800 /* GSF_CANALS */ CanalChangeInfo,
4801 /* GSF_BRIDGES */ BridgeChangeInfo,
4802 /* GSF_HOUSES */ TownHouseChangeInfo,
4803 /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4804 /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4805 /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4806 /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4807 /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4808 /* GSF_AIRPORTS */ AirportChangeInfo,
4809 /* GSF_SIGNALS */ nullptr,
4810 /* GSF_OBJECTS */ ObjectChangeInfo,
4811 /* GSF_RAILTYPES */ RailTypeChangeInfo,
4812 /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4813 /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4814 /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4815 };
4816 static_assert(GSF_END == lengthof(handler));
4817
4818 uint8 feature = buf->ReadByte();
4819 uint8 numprops = buf->ReadByte();
4820 uint numinfo = buf->ReadByte();
4821 uint engine = buf->ReadExtendedByte();
4822
4823 if (feature >= GSF_END) {
4824 grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4825 return;
4826 }
4827
4828 grfmsg(6, "FeatureChangeInfo: Feature 0x%02X, %d properties, to apply to %d+%d",
4829 feature, numprops, engine, numinfo);
4830
4831 if (handler[feature] == nullptr) {
4832 if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4833 return;
4834 }
4835
4836 /* Mark the feature as used by the grf */
4837 SetBit(_cur.grffile->grf_features, feature);
4838
4839 while (numprops-- && buf->HasData()) {
4840 uint8 prop = buf->ReadByte();
4841
4842 ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4843 if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4844 }
4845 }
4846
4847 /* Action 0x00 (GLS_SAFETYSCAN) */
4848 static void SafeChangeInfo(ByteReader *buf)
4849 {
4850 uint8 feature = buf->ReadByte();
4851 uint8 numprops = buf->ReadByte();
4852 uint numinfo = buf->ReadByte();
4853 buf->ReadExtendedByte(); // id
4854
4855 if (feature == GSF_BRIDGES && numprops == 1) {
4856 uint8 prop = buf->ReadByte();
4857 /* Bridge property 0x0D is redefinition of sprite layout tables, which
4858 * is considered safe. */
4859 if (prop == 0x0D) return;
4860 } else if (feature == GSF_GLOBALVAR && numprops == 1) {
4861 uint8 prop = buf->ReadByte();
4862 /* Engine ID Mappings are safe, if the source is static */
4863 if (prop == 0x11) {
4864 bool is_safe = true;
4865 for (uint i = 0; i < numinfo; i++) {
4866 uint32 s = buf->ReadDWord();
4867 buf->ReadDWord(); // dest
4868 const GRFConfig *grfconfig = GetGRFConfig(s);
4869 if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
4870 is_safe = false;
4871 break;
4872 }
4873 }
4874 if (is_safe) return;
4875 }
4876 }
4877
4878 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
4879
4880 /* Skip remainder of GRF */
4881 _cur.skip_sprites = -1;
4882 }
4883
4884 /* Action 0x00 (GLS_RESERVE) */
4885 static void ReserveChangeInfo(ByteReader *buf)
4886 {
4887 uint8 feature = buf->ReadByte();
4888
4889 if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
4890
4891 uint8 numprops = buf->ReadByte();
4892 uint8 numinfo = buf->ReadByte();
4893 uint8 index = buf->ReadExtendedByte();
4894
4895 while (numprops-- && buf->HasData()) {
4896 uint8 prop = buf->ReadByte();
4897 ChangeInfoResult cir = CIR_SUCCESS;
4898
4899 switch (feature) {
4900 default: NOT_REACHED();
4901 case GSF_CARGOES:
4902 cir = CargoChangeInfo(index, numinfo, prop, buf);
4903 break;
4904
4905 case GSF_GLOBALVAR:
4906 cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
4907 break;
4908
4909 case GSF_RAILTYPES:
4910 cir = RailTypeReserveInfo(index, numinfo, prop, buf);
4911 break;
4912
4913 case GSF_ROADTYPES:
4914 cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
4915 break;
4916
4917 case GSF_TRAMTYPES:
4918 cir = TramTypeReserveInfo(index, numinfo, prop, buf);
4919 break;
4920 }
4921
4922 if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
4923 }
4924 }
4925
4926 /* Action 0x01 */
4927 static void NewSpriteSet(ByteReader *buf)
4928 {
4929 /* Basic format: <01> <feature> <num-sets> <num-ent>
4930 * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
4931 *
4932 * B feature feature to define sprites for
4933 * 0, 1, 2, 3: veh-type, 4: train stations
4934 * E first-set first sprite set to define
4935 * B num-sets number of sprite sets (extended byte in extended format)
4936 * E num-ent how many entries per sprite set
4937 * For vehicles, this is the number of different
4938 * vehicle directions in each sprite set
4939 * Set num-dirs=8, unless your sprites are symmetric.
4940 * In that case, use num-dirs=4.
4941 */
4942
4943 uint8 feature = buf->ReadByte();
4944 uint16 num_sets = buf->ReadByte();
4945 uint16 first_set = 0;
4946
4947 if (num_sets == 0 && buf->HasData(3)) {
4948 /* Extended Action1 format.
4949 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4950 first_set = buf->ReadExtendedByte();
4951 num_sets = buf->ReadExtendedByte();
4952 }
4953 uint16 num_ents = buf->ReadExtendedByte();
4954
4955 if (feature >= GSF_END) {
4956 _cur.skip_sprites = num_sets * num_ents;
4957 grfmsg(1, "NewSpriteSet: Unsupported feature 0x%02X, skipping %d sprites", feature, _cur.skip_sprites);
4958 return;
4959 }
4960
4961 _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
4962
4963 grfmsg(7, "New sprite set at %d of feature 0x%02X, consisting of %d sets with %d views each (total %d)",
4964 _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
4965 );
4966
4967 for (int i = 0; i < num_sets * num_ents; i++) {
4968 _cur.nfo_line++;
4969 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
4970 }
4971 }
4972
4973 /* Action 0x01 (SKIP) */
4974 static void SkipAct1(ByteReader *buf)
4975 {
4976 buf->ReadByte();
4977 uint16 num_sets = buf->ReadByte();
4978
4979 if (num_sets == 0 && buf->HasData(3)) {
4980 /* Extended Action1 format.
4981 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4982 buf->ReadExtendedByte(); // first_set
4983 num_sets = buf->ReadExtendedByte();
4984 }
4985 uint16 num_ents = buf->ReadExtendedByte();
4986
4987 _cur.skip_sprites = num_sets * num_ents;
4988
4989 grfmsg(3, "SkipAct1: Skipping %d sprites", _cur.skip_sprites);
4990 }
4991
4992 /* Helper function to either create a callback or link to a previously
4993 * defined spritegroup. */
4994 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 groupid)
4995 {
4996 if (HasBit(groupid, 15)) {
4997 assert(CallbackResultSpriteGroup::CanAllocateItem());
4998 return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
4999 }
5000
5001 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5002 grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
5003 return nullptr;
5004 }
5005
5006 return _cur.spritegroups[groupid];
5007 }
5008
5017 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
5018 {
5019 if (HasBit(spriteid, 15)) {
5020 assert(CallbackResultSpriteGroup::CanAllocateItem());
5021 return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
5022 }
5023
5024 if (!_cur.IsValidSpriteSet(feature, spriteid)) {
5025 grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
5026 return nullptr;
5027 }
5028
5029 SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
5030 uint num_sprites = _cur.GetNumEnts(feature, spriteid);
5031
5032 /* Ensure that the sprites are loeded */
5033 assert(spriteset_start + num_sprites <= _cur.spriteid);
5034
5035 assert(ResultSpriteGroup::CanAllocateItem());
5036 return new ResultSpriteGroup(spriteset_start, num_sprites);
5037 }
5038
5039 /* Action 0x02 */
5040 static void NewSpriteGroup(ByteReader *buf)
5041 {
5042 /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5043 *
5044 * B feature see action 1
5045 * B set-id ID of this particular definition
5046 * B type/num-entries
5047 * if 80 or greater, this is a randomized or variational
5048 * list definition, see below
5049 * otherwise it specifies a number of entries, the exact
5050 * meaning depends on the feature
5051 * V feature-specific-data (huge mess, don't even look it up --pasky) */
5052 const SpriteGroup *act_group = nullptr;
5053
5054 uint8 feature = buf->ReadByte();
5055 if (feature >= GSF_END) {
5056 grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5057 return;
5058 }
5059
5060 uint8 setid = buf->ReadByte();
5061 uint8 type = buf->ReadByte();
5062
5063 /* Sprite Groups are created here but they are allocated from a pool, so
5064 * we do not need to delete anything if there is an exception from the
5065 * ByteReader. */
5066
5067 switch (type) {
5068 /* Deterministic Sprite Group */
5069 case 0x81: // Self scope, byte
5070 case 0x82: // Parent scope, byte
5071 case 0x85: // Self scope, word
5072 case 0x86: // Parent scope, word
5073 case 0x89: // Self scope, dword
5074 case 0x8A: // Parent scope, dword
5075 {
5076 byte varadjust;
5077 byte varsize;
5078
5079 assert(DeterministicSpriteGroup::CanAllocateItem());
5080 DeterministicSpriteGroup *group = new DeterministicSpriteGroup();
5081 group->nfo_line = _cur.nfo_line;
5082 act_group = group;
5083 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5084
5085 switch (GB(type, 2, 2)) {
5086 default: NOT_REACHED();
5087 case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5088 case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5089 case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5090 }
5091
5092 /* Loop through the var adjusts. Unfortunately we don't know how many we have
5093 * from the outset, so we shall have to keep reallocing. */
5094 do {
5095 DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5096
5097 /* The first var adjust doesn't have an operation specified, so we set it to add. */
5098 adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
5099 adjust.variable = buf->ReadByte();
5100 if (adjust.variable == 0x7E) {
5101 /* Link subroutine group */
5102 adjust.subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
5103 } else {
5104 adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf->ReadByte() : 0;
5105 }
5106
5107 varadjust = buf->ReadByte();
5108 adjust.shift_num = GB(varadjust, 0, 5);
5109 adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5110 adjust.and_mask = buf->ReadVarSize(varsize);
5111
5112 if (adjust.type != DSGA_TYPE_NONE) {
5113 adjust.add_val = buf->ReadVarSize(varsize);
5114 adjust.divmod_val = buf->ReadVarSize(varsize);
5115 } else {
5116 adjust.add_val = 0;
5117 adjust.divmod_val = 0;
5118 }
5119
5120 /* Continue reading var adjusts while bit 5 is set. */
5121 } while (HasBit(varadjust, 5));
5122
5123 std::vector<DeterministicSpriteGroupRange> ranges;
5124 ranges.resize(buf->ReadByte());
5125 for (uint i = 0; i < ranges.size(); i++) {
5126 ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5127 ranges[i].low = buf->ReadVarSize(varsize);
5128 ranges[i].high = buf->ReadVarSize(varsize);
5129 }
5130
5131 group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5132 group->error_group = ranges.size() > 0 ? ranges[0].group : group->default_group;
5133 /* nvar == 0 is a special case -- we turn our value into a callback result */
5134 group->calculated_result = ranges.size() == 0;
5135
5136 /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5137 std::vector<uint32> bounds;
5138 for (uint i = 0; i < ranges.size(); i++) {
5139 bounds.push_back(ranges[i].low);
5140 if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
5141 }
5142 std::sort(bounds.begin(), bounds.end());
5143 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5144
5145 std::vector<const SpriteGroup *> target;
5146 for (uint j = 0; j < bounds.size(); ++j) {
5147 uint32 v = bounds[j];
5148 const SpriteGroup *t = group->default_group;
5149 for (uint i = 0; i < ranges.size(); i++) {
5150 if (ranges[i].low <= v && v <= ranges[i].high) {
5151 t = ranges[i].group;
5152 break;
5153 }
5154 }
5155 target.push_back(t);
5156 }
5157 assert(target.size() == bounds.size());
5158
5159 for (uint j = 0; j < bounds.size(); ) {
5160 if (target[j] != group->default_group) {
5161 DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5162 r.group = target[j];
5163 r.low = bounds[j];
5164 while (j < bounds.size() && target[j] == r.group) {
5165 j++;
5166 }
5167 r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5168 } else {
5169 j++;
5170 }
5171 }
5172
5173 break;
5174 }
5175
5176 /* Randomized Sprite Group */
5177 case 0x80: // Self scope
5178 case 0x83: // Parent scope
5179 case 0x84: // Relative scope
5180 {
5181 assert(RandomizedSpriteGroup::CanAllocateItem());
5182 RandomizedSpriteGroup *group = new RandomizedSpriteGroup();
5183 group->nfo_line = _cur.nfo_line;
5184 act_group = group;
5185 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5186
5187 if (HasBit(type, 2)) {
5188 if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5189 group->count = buf->ReadByte();
5190 }
5191
5192 uint8 triggers = buf->ReadByte();
5193 group->triggers = GB(triggers, 0, 7);
5194 group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5195 group->lowest_randbit = buf->ReadByte();
5196
5197 byte num_groups = buf->ReadByte();
5198 if (!HasExactlyOneBit(num_groups)) {
5199 grfmsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5200 }
5201
5202 for (uint i = 0; i < num_groups; i++) {
5203 group->groups.push_back(GetGroupFromGroupID(setid, type, buf->ReadWord()));
5204 }
5205
5206 break;
5207 }
5208
5209 /* Neither a variable or randomized sprite group... must be a real group */
5210 default:
5211 {
5212 switch (feature) {
5213 case GSF_TRAINS:
5214 case GSF_ROADVEHICLES:
5215 case GSF_SHIPS:
5216 case GSF_AIRCRAFT:
5217 case GSF_STATIONS:
5218 case GSF_CANALS:
5219 case GSF_CARGOES:
5220 case GSF_AIRPORTS:
5221 case GSF_RAILTYPES:
5222 case GSF_ROADTYPES:
5223 case GSF_TRAMTYPES:
5224 {
5225 byte num_loaded = type;
5226 byte num_loading = buf->ReadByte();
5227
5228 if (!_cur.HasValidSpriteSets(feature)) {
5229 grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5230 return;
5231 }
5232
5233 grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u loaded, %u loading",
5234 setid, num_loaded, num_loading);
5235
5236 if (num_loaded + num_loading == 0) {
5237 grfmsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5238 break;
5239 }
5240
5241 if (num_loaded + num_loading == 1) {
5242 /* Avoid creating 'Real' sprite group if only one option. */
5243 uint16 spriteid = buf->ReadWord();
5244 act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5245 grfmsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset %u", spriteid);
5246 break;
5247 }
5248
5249 std::vector<uint16> loaded;
5250 std::vector<uint16> loading;
5251
5252 for (uint i = 0; i < num_loaded; i++) {
5253 loaded.push_back(buf->ReadWord());
5254 grfmsg(8, "NewSpriteGroup: + rg->loaded[%i] = subset %u", i, loaded[i]);
5255 }
5256
5257 for (uint i = 0; i < num_loading; i++) {
5258 loading.push_back(buf->ReadWord());
5259 grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, loading[i]);
5260 }
5261
5262 if (std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end() &&
5263 std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end() &&
5264 loaded[0] == loading[0])
5265 {
5266 /* Both lists only contain the same value, so don't create 'Real' sprite group */
5267 act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5268 grfmsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset %u", loaded[0]);
5269 break;
5270 }
5271
5272 assert(RealSpriteGroup::CanAllocateItem());
5273 RealSpriteGroup *group = new RealSpriteGroup();
5274 group->nfo_line = _cur.nfo_line;
5275 act_group = group;
5276
5277 for (uint16 spriteid : loaded) {
5278 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5279 group->loaded.push_back(t);
5280 }
5281
5282 for (uint16 spriteid : loading) {
5283 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5284 group->loading.push_back(t);
5285 }
5286
5287 break;
5288 }
5289
5290 case GSF_HOUSES:
5291 case GSF_AIRPORTTILES:
5292 case GSF_OBJECTS:
5293 case GSF_INDUSTRYTILES: {
5294 byte num_building_sprites = std::max((uint8)1, type);
5295
5296 assert(TileLayoutSpriteGroup::CanAllocateItem());
5297 TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup();
5298 group->nfo_line = _cur.nfo_line;
5299 act_group = group;
5300
5301 /* On error, bail out immediately. Temporary GRF data was already freed */
5302 if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5303 break;
5304 }
5305
5306 case GSF_INDUSTRIES: {
5307 if (type > 2) {
5308 grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
5309 break;
5310 }
5311
5312 assert(IndustryProductionSpriteGroup::CanAllocateItem());
5313 IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup();
5314 group->nfo_line = _cur.nfo_line;
5315 act_group = group;
5316 group->version = type;
5317 if (type == 0) {
5318 group->num_input = 3;
5319 for (uint i = 0; i < 3; i++) {
5320 group->subtract_input[i] = (int16)buf->ReadWord(); // signed
5321 }
5322 group->num_output = 2;
5323 for (uint i = 0; i < 2; i++) {
5324 group->add_output[i] = buf->ReadWord(); // unsigned
5325 }
5326 group->again = buf->ReadByte();
5327 } else if (type == 1) {
5328 group->num_input = 3;
5329 for (uint i = 0; i < 3; i++) {
5330 group->subtract_input[i] = buf->ReadByte();
5331 }
5332 group->num_output = 2;
5333 for (uint i = 0; i < 2; i++) {
5334 group->add_output[i] = buf->ReadByte();
5335 }
5336 group->again = buf->ReadByte();
5337 } else if (type == 2) {
5338 group->num_input = buf->ReadByte();
5339 if (group->num_input > lengthof(group->subtract_input)) {
5340 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5341 error->data = "too many inputs (max 16)";
5342 return;
5343 }
5344 for (uint i = 0; i < group->num_input; i++) {
5345 byte rawcargo = buf->ReadByte();
5346 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5347 if (cargo == CT_INVALID) {
5348 /* The mapped cargo is invalid. This is permitted at this point,
5349 * as long as the result is not used. Mark it invalid so this
5350 * can be tested later. */
5351 group->version = 0xFF;
5352 } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5353 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5354 error->data = "duplicate input cargo";
5355 return;
5356 }
5357 group->cargo_input[i] = cargo;
5358 group->subtract_input[i] = buf->ReadByte();
5359 }
5360 group->num_output = buf->ReadByte();
5361 if (group->num_output > lengthof(group->add_output)) {
5362 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5363 error->data = "too many outputs (max 16)";
5364 return;
5365 }
5366 for (uint i = 0; i < group->num_output; i++) {
5367 byte rawcargo = buf->ReadByte();
5368 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5369 if (cargo == CT_INVALID) {
5370 /* Mark this result as invalid to use */
5371 group->version = 0xFF;
5372 } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5373 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5374 error->data = "duplicate output cargo";
5375 return;
5376 }
5377 group->cargo_output[i] = cargo;
5378 group->add_output[i] = buf->ReadByte();
5379 }
5380 group->again = buf->ReadByte();
5381 } else {
5382 NOT_REACHED();
5383 }
5384 break;
5385 }
5386
5387 /* Loading of Tile Layout and Production Callback groups would happen here */
5388 default: grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5389 }
5390 }
5391 }
5392
5393 _cur.spritegroups[setid] = act_group;
5394 }
5395
5396 static CargoID TranslateCargo(uint8 feature, uint8 ctype)
5397 {
5398 if (feature == GSF_OBJECTS) {
5399 switch (ctype) {
5400 case 0: return 0;
5401 case 0xFF: return CT_PURCHASE_OBJECT;
5402 default:
5403 grfmsg(1, "TranslateCargo: Invalid cargo bitnum %d for objects, skipping.", ctype);
5404 return CT_INVALID;
5405 }
5406 }
5407 /* Special cargo types for purchase list and stations */
5408 if (feature == GSF_STATIONS && ctype == 0xFE) return CT_DEFAULT_NA;
5409 if (ctype == 0xFF) return CT_PURCHASE;
5410
5411 if (_cur.grffile->cargo_list.size() == 0) {
5412 /* No cargo table, so use bitnum values */
5413 if (ctype >= 32) {
5414 grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
5415 return CT_INVALID;
5416 }
5417
5418 for (const CargoSpec *cs : CargoSpec::Iterate()) {
5419 if (cs->bitnum == ctype) {
5420 grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, cs->Index());
5421 return cs->Index();
5422 }
5423 }
5424
5425 grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
5426 return CT_INVALID;
5427 }
5428
5429 /* Check if the cargo type is out of bounds of the cargo translation table */
5430 if (ctype >= _cur.grffile->cargo_list.size()) {
5431 grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5432 return CT_INVALID;
5433 }
5434
5435 /* Look up the cargo label from the translation table */
5436 CargoLabel cl = _cur.grffile->cargo_list[ctype];
5437 if (cl == 0) {
5438 grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
5439 return CT_INVALID;
5440 }
5441
5442 ctype = GetCargoIDByLabel(cl);
5443 if (ctype == CT_INVALID) {
5444 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));
5445 return CT_INVALID;
5446 }
5447
5448 grfmsg(6, "TranslateCargo: Cargo '%c%c%c%c' mapped to cargo type %d.", GB(cl, 24, 8), GB(cl, 16, 8), GB(cl, 8, 8), GB(cl, 0, 8), ctype);
5449 return ctype;
5450 }
5451
5452
5453 static bool IsValidGroupID(uint16 groupid, const char *function)
5454 {
5455 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5456 grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
5457 return false;
5458 }
5459
5460 return true;
5461 }
5462
5463 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
5464 {
5465 static EngineID *last_engines;
5466 static uint last_engines_count;
5467 bool wagover = false;
5468
5469 /* Test for 'wagon override' flag */
5470 if (HasBit(idcount, 7)) {
5471 wagover = true;
5472 /* Strip off the flag */
5473 idcount = GB(idcount, 0, 7);
5474
5475 if (last_engines_count == 0) {
5476 grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5477 return;
5478 }
5479
5480 grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
5481 last_engines_count, idcount);
5482 } else {
5483 if (last_engines_count != idcount) {
5484 last_engines = ReallocT(last_engines, idcount);
5485 last_engines_count = idcount;
5486 }
5487 }
5488
5489 EngineID *engines = AllocaM(EngineID, idcount);
5490 for (uint i = 0; i < idcount; i++) {
5491 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5492 if (e == nullptr) {
5493 /* No engine could be allocated?!? Deal with it. Okay,
5494 * this might look bad. Also make sure this NewGRF
5495 * gets disabled, as a half loaded one is bad. */
5496 HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5497 return;
5498 }
5499
5500 engines[i] = e->index;
5501 if (!wagover) last_engines[i] = engines[i];
5502 }
5503
5504 uint8 cidcount = buf->ReadByte();
5505 for (uint c = 0; c < cidcount; c++) {
5506 uint8 ctype = buf->ReadByte();
5507 uint16 groupid = buf->ReadWord();
5508 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5509
5510 grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
5511
5512 ctype = TranslateCargo(feature, ctype);
5513 if (ctype == CT_INVALID) continue;
5514
5515 for (uint i = 0; i < idcount; i++) {
5516 EngineID engine = engines[i];
5517
5518 grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
5519
5520 if (wagover) {
5521 SetWagonOverrideSprites(engine, ctype, _cur.spritegroups[groupid], last_engines, last_engines_count);
5522 } else {
5523 SetCustomEngineSprites(engine, ctype, _cur.spritegroups[groupid]);
5524 }
5525 }
5526 }
5527
5528 uint16 groupid = buf->ReadWord();
5529 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5530
5531 grfmsg(8, "-- Default group id 0x%04X", groupid);
5532
5533 for (uint i = 0; i < idcount; i++) {
5534 EngineID engine = engines[i];
5535
5536 if (wagover) {
5537 SetWagonOverrideSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5538 } else {
5539 SetCustomEngineSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid]);
5540 SetEngineGRF(engine, _cur.grffile);
5541 }
5542 }
5543 }
5544
5545
5546 static void CanalMapSpriteGroup(ByteReader *buf, uint8 idcount)
5547 {
5548 CanalFeature *cfs = AllocaM(CanalFeature, idcount);
5549 for (uint i = 0; i < idcount; i++) {
5550 cfs[i] = (CanalFeature)buf->ReadByte();
5551 }
5552
5553 uint8 cidcount = buf->ReadByte();
5554 buf->Skip(cidcount * 3);
5555
5556 uint16 groupid = buf->ReadWord();
5557 if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5558
5559 for (uint i = 0; i < idcount; i++) {
5560 CanalFeature cf = cfs[i];
5561
5562 if (cf >= CF_END) {
5563 grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
5564 continue;
5565 }
5566
5567 _water_feature[cf].grffile = _cur.grffile;
5568 _water_feature[cf].group = _cur.spritegroups[groupid];
5569 }
5570 }
5571
5572
5573 static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
5574 {
5575 if (_cur.grffile->stations == nullptr) {
5576 grfmsg(1, "StationMapSpriteGroup: No stations defined, skipping");
5577 return;
5578 }
5579
5580 uint8 *stations = AllocaM(uint8, idcount);
5581 for (uint i = 0; i < idcount; i++) {
5582 stations[i] = buf->ReadByte();
5583 }
5584
5585 uint8 cidcount = buf->ReadByte();
5586 for (uint c = 0; c < cidcount; c++) {
5587 uint8 ctype = buf->ReadByte();
5588 uint16 groupid = buf->ReadWord();
5589 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5590
5591 ctype = TranslateCargo(GSF_STATIONS, ctype);
5592 if (ctype == CT_INVALID) continue;
5593
5594 for (uint i = 0; i < idcount; i++) {
5595 StationSpec *statspec = stations[i] >= NUM_STATIONS_PER_GRF ? nullptr : _cur.grffile->stations[stations[i]];
5596
5597 if (statspec == nullptr) {
5598 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5599 continue;
5600 }
5601
5602 statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5603 }
5604 }
5605
5606 uint16 groupid = buf->ReadWord();
5607 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5608
5609 for (uint i = 0; i < idcount; i++) {
5610 StationSpec *statspec = stations[i] >= NUM_STATIONS_PER_GRF ? nullptr : _cur.grffile->stations[stations[i]];
5611
5612 if (statspec == nullptr) {
5613 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5614 continue;
5615 }
5616
5617 if (statspec->grf_prop.grffile != nullptr) {
5618 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X mapped multiple times, skipping", stations[i]);
5619 continue;
5620 }
5621
5622 statspec->grf_prop.spritegroup[CT_DEFAULT] = _cur.spritegroups[groupid];
5623 statspec->grf_prop.grffile = _cur.grffile;
5624 statspec->grf_prop.local_id = stations[i];
5625 StationClass::Assign(statspec);
5626 }
5627 }
5628
5629
5630 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
5631 {
5632 if (_cur.grffile->housespec == nullptr) {
5633 grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5634 return;
5635 }
5636
5637 uint8 *houses = AllocaM(uint8, idcount);
5638 for (uint i = 0; i < idcount; i++) {
5639 houses[i] = buf->ReadByte();
5640 }
5641
5642 /* Skip the cargo type section, we only care about the default group */
5643 uint8 cidcount = buf->ReadByte();
5644 buf->Skip(cidcount * 3);
5645
5646 uint16 groupid = buf->ReadWord();
5647 if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5648
5649 for (uint i = 0; i < idcount; i++) {
5650 HouseSpec *hs = houses[i] >= NUM_HOUSES_PER_GRF ? nullptr : _cur.grffile->housespec[houses[i]];
5651
5652 if (hs == nullptr) {
5653 grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
5654 continue;
5655 }
5656
5657 hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5658 }
5659 }
5660
5661 static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
5662 {
5663 if (_cur.grffile->industryspec == nullptr) {
5664 grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5665 return;
5666 }
5667
5668 uint8 *industries = AllocaM(uint8, idcount);
5669 for (uint i = 0; i < idcount; i++) {
5670 industries[i] = buf->ReadByte();
5671 }
5672
5673 /* Skip the cargo type section, we only care about the default group */
5674 uint8 cidcount = buf->ReadByte();
5675 buf->Skip(cidcount * 3);
5676
5677 uint16 groupid = buf->ReadWord();
5678 if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5679
5680 for (uint i = 0; i < idcount; i++) {
5681 IndustrySpec *indsp = industries[i] >= NUM_INDUSTRYTYPES_PER_GRF ? nullptr : _cur.grffile->industryspec[industries[i]];
5682
5683 if (indsp == nullptr) {
5684 grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
5685 continue;
5686 }
5687
5688 indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5689 }
5690 }
5691
5692 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5693 {
5694 if (_cur.grffile->indtspec == nullptr) {
5695 grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5696 return;
5697 }
5698
5699 uint8 *indtiles = AllocaM(uint8, idcount);
5700 for (uint i = 0; i < idcount; i++) {
5701 indtiles[i] = buf->ReadByte();
5702 }
5703
5704 /* Skip the cargo type section, we only care about the default group */
5705 uint8 cidcount = buf->ReadByte();
5706 buf->Skip(cidcount * 3);
5707
5708 uint16 groupid = buf->ReadWord();
5709 if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5710
5711 for (uint i = 0; i < idcount; i++) {
5712 IndustryTileSpec *indtsp = indtiles[i] >= NUM_INDUSTRYTILES_PER_GRF ? nullptr : _cur.grffile->indtspec[indtiles[i]];
5713
5714 if (indtsp == nullptr) {
5715 grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
5716 continue;
5717 }
5718
5719 indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5720 }
5721 }
5722
5723 static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
5724 {
5725 CargoID *cargoes = AllocaM(CargoID, idcount);
5726 for (uint i = 0; i < idcount; i++) {
5727 cargoes[i] = buf->ReadByte();
5728 }
5729
5730 /* Skip the cargo type section, we only care about the default group */
5731 uint8 cidcount = buf->ReadByte();
5732 buf->Skip(cidcount * 3);
5733
5734 uint16 groupid = buf->ReadWord();
5735 if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5736
5737 for (uint i = 0; i < idcount; i++) {
5738 CargoID cid = cargoes[i];
5739
5740 if (cid >= NUM_CARGO) {
5741 grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
5742 continue;
5743 }
5744
5745 CargoSpec *cs = CargoSpec::Get(cid);
5746 cs->grffile = _cur.grffile;
5747 cs->group = _cur.spritegroups[groupid];
5748 }
5749 }
5750
5751 static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
5752 {
5753 if (_cur.grffile->objectspec == nullptr) {
5754 grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5755 return;
5756 }
5757
5758 uint8 *objects = AllocaM(uint8, idcount);
5759 for (uint i = 0; i < idcount; i++) {
5760 objects[i] = buf->ReadByte();
5761 }
5762
5763 uint8 cidcount = buf->ReadByte();
5764 for (uint c = 0; c < cidcount; c++) {
5765 uint8 ctype = buf->ReadByte();
5766 uint16 groupid = buf->ReadWord();
5767 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5768
5769 ctype = TranslateCargo(GSF_OBJECTS, ctype);
5770 if (ctype == CT_INVALID) continue;
5771
5772 for (uint i = 0; i < idcount; i++) {
5773 ObjectSpec *spec = objects[i] >= NUM_OBJECTS_PER_GRF ? nullptr : _cur.grffile->objectspec[objects[i]];
5774
5775 if (spec == nullptr) {
5776 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5777 continue;
5778 }
5779
5780 spec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5781 }
5782 }
5783
5784 uint16 groupid = buf->ReadWord();
5785 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5786
5787 for (uint i = 0; i < idcount; i++) {
5788 ObjectSpec *spec = objects[i] >= NUM_OBJECTS_PER_GRF ? nullptr : _cur.grffile->objectspec[objects[i]];
5789
5790 if (spec == nullptr) {
5791 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5792 continue;
5793 }
5794
5795 if (spec->grf_prop.grffile != nullptr) {
5796 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X mapped multiple times, skipping", objects[i]);
5797 continue;
5798 }
5799
5800 spec->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5801 spec->grf_prop.grffile = _cur.grffile;
5802 spec->grf_prop.local_id = objects[i];
5803 }
5804 }
5805
5806 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8 idcount)
5807 {
5808 uint8 *railtypes = AllocaM(uint8, idcount);
5809 for (uint i = 0; i < idcount; i++) {
5810 uint8 id = buf->ReadByte();
5811 railtypes[i] = id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE;
5812 }
5813
5814 uint8 cidcount = buf->ReadByte();
5815 for (uint c = 0; c < cidcount; c++) {
5816 uint8 ctype = buf->ReadByte();
5817 uint16 groupid = buf->ReadWord();
5818 if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5819
5820 if (ctype >= RTSG_END) continue;
5821
5822 extern RailtypeInfo _railtypes[RAILTYPE_END];
5823 for (uint i = 0; i < idcount; i++) {
5824 if (railtypes[i] != INVALID_RAILTYPE) {
5825 RailtypeInfo *rti = &_railtypes[railtypes[i]];
5826
5827 rti->grffile[ctype] = _cur.grffile;
5828 rti->group[ctype] = _cur.spritegroups[groupid];
5829 }
5830 }
5831 }
5832
5833 /* Railtypes do not use the default group. */
5834 buf->ReadWord();
5835 }
5836
5837 static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8 idcount, RoadTramType rtt)
5838 {
5839 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5840
5841 uint8 *roadtypes = AllocaM(uint8, idcount);
5842 for (uint i = 0; i < idcount; i++) {
5843 uint8 id = buf->ReadByte();
5844 roadtypes[i] = id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE;
5845 }
5846
5847 uint8 cidcount = buf->ReadByte();
5848 for (uint c = 0; c < cidcount; c++) {
5849 uint8 ctype = buf->ReadByte();
5850 uint16 groupid = buf->ReadWord();
5851 if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
5852
5853 if (ctype >= ROTSG_END) continue;
5854
5855 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
5856 for (uint i = 0; i < idcount; i++) {
5857 if (roadtypes[i] != INVALID_ROADTYPE) {
5858 RoadTypeInfo *rti = &_roadtypes[roadtypes[i]];
5859
5860 rti->grffile[ctype] = _cur.grffile;
5861 rti->group[ctype] = _cur.spritegroups[groupid];
5862 }
5863 }
5864 }
5865
5866 /* Roadtypes do not use the default group. */
5867 buf->ReadWord();
5868 }
5869
5870 static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
5871 {
5872 if (_cur.grffile->airportspec == nullptr) {
5873 grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
5874 return;
5875 }
5876
5877 uint8 *airports = AllocaM(uint8, idcount);
5878 for (uint i = 0; i < idcount; i++) {
5879 airports[i] = buf->ReadByte();
5880 }
5881
5882 /* Skip the cargo type section, we only care about the default group */
5883 uint8 cidcount = buf->ReadByte();
5884 buf->Skip(cidcount * 3);
5885
5886 uint16 groupid = buf->ReadWord();
5887 if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
5888
5889 for (uint i = 0; i < idcount; i++) {
5890 AirportSpec *as = airports[i] >= NUM_AIRPORTS_PER_GRF ? nullptr : _cur.grffile->airportspec[airports[i]];
5891
5892 if (as == nullptr) {
5893 grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
5894 continue;
5895 }
5896
5897 as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5898 }
5899 }
5900
5901 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5902 {
5903 if (_cur.grffile->airtspec == nullptr) {
5904 grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
5905 return;
5906 }
5907
5908 uint8 *airptiles = AllocaM(uint8, idcount);
5909 for (uint i = 0; i < idcount; i++) {
5910 airptiles[i] = buf->ReadByte();
5911 }
5912
5913 /* Skip the cargo type section, we only care about the default group */
5914 uint8 cidcount = buf->ReadByte();
5915 buf->Skip(cidcount * 3);
5916
5917 uint16 groupid = buf->ReadWord();
5918 if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
5919
5920 for (uint i = 0; i < idcount; i++) {
5921 AirportTileSpec *airtsp = airptiles[i] >= NUM_AIRPORTTILES_PER_GRF ? nullptr : _cur.grffile->airtspec[airptiles[i]];
5922
5923 if (airtsp == nullptr) {
5924 grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
5925 continue;
5926 }
5927
5928 airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5929 }
5930 }
5931
5932
5933 /* Action 0x03 */
5934 static void FeatureMapSpriteGroup(ByteReader *buf)
5935 {
5936 /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
5937 * id-list := [<id>] [id-list]
5938 * cargo-list := <cargo-type> <cid> [cargo-list]
5939 *
5940 * B feature see action 0
5941 * B n-id bits 0-6: how many IDs this definition applies to
5942 * bit 7: if set, this is a wagon override definition (see below)
5943 * B ids the IDs for which this definition applies
5944 * B num-cid number of cargo IDs (sprite group IDs) in this definition
5945 * can be zero, in that case the def-cid is used always
5946 * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
5947 * W cid cargo ID (sprite group ID) for this type of cargo
5948 * W def-cid default cargo ID (sprite group ID) */
5949
5950 uint8 feature = buf->ReadByte();
5951 uint8 idcount = buf->ReadByte();
5952
5953 if (feature >= GSF_END) {
5954 grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5955 return;
5956 }
5957
5958 /* If idcount is zero, this is a feature callback */
5959 if (idcount == 0) {
5960 /* Skip number of cargo ids? */
5961 buf->ReadByte();
5962 uint16 groupid = buf->ReadWord();
5963 if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
5964
5965 grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x%02X", feature);
5966
5967 AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
5968 return;
5969 }
5970
5971 /* Mark the feature as used by the grf (generic callbacks do not count) */
5972 SetBit(_cur.grffile->grf_features, feature);
5973
5974 grfmsg(6, "FeatureMapSpriteGroup: Feature 0x%02X, %d ids", feature, idcount);
5975
5976 switch (feature) {
5977 case GSF_TRAINS:
5978 case GSF_ROADVEHICLES:
5979 case GSF_SHIPS:
5980 case GSF_AIRCRAFT:
5981 VehicleMapSpriteGroup(buf, feature, idcount);
5982 return;
5983
5984 case GSF_CANALS:
5985 CanalMapSpriteGroup(buf, idcount);
5986 return;
5987
5988 case GSF_STATIONS:
5989 StationMapSpriteGroup(buf, idcount);
5990 return;
5991
5992 case GSF_HOUSES:
5993 TownHouseMapSpriteGroup(buf, idcount);
5994 return;
5995
5996 case GSF_INDUSTRIES:
5997 IndustryMapSpriteGroup(buf, idcount);
5998 return;
5999
6000 case GSF_INDUSTRYTILES:
6001 IndustrytileMapSpriteGroup(buf, idcount);
6002 return;
6003
6004 case GSF_CARGOES:
6005 CargoMapSpriteGroup(buf, idcount);
6006 return;
6007
6008 case GSF_AIRPORTS:
6009 AirportMapSpriteGroup(buf, idcount);
6010 return;
6011
6012 case GSF_OBJECTS:
6013 ObjectMapSpriteGroup(buf, idcount);
6014 break;
6015
6016 case GSF_RAILTYPES:
6017 RailTypeMapSpriteGroup(buf, idcount);
6018 break;
6019
6020 case GSF_ROADTYPES:
6021 RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
6022 break;
6023
6024 case GSF_TRAMTYPES:
6025 RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
6026 break;
6027
6028 case GSF_AIRPORTTILES:
6029 AirportTileMapSpriteGroup(buf, idcount);
6030 return;
6031
6032 default:
6033 grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
6034 return;
6035 }
6036 }
6037
6038 /* Action 0x04 */
6039 static void FeatureNewName(ByteReader *buf)
6040 {
6041 /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
6042 *
6043 * B veh-type see action 0 (as 00..07, + 0A
6044 * But IF veh-type = 48, then generic text
6045 * B language-id If bit 6 is set, This is the extended language scheme,
6046 * with up to 64 language.
6047 * Otherwise, it is a mapping where set bits have meaning
6048 * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6049 * Bit 7 set means this is a generic text, not a vehicle one (or else)
6050 * B num-veh number of vehicles which are getting a new name
6051 * B/W offset number of the first vehicle that gets a new name
6052 * Byte : ID of vehicle to change
6053 * Word : ID of string to change/add
6054 * S data new texts, each of them zero-terminated, after
6055 * which the next name begins. */
6056
6057 bool new_scheme = _cur.grffile->grf_version >= 7;
6058
6059 uint8 feature = buf->ReadByte();
6060 if (feature >= GSF_END && feature != 0x48) {
6061 grfmsg(1, "FeatureNewName: Unsupported feature 0x%02X, skipping", feature);
6062 return;
6063 }
6064
6065 uint8 lang = buf->ReadByte();
6066 uint8 num = buf->ReadByte();
6067 bool generic = HasBit(lang, 7);
6068 uint16 id;
6069 if (generic) {
6070 id = buf->ReadWord();
6071 } else if (feature <= GSF_AIRCRAFT) {
6072 id = buf->ReadExtendedByte();
6073 } else {
6074 id = buf->ReadByte();
6075 }
6076
6077 ClrBit(lang, 7);
6078
6079 uint16 endid = id + num;
6080
6081 grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature 0x%02X) in language 0x%02X",
6082 id, endid, feature, lang);
6083
6084 for (; id < endid && buf->HasData(); id++) {
6085 const char *name = buf->ReadString();
6086 grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
6087
6088 switch (feature) {
6089 case GSF_TRAINS:
6090 case GSF_ROADVEHICLES:
6091 case GSF_SHIPS:
6092 case GSF_AIRCRAFT:
6093 if (!generic) {
6094 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6095 if (e == nullptr) break;
6096 StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6097 e->info.string_id = string;
6098 } else {
6099 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6100 }
6101 break;
6102
6103 default:
6104 if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0x10000)) {
6105 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6106 break;
6107 }
6108
6109 switch (GB(id, 8, 8)) {
6110 case 0xC4: // Station class name
6111 if (GB(id, 0, 8) >= NUM_STATIONS_PER_GRF || _cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6112 grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6113 } else {
6114 StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
6115 StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6116 }
6117 break;
6118
6119 case 0xC5: // Station name
6120 if (GB(id, 0, 8) >= NUM_STATIONS_PER_GRF || _cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6121 grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6122 } else {
6123 _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6124 }
6125 break;
6126
6127 case 0xC7: // Airporttile name
6128 if (GB(id, 0, 8) >= NUM_AIRPORTTILES_PER_GRF || _cur.grffile->airtspec == nullptr || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6129 grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
6130 } else {
6131 _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6132 }
6133 break;
6134
6135 case 0xC9: // House name
6136 if (GB(id, 0, 8) >= NUM_HOUSES_PER_GRF || _cur.grffile->housespec == nullptr || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6137 grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
6138 } else {
6139 _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6140 }
6141 break;
6142
6143 default:
6144 grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
6145 break;
6146 }
6147 break;
6148 }
6149 }
6150 }
6151
6160 static uint16 SanitizeSpriteOffset(uint16& num, uint16 offset, int max_sprites, const char *name)
6161 {
6162
6163 if (offset >= max_sprites) {
6164 grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
6165 uint orig_num = num;
6166 num = 0;
6167 return orig_num;
6168 }
6169
6170 if (offset + num > max_sprites) {
6171 grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
6172 uint orig_num = num;
6173 num = std::max(max_sprites - offset, 0);
6174 return orig_num - num;
6175 }
6176
6177 return 0;
6178 }
6179
6180
6182 enum Action5BlockType {
6183 A5BLOCK_FIXED,
6184 A5BLOCK_ALLOW_OFFSET,
6185 A5BLOCK_INVALID,
6186 };
6188 struct Action5Type {
6189 Action5BlockType block_type;
6190 SpriteID sprite_base;
6191 uint16 min_sprites;
6192 uint16 max_sprites;
6193 const char *name;
6194 };
6195
6197 static const Action5Type _action5_types[] = {
6198 /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6199 /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6200 /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6201 /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6202 /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6203 /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6204 /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6205 /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6206 /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6207 /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6208 /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6209 /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6210 /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6211 /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6212 /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6213 /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6214 /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6215 /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6216 /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6217 /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6218 /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6219 /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6220 /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6221 /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6222 /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6223 /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6224 };
6225
6226 /* Action 0x05 */
6227 static void GraphicsNew(ByteReader *buf)
6228 {
6229 /* <05> <graphics-type> <num-sprites> <other data...>
6230 *
6231 * B graphics-type What set of graphics the sprites define.
6232 * E num-sprites How many sprites are in this set?
6233 * V other data Graphics type specific data. Currently unused. */
6234
6235 uint8 type = buf->ReadByte();
6236 uint16 num = buf->ReadExtendedByte();
6237 uint16 offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
6238 ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6239
6240 if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6241 /* Special not-TTDP-compatible case used in openttd.grf
6242 * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6243 grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6244 LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6245 LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6246 LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6247 LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6248 LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6249 LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6250 LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6251 LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6252 LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6253 LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6254 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
6255 return;
6256 }
6257
6258 /* Supported type? */
6259 if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6260 grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
6261 _cur.skip_sprites = num;
6262 return;
6263 }
6264
6265 const Action5Type *action5_type = &_action5_types[type];
6266
6267 /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6268 * except for the long version of the shore type:
6269 * Ignore offset if not allowed */
6270 if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6271 grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6272 offset = 0;
6273 }
6274
6275 /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6276 * This does not make sense, if <offset> is allowed */
6277 if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6278 grfmsg(1, "GraphicsNew: %s (type 0x%02X) count must be at least %d. Only %d were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num);
6279 _cur.skip_sprites = num;
6280 return;
6281 }
6282
6283 /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6284 uint16 skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6285 SpriteID replace = action5_type->sprite_base + offset;
6286
6287 /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6288 grfmsg(2, "GraphicsNew: Replacing sprites %d to %d of %s (type 0x%02X) at SpriteID 0x%04X", offset, offset + num - 1, action5_type->name, type, replace);
6289
6290 if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
6291
6292 if (type == 0x0B) {
6293 static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6294 static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6295 if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6296 if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6297 }
6298
6299 /* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */
6300 bool dup_oneway_sprites = ((type == 0x09) && (offset + num <= SPR_ONEWAY_SLOPE_N_OFFSET));
6301
6302 for (; num > 0; num--) {
6303 _cur.nfo_line++;
6304 int load_index = (replace == 0 ? _cur.spriteid++ : replace++);
6305 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line);
6306 if (dup_oneway_sprites) {
6307 DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_N_OFFSET);
6308 DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_S_OFFSET);
6309 }
6310 }
6311
6312 _cur.skip_sprites = skip_num;
6313 }
6314
6315 /* Action 0x05 (SKIP) */
6316 static void SkipAct5(ByteReader *buf)
6317 {
6318 /* Ignore type byte */
6319 buf->ReadByte();
6320
6321 /* Skip the sprites of this action */
6322 _cur.skip_sprites = buf->ReadExtendedByte();
6323
6324 grfmsg(3, "SkipAct5: Skipping %d sprites", _cur.skip_sprites);
6325 }
6326
6338 bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
6339 {
6340 switch (param) {
6341 case 0x00: // current date
6342 *value = std::max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
6343 return true;
6344
6345 case 0x01: // current year
6346 *value = Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
6347 return true;
6348
6349 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)
6350 YearMonthDay ymd;
6351 ConvertDateToYMD(_date, &ymd);
6352 Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1);
6353 *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16;
6354 return true;
6355 }
6356
6357 case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6358 *value = _settings_game.game_creation.landscape;
6359 return true;
6360
6361 case 0x06: // road traffic side, bit 4 clear=left, set=right
6362 *value = _settings_game.vehicle.road_side << 4;
6363 return true;
6364
6365 case 0x09: // date fraction
6366 *value = _date_fract * 885;
6367 return true;
6368
6369 case 0x0A: // animation counter
6370 *value = GB(_tick_counter, 0, 16);
6371 return true;
6372
6373 case 0x0B: { // TTDPatch version
6374 uint major = 2;
6375 uint minor = 6;
6376 uint revision = 1; // special case: 2.0.1 is 2.0.10
6377 uint build = 1382;
6378 *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6379 return true;
6380 }
6381
6382 case 0x0D: // TTD Version, 00=DOS, 01=Windows
6383 *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6384 return true;
6385
6386 case 0x0E: // Y-offset for train sprites
6387 *value = _cur.grffile->traininfo_vehicle_pitch;
6388 return true;
6389
6390 case 0x0F: // Rail track type cost factors
6391 *value = 0;
6392 SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6393 if (_settings_game.vehicle.disable_elrails) {
6394 /* skip elrail multiplier - disabled */
6395 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6396 } else {
6397 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6398 /* Skip monorail multiplier - no space in result */
6399 }
6400 SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6401 return true;
6402
6403 case 0x11: // current rail tool type
6404 *value = 0; // constant fake value to avoid desync
6405 return true;
6406
6407 case 0x12: // Game mode
6408 *value = _game_mode;
6409 return true;
6410
6411 /* case 0x13: // Tile refresh offset to left not implemented */
6412 /* case 0x14: // Tile refresh offset to right not implemented */
6413 /* case 0x15: // Tile refresh offset upwards not implemented */
6414 /* case 0x16: // Tile refresh offset downwards not implemented */
6415 /* case 0x17: // temperate snow line not implemented */
6416
6417 case 0x1A: // Always -1
6418 *value = UINT_MAX;
6419 return true;
6420
6421 case 0x1B: // Display options
6422 *value = 0x3F; // constant fake value to avoid desync
6423 return true;
6424
6425 case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6426 *value = 1;
6427 return true;
6428
6429 case 0x1E: // Miscellaneous GRF features
6430 *value = _misc_grf_features;
6431
6432 /* Add the local flags */
6433 assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6434 if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6435 return true;
6436
6437 /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6438
6439 case 0x20: { // snow line height
6440 byte snowline = GetSnowLine();
6441 if (_settings_game.game_creation.landscape == LT_ARCTIC && snowline <= _settings_game.construction.map_height_limit) {
6442 *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6443 } else {
6444 /* No snow */
6445 *value = 0xFF;
6446 }
6447 return true;
6448 }
6449
6450 case 0x21: // OpenTTD version
6451 *value = _openttd_newgrf_version;
6452 return true;
6453
6454 case 0x22: // difficulty level
6455 *value = SP_CUSTOM;
6456 return true;
6457
6458 case 0x23: // long format date
6459 *value = _date;
6460 return true;
6461
6462 case 0x24: // long format year
6463 *value = _cur_year;
6464 return true;
6465
6466 default: return false;
6467 }
6468 }
6469
6470 static uint32 GetParamVal(byte param, uint32 *cond_val)
6471 {
6472 /* First handle variable common with VarAction2 */
6473 uint32 value;
6474 if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6475
6476 /* Non-common variable */
6477 switch (param) {
6478 case 0x84: { // GRF loading stage
6479 uint32 res = 0;
6480
6481 if (_cur.stage > GLS_INIT) SetBit(res, 0);
6482 if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6483 if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6484 return res;
6485 }
6486
6487 case 0x85: // TTDPatch flags, only for bit tests
6488 if (cond_val == nullptr) {
6489 /* Supported in Action 0x07 and 0x09, not 0x0D */
6490 return 0;
6491 } else {
6492 uint32 index = *cond_val / 0x20;
6493 uint32 param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6494 *cond_val %= 0x20;
6495 return param_val;
6496 }
6497
6498 case 0x88: // GRF ID check
6499 return 0;
6500
6501 /* case 0x99: Global ID offset not implemented */
6502
6503 default:
6504 /* GRF Parameter */
6505 if (param < 0x80) return _cur.grffile->GetParam(param);
6506
6507 /* In-game variable. */
6508 grfmsg(1, "Unsupported in-game variable 0x%02X", param);
6509 return UINT_MAX;
6510 }
6511 }
6512
6513 /* Action 0x06 */
6514 static void CfgApply(ByteReader *buf)
6515 {
6516 /* <06> <param-num> <param-size> <offset> ... <FF>
6517 *
6518 * B param-num Number of parameter to substitute (First = "zero")
6519 * Ignored if that parameter was not specified in newgrf.cfg
6520 * B param-size How many bytes to replace. If larger than 4, the
6521 * bytes of the following parameter are used. In that
6522 * case, nothing is applied unless *all* parameters
6523 * were specified.
6524 * B offset Offset into data from beginning of next sprite
6525 * to place where parameter is to be stored. */
6526
6527 /* Preload the next sprite */
6528 SpriteFile &file = *_cur.file;
6529 size_t pos = file.GetPos();
6530 uint32 num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6531 uint8 type = file.ReadByte();
6532 byte *preload_sprite = nullptr;
6533
6534 /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6535 if (type == 0xFF) {
6536 preload_sprite = MallocT<byte>(num);
6537 file.ReadBlock(preload_sprite, num);
6538 }
6539
6540 /* Reset the file position to the start of the next sprite */
6541 file.SeekTo(pos, SEEK_SET);
6542
6543 if (type != 0xFF) {
6544 grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6545 free(preload_sprite);
6546 return;
6547 }
6548
6549 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6550 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
6551 if (it != _grf_line_to_action6_sprite_override.end()) {
6552 free(preload_sprite);
6553 preload_sprite = _grf_line_to_action6_sprite_override[location];
6554 } else {
6555 _grf_line_to_action6_sprite_override[location] = preload_sprite;
6556 }
6557
6558 /* Now perform the Action 0x06 on our data. */
6559
6560 for (;;) {
6561 uint i;
6562 uint param_num;
6563 uint param_size;
6564 uint offset;
6565 bool add_value;
6566
6567 /* Read the parameter to apply. 0xFF indicates no more data to change. */
6568 param_num = buf->ReadByte();
6569 if (param_num == 0xFF) break;
6570
6571 /* Get the size of the parameter to use. If the size covers multiple
6572 * double words, sequential parameter values are used. */
6573 param_size = buf->ReadByte();
6574
6575 /* Bit 7 of param_size indicates we should add to the original value
6576 * instead of replacing it. */
6577 add_value = HasBit(param_size, 7);
6578 param_size = GB(param_size, 0, 7);
6579
6580 /* Where to apply the data to within the pseudo sprite data. */
6581 offset = buf->ReadExtendedByte();
6582
6583 /* If the parameter is a GRF parameter (not an internal variable) check
6584 * if it (and all further sequential parameters) has been defined. */
6585 if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6586 grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
6587 break;
6588 }
6589
6590 grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
6591
6592 bool carry = false;
6593 for (i = 0; i < param_size && offset + i < num; i++) {
6594 uint32 value = GetParamVal(param_num + i / 4, nullptr);
6595 /* Reset carry flag for each iteration of the variable (only really
6596 * matters if param_size is greater than 4) */
6597 if (i % 4 == 0) carry = false;
6598
6599 if (add_value) {
6600 uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6601 preload_sprite[offset + i] = GB(new_value, 0, 8);
6602 /* Check if the addition overflowed */
6603 carry = new_value >= 256;
6604 } else {
6605 preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6606 }
6607 }
6608 }
6609 }
6610
6620 static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
6621 {
6622 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6623 error->data = _cur.grfconfig->GetName();
6624 }
6625
6626 /* Action 0x07
6627 * Action 0x09 */
6628 static void SkipIf(ByteReader *buf)
6629 {
6630 /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6631 *
6632 * B param-num
6633 * B param-size
6634 * B condition-type
6635 * V value
6636 * B num-sprites */
6637 uint32 cond_val = 0;
6638 uint32 mask = 0;
6639 bool result;
6640
6641 uint8 param = buf->ReadByte();
6642 uint8 paramsize = buf->ReadByte();
6643 uint8 condtype = buf->ReadByte();
6644
6645 if (condtype < 2) {
6646 /* Always 1 for bit tests, the given value should be ignored. */
6647 paramsize = 1;
6648 }
6649
6650 switch (paramsize) {
6651 case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6652 case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6653 case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6654 case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6655 default: break;
6656 }
6657
6658 if (param < 0x80 && _cur.grffile->param_end <= param) {
6659 grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
6660 return;
6661 }
6662
6663 grfmsg(7, "SkipIf: Test condtype %d, param 0x%02X, condval 0x%08X", condtype, param, cond_val);
6664
6665 /* condtypes that do not use 'param' are always valid.
6666 * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6667 */
6668 if (condtype >= 0x0B) {
6669 /* Tests that ignore 'param' */
6670 switch (condtype) {
6671 case 0x0B: result = GetCargoIDByLabel(BSWAP32(cond_val)) == CT_INVALID;
6672 break;
6673 case 0x0C: result = GetCargoIDByLabel(BSWAP32(cond_val)) != CT_INVALID;
6674 break;
6675 case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6676 break;
6677 case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6678 break;
6679 case 0x0F: {
6680 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6681 result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6682 break;
6683 }
6684 case 0x10: {
6685 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6686 result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6687 break;
6688 }
6689 case 0x11: {
6690 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6691 result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6692 break;
6693 }
6694 case 0x12: {
6695 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6696 result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6697 break;
6698 }
6699 default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6700 }
6701 } else if (param == 0x88) {
6702 /* GRF ID checks */
6703
6704 GRFConfig *c = GetGRFConfig(cond_val, mask);
6705
6706 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6707 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
6708 c = nullptr;
6709 }
6710
6711 if (condtype != 10 && c == nullptr) {
6712 grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
6713 return;
6714 }
6715
6716 switch (condtype) {
6717 /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6718 case 0x06: // Is GRFID active?
6719 result = c->status == GCS_ACTIVATED;
6720 break;
6721
6722 case 0x07: // Is GRFID non-active?
6723 result = c->status != GCS_ACTIVATED;
6724 break;
6725
6726 case 0x08: // GRFID is not but will be active?
6727 result = c->status == GCS_INITIALISED;
6728 break;
6729
6730 case 0x09: // GRFID is or will be active?
6731 result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6732 break;
6733
6734 case 0x0A: // GRFID is not nor will be active
6735 /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6736 result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6737 break;
6738
6739 default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
6740 }
6741 } else {
6742 /* Tests that use 'param' and are not GRF ID checks. */
6743 uint32 param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6744 switch (condtype) {
6745 case 0x00: result = !!(param_val & (1 << cond_val));
6746 break;
6747 case 0x01: result = !(param_val & (1 << cond_val));
6748 break;
6749 case 0x02: result = (param_val & mask) == cond_val;
6750 break;
6751 case 0x03: result = (param_val & mask) != cond_val;
6752 break;
6753 case 0x04: result = (param_val & mask) < cond_val;
6754 break;
6755 case 0x05: result = (param_val & mask) > cond_val;
6756 break;
6757 default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6758 }
6759 }
6760
6761 if (!result) {
6762 grfmsg(2, "SkipIf: Not skipping sprites, test was false");
6763 return;
6764 }
6765
6766 uint8 numsprites = buf->ReadByte();
6767
6768 /* numsprites can be a GOTO label if it has been defined in the GRF
6769 * file. The jump will always be the first matching label that follows
6770 * the current nfo_line. If no matching label is found, the first matching
6771 * label in the file is used. */
6772 const GRFLabel *choice = nullptr;
6773 for (const auto &label : _cur.grffile->labels) {
6774 if (label.label != numsprites) continue;
6775
6776 /* Remember a goto before the current line */
6777 if (choice == nullptr) choice = &label;
6778 /* If we find a label here, this is definitely good */
6779 if (label.nfo_line > _cur.nfo_line) {
6780 choice = &label;
6781 break;
6782 }
6783 }
6784
6785 if (choice != nullptr) {
6786 grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
6787 _cur.file->SeekTo(choice->pos, SEEK_SET);
6788 _cur.nfo_line = choice->nfo_line;
6789 return;
6790 }
6791
6792 grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
6793 _cur.skip_sprites = numsprites;
6794 if (_cur.skip_sprites == 0) {
6795 /* Zero means there are no sprites to skip, so
6796 * we use -1 to indicate that all further
6797 * sprites should be skipped. */
6798 _cur.skip_sprites = -1;
6799
6800 /* If an action 8 hasn't been encountered yet, disable the grf. */
6801 if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6802 DisableGrf();
6803 }
6804 }
6805 }
6806
6807
6808 /* Action 0x08 (GLS_FILESCAN) */
6809 static void ScanInfo(ByteReader *buf)
6810 {
6811 uint8 grf_version = buf->ReadByte();
6812 uint32 grfid = buf->ReadDWord();
6813 const char *name = buf->ReadString();
6814
6815 _cur.grfconfig->ident.grfid = grfid;
6816
6817 if (grf_version < 2 || grf_version > 8) {
6818 SetBit(_cur.grfconfig->flags, GCF_INVALID);
6819 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);
6820 }
6821
6822 /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
6823 if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
6824
6825 AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
6826
6827 if (buf->HasData()) {
6828 const char *info = buf->ReadString();
6829 AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
6830 }
6831
6832 /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
6833 _cur.skip_sprites = -1;
6834 }
6835
6836 /* Action 0x08 */
6837 static void GRFInfo(ByteReader *buf)
6838 {
6839 /* <08> <version> <grf-id> <name> <info>
6840 *
6841 * B version newgrf version, currently 06
6842 * 4*B grf-id globally unique ID of this .grf file
6843 * S name name of this .grf set
6844 * S info string describing the set, and e.g. author and copyright */
6845
6846 uint8 version = buf->ReadByte();
6847 uint32 grfid = buf->ReadDWord();
6848 const char *name = buf->ReadString();
6849
6850 if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
6851 DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
6852 return;
6853 }
6854
6855 if (_cur.grffile->grfid != grfid) {
6856 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));
6857 _cur.grffile->grfid = grfid;
6858 }
6859
6860 _cur.grffile->grf_version = version;
6861 _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
6862
6863 /* Do swap the GRFID for displaying purposes since people expect that */
6864 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);
6865 }
6866
6867 /* Action 0x0A */
6868 static void SpriteReplace(ByteReader *buf)
6869 {
6870 /* <0A> <num-sets> <set1> [<set2> ...]
6871 * <set>: <num-sprites> <first-sprite>
6872 *
6873 * B num-sets How many sets of sprites to replace.
6874 * Each set:
6875 * B num-sprites How many sprites are in this set
6876 * W first-sprite First sprite number to replace */
6877
6878 uint8 num_sets = buf->ReadByte();
6879
6880 for (uint i = 0; i < num_sets; i++) {
6881 uint8 num_sprites = buf->ReadByte();
6882 uint16 first_sprite = buf->ReadWord();
6883
6884 grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
6885 i, num_sprites, first_sprite
6886 );
6887
6888 for (uint j = 0; j < num_sprites; j++) {
6889 int load_index = first_sprite + j;
6890 _cur.nfo_line++;
6891 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
6892
6893 /* Shore sprites now located at different addresses.
6894 * So detect when the old ones get replaced. */
6895 if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
6896 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
6897 }
6898 }
6899 }
6900 }
6901
6902 /* Action 0x0A (SKIP) */
6903 static void SkipActA(ByteReader *buf)
6904 {
6905 uint8 num_sets = buf->ReadByte();
6906
6907 for (uint i = 0; i < num_sets; i++) {
6908 /* Skip the sprites this replaces */
6909 _cur.skip_sprites += buf->ReadByte();
6910 /* But ignore where they go */
6911 buf->ReadWord();
6912 }
6913
6914 grfmsg(3, "SkipActA: Skipping %d sprites", _cur.skip_sprites);
6915 }
6916
6917 /* Action 0x0B */
6918 static void GRFLoadError(ByteReader *buf)
6919 {
6920 /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
6921 *
6922 * B severity 00: notice, continue loading grf file
6923 * 01: warning, continue loading grf file
6924 * 02: error, but continue loading grf file, and attempt
6925 * loading grf again when loading or starting next game
6926 * 03: error, abort loading and prevent loading again in
6927 * the future (only when restarting the patch)
6928 * B language-id see action 4, use 1F for built-in error messages
6929 * B message-id message to show, see below
6930 * S message for custom messages (message-id FF), text of the message
6931 * not present for built-in messages.
6932 * V data additional data for built-in (or custom) messages
6933 * B parnum parameter numbers to be shown in the message (maximum of 2) */
6934
6935 static const StringID msgstr[] = {
6936 STR_NEWGRF_ERROR_VERSION_NUMBER,
6937 STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
6938 STR_NEWGRF_ERROR_UNSET_SWITCH,
6939 STR_NEWGRF_ERROR_INVALID_PARAMETER,
6940 STR_NEWGRF_ERROR_LOAD_BEFORE,
6941 STR_NEWGRF_ERROR_LOAD_AFTER,
6942 STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
6943 };
6944
6945 static const StringID sevstr[] = {
6946 STR_NEWGRF_ERROR_MSG_INFO,
6947 STR_NEWGRF_ERROR_MSG_WARNING,
6948 STR_NEWGRF_ERROR_MSG_ERROR,
6949 STR_NEWGRF_ERROR_MSG_FATAL
6950 };
6951
6952 byte severity = buf->ReadByte();
6953 byte lang = buf->ReadByte();
6954 byte message_id = buf->ReadByte();
6955
6956 /* Skip the error if it isn't valid for the current language. */
6957 if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
6958
6959 /* Skip the error until the activation stage unless bit 7 of the severity
6960 * is set. */
6961 if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
6962 grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur.stage);
6963 return;
6964 }
6965 ClrBit(severity, 7);
6966
6967 if (severity >= lengthof(sevstr)) {
6968 grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
6969 severity = 2;
6970 } else if (severity == 3) {
6971 /* This is a fatal error, so make sure the GRF is deactivated and no
6972 * more of it gets loaded. */
6973 DisableGrf();
6974
6975 /* Make sure we show fatal errors, instead of silly infos from before */
6976 delete _cur.grfconfig->error;
6977 _cur.grfconfig->error = nullptr;
6978 }
6979
6980 if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
6981 grfmsg(7, "GRFLoadError: Invalid message id.");
6982 return;
6983 }
6984
6985 if (buf->Remaining() <= 1) {
6986 grfmsg(7, "GRFLoadError: No message data supplied.");
6987 return;
6988 }
6989
6990 /* For now we can only show one message per newgrf file. */
6991 if (_cur.grfconfig->error != nullptr) return;
6992
6993 GRFError *error = new GRFError(sevstr[severity]);
6994
6995 if (message_id == 0xFF) {
6996 /* This is a custom error message. */
6997 if (buf->HasData()) {
6998 const char *message = buf->ReadString();
6999
7000 error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
7001 } else {
7002 grfmsg(7, "GRFLoadError: No custom message supplied.");
7003 error->custom_message.clear();
7004 }
7005 } else {
7006 error->message = msgstr[message_id];
7007 }
7008
7009 if (buf->HasData()) {
7010 const char *data = buf->ReadString();
7011
7012 error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
7013 } else {
7014 grfmsg(7, "GRFLoadError: No message data supplied.");
7015 error->data.clear();
7016 }
7017
7018 /* Only two parameter numbers can be used in the string. */
7019 for (uint i = 0; i < lengthof(error->param_value) && buf->HasData(); i++) {
7020 uint param_number = buf->ReadByte();
7021 error->param_value[i] = _cur.grffile->GetParam(param_number);
7022 }
7023
7024 _cur.grfconfig->error = error;
7025 }
7026
7027 /* Action 0x0C */
7028 static void GRFComment(ByteReader *buf)
7029 {
7030 /* <0C> [<ignored...>]
7031 *
7032 * V ignored Anything following the 0C is ignored */
7033
7034 if (!buf->HasData()) return;
7035
7036 const char *text = buf->ReadString();
7037 grfmsg(2, "GRFComment: %s", text);
7038 }
7039
7040 /* Action 0x0D (GLS_SAFETYSCAN) */
7041 static void SafeParamSet(ByteReader *buf)
7042 {
7043 uint8 target = buf->ReadByte();
7044
7045 /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
7046 if (target < 0x80 || target == 0x9E) return;
7047
7048 /* GRM could be unsafe, but as here it can only happen after other GRFs
7049 * are loaded, it should be okay. If the GRF tried to use the slots it
7050 * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
7051 * sprites is considered safe. */
7052
7053 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7054
7055 /* Skip remainder of GRF */
7056 _cur.skip_sprites = -1;
7057 }
7058
7059
7060 static uint32 GetPatchVariable(uint8 param)
7061 {
7062 switch (param) {
7063 /* start year - 1920 */
7064 case 0x0B: return std::max(_settings_game.game_creation.starting_year, ORIGINAL_BASE_YEAR) - ORIGINAL_BASE_YEAR;
7065
7066 /* freight trains weight factor */
7067 case 0x0E: return _settings_game.vehicle.freight_trains;
7068
7069 /* empty wagon speed increase */
7070 case 0x0F: return 0;
7071
7072 /* plane speed factor; our patch option is reversed from TTDPatch's,
7073 * the following is good for 1x, 2x and 4x (most common?) and...
7074 * well not really for 3x. */
7075 case 0x10:
7076 switch (_settings_game.vehicle.plane_speed) {
7077 default:
7078 case 4: return 1;
7079 case 3: return 2;
7080 case 2: return 2;
7081 case 1: return 4;
7082 }
7083
7084
7085 /* 2CC colourmap base sprite */
7086 case 0x11: return SPR_2CCMAP_BASE;
7087
7088 /* map size: format = -MABXYSS
7089 * M : the type of map
7090 * bit 0 : set : squared map. Bit 1 is now not relevant
7091 * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7092 * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7093 * clear : X is the bigger edge.
7094 * A : minimum edge(log2) of the map
7095 * B : maximum edge(log2) of the map
7096 * XY : edges(log2) of each side of the map.
7097 * SS : combination of both X and Y, thus giving the size(log2) of the map
7098 */
7099 case 0x13: {
7100 byte map_bits = 0;
7101 byte log_X = MapLogX() - 6; // subtraction is required to make the minimal size (64) zero based
7102 byte log_Y = MapLogY() - 6;
7103 byte max_edge = std::max(log_X, log_Y);
7104
7105 if (log_X == log_Y) { // we have a squared map, since both edges are identical
7106 SetBit(map_bits, 0);
7107 } else {
7108 if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7109 }
7110
7111 return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7112 (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7113 }
7114
7115 /* The maximum height of the map. */
7116 case 0x14:
7117 return _settings_game.construction.map_height_limit;
7118
7119 /* Extra foundations base sprite */
7120 case 0x15:
7121 return SPR_SLOPES_BASE;
7122
7123 /* Shore base sprite */
7124 case 0x16:
7125 return SPR_SHORE_BASE;
7126
7127 /* Game map seed */
7128 case 0x17:
7129 return _settings_game.game_creation.generation_seed;
7130
7131 default:
7132 grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
7133 return 0;
7134 }
7135 }
7136
7137
7138 static uint32 PerformGRM(uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
7139 {
7140 uint start = 0;
7141 uint size = 0;
7142
7143 if (op == 6) {
7144 /* Return GRFID of set that reserved ID */
7145 return grm[_cur.grffile->GetParam(target)];
7146 }
7147
7148 /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7149 if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7150
7151 for (uint i = start; i < num_ids; i++) {
7152 if (grm[i] == 0) {
7153 size++;
7154 } else {
7155 if (op == 2 || op == 3) break;
7156 start = i + 1;
7157 size = 0;
7158 }
7159
7160 if (size == count) break;
7161 }
7162
7163 if (size == count) {
7164 /* Got the slot... */
7165 if (op == 0 || op == 3) {
7166 grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
7167 for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7168 }
7169 return start;
7170 }
7171
7172 /* Unable to allocate */
7173 if (op != 4 && op != 5) {
7174 /* Deactivate GRF */
7175 grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
7176 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7177 return UINT_MAX;
7178 }
7179
7180 grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
7181 return UINT_MAX;
7182 }
7183
7184
7186 static void ParamSet(ByteReader *buf)
7187 {
7188 /* <0D> <target> <operation> <source1> <source2> [<data>]
7189 *
7190 * B target parameter number where result is stored
7191 * B operation operation to perform, see below
7192 * B source1 first source operand
7193 * B source2 second source operand
7194 * D data data to use in the calculation, not necessary
7195 * if both source1 and source2 refer to actual parameters
7196 *
7197 * Operations
7198 * 00 Set parameter equal to source1
7199 * 01 Addition, source1 + source2
7200 * 02 Subtraction, source1 - source2
7201 * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7202 * 04 Signed multiplication, source1 * source2 (both signed)
7203 * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7204 * signed quantity; left shift if positive and right shift if
7205 * negative, source1 is unsigned)
7206 * 06 Signed bit shift, source1 by source2
7207 * (source2 like in 05, and source1 as well)
7208 */
7209
7210 uint8 target = buf->ReadByte();
7211 uint8 oper = buf->ReadByte();
7212 uint32 src1 = buf->ReadByte();
7213 uint32 src2 = buf->ReadByte();
7214
7215 uint32 data = 0;
7216 if (buf->Remaining() >= 4) data = buf->ReadDWord();
7217
7218 /* You can add 80 to the operation to make it apply only if the target
7219 * is not defined yet. In this respect, a parameter is taken to be
7220 * defined if any of the following applies:
7221 * - it has been set to any value in the newgrf(w).cfg parameter list
7222 * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7223 * an earlier action D */
7224 if (HasBit(oper, 7)) {
7225 if (target < 0x80 && target < _cur.grffile->param_end) {
7226 grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
7227 return;
7228 }
7229
7230 oper = GB(oper, 0, 7);
7231 }
7232
7233 if (src2 == 0xFE) {
7234 if (GB(data, 0, 8) == 0xFF) {
7235 if (data == 0x0000FFFF) {
7236 /* Patch variables */
7237 src1 = GetPatchVariable(src1);
7238 } else {
7239 /* GRF Resource Management */
7240 uint8 op = src1;
7241 uint8 feature = GB(data, 8, 8);
7242 uint16 count = GB(data, 16, 16);
7243
7244 if (_cur.stage == GLS_RESERVE) {
7245 if (feature == 0x08) {
7246 /* General sprites */
7247 if (op == 0) {
7248 /* Check if the allocated sprites will fit below the original sprite limit */
7249 if (_cur.spriteid + count >= 16384) {
7250 grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
7251 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7252 return;
7253 }
7254
7255 /* Reserve space at the current sprite ID */
7256 grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur.spriteid);
7257 _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
7258 _cur.spriteid += count;
7259 }
7260 }
7261 /* Ignore GRM result during reservation */
7262 src1 = 0;
7263 } else if (_cur.stage == GLS_ACTIVATION) {
7264 switch (feature) {
7265 case 0x00: // Trains
7266 case 0x01: // Road Vehicles
7267 case 0x02: // Ships
7268 case 0x03: // Aircraft
7269 if (!_settings_game.vehicle.dynamic_engines) {
7270 src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7271 if (_cur.skip_sprites == -1) return;
7272 } else {
7273 /* GRM does not apply for dynamic engine allocation. */
7274 switch (op) {
7275 case 2:
7276 case 3:
7277 src1 = _cur.grffile->GetParam(target);
7278 break;
7279
7280 default:
7281 src1 = 0;
7282 break;
7283 }
7284 }
7285 break;
7286
7287 case 0x08: // General sprites
7288 switch (op) {
7289 case 0:
7290 /* Return space reserved during reservation stage */
7291 src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
7292 grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
7293 break;
7294
7295 case 1:
7296 src1 = _cur.spriteid;
7297 break;
7298
7299 default:
7300 grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
7301 return;
7302 }
7303 break;
7304
7305 case 0x0B: // Cargo
7306 /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7307 src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7308 if (_cur.skip_sprites == -1) return;
7309 break;
7310
7311 default: grfmsg(1, "ParamSet: GRM: Unsupported feature 0x%X", feature); return;
7312 }
7313 } else {
7314 /* Ignore GRM during initialization */
7315 src1 = 0;
7316 }
7317 }
7318 } else {
7319 /* Read another GRF File's parameter */
7320 const GRFFile *file = GetFileByGRFID(data);
7321 GRFConfig *c = GetGRFConfig(data);
7322 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7323 /* Disable the read GRF if it is a static NewGRF. */
7324 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
7325 src1 = 0;
7326 } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7327 src1 = 0;
7328 } else if (src1 == 0xFE) {
7329 src1 = c->version;
7330 } else {
7331 src1 = file->GetParam(src1);
7332 }
7333 }
7334 } else {
7335 /* The source1 and source2 operands refer to the grf parameter number
7336 * like in action 6 and 7. In addition, they can refer to the special
7337 * variables available in action 7, or they can be FF to use the value
7338 * of <data>. If referring to parameters that are undefined, a value
7339 * of 0 is used instead. */
7340 src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7341 src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7342 }
7343
7344 uint32 res;
7345 switch (oper) {
7346 case 0x00:
7347 res = src1;
7348 break;
7349
7350 case 0x01:
7351 res = src1 + src2;
7352 break;
7353
7354 case 0x02:
7355 res = src1 - src2;
7356 break;
7357
7358 case 0x03:
7359 res = src1 * src2;
7360 break;
7361
7362 case 0x04:
7363 res = (int32)src1 * (int32)src2;
7364 break;
7365
7366 case 0x05:
7367 if ((int32)src2 < 0) {
7368 res = src1 >> -(int32)src2;
7369 } else {
7370 res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7371 }
7372 break;
7373
7374 case 0x06:
7375 if ((int32)src2 < 0) {
7376 res = (int32)src1 >> -(int32)src2;
7377 } else {
7378 res = (int32)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7379 }
7380 break;
7381
7382 case 0x07: // Bitwise AND
7383 res = src1 & src2;
7384 break;
7385
7386 case 0x08: // Bitwise OR
7387 res = src1 | src2;
7388 break;
7389
7390 case 0x09: // Unsigned division
7391 if (src2 == 0) {
7392 res = src1;
7393 } else {
7394 res = src1 / src2;
7395 }
7396 break;
7397
7398 case 0x0A: // Signed division
7399 if (src2 == 0) {
7400 res = src1;
7401 } else {
7402 res = (int32)src1 / (int32)src2;
7403 }
7404 break;
7405
7406 case 0x0B: // Unsigned modulo
7407 if (src2 == 0) {
7408 res = src1;
7409 } else {
7410 res = src1 % src2;
7411 }
7412 break;
7413
7414 case 0x0C: // Signed modulo
7415 if (src2 == 0) {
7416 res = src1;
7417 } else {
7418 res = (int32)src1 % (int32)src2;
7419 }
7420 break;
7421
7422 default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
7423 }
7424
7425 switch (target) {
7426 case 0x8E: // Y-Offset for train sprites
7427 _cur.grffile->traininfo_vehicle_pitch = res;
7428 break;
7429
7430 case 0x8F: { // Rail track type cost factors
7431 extern RailtypeInfo _railtypes[RAILTYPE_END];
7432 _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7433 if (_settings_game.vehicle.disable_elrails) {
7434 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7435 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7436 } else {
7437 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7438 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7439 }
7440 _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7441 break;
7442 }
7443
7444 /* not implemented */
7445 case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7446 case 0x94: // Tile refresh offset to right
7447 case 0x95: // Tile refresh offset upwards
7448 case 0x96: // Tile refresh offset downwards
7449 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
7450 case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7451 grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7452 break;
7453
7454 case 0x9E: // Miscellaneous GRF features
7455 /* Set train list engine width */
7456 _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7457 /* Remove the local flags from the global flags */
7458 ClrBit(res, GMB_TRAIN_WIDTH_32_PIXELS);
7459
7460 /* Only copy safe bits for static grfs */
7461 if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7462 uint32 safe_bits = 0;
7463 SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7464
7465 _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7466 } else {
7467 _misc_grf_features = res;
7468 }
7469 break;
7470
7471 case 0x9F: // locale-dependent settings
7472 grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7473 break;
7474
7475 default:
7476 if (target < 0x80) {
7477 _cur.grffile->param[target] = res;
7478 /* param is zeroed by default */
7479 if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7480 } else {
7481 grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
7482 }
7483 break;
7484 }
7485 }
7486
7487 /* Action 0x0E (GLS_SAFETYSCAN) */
7488 static void SafeGRFInhibit(ByteReader *buf)
7489 {
7490 /* <0E> <num> <grfids...>
7491 *
7492 * B num Number of GRFIDs that follow
7493 * D grfids GRFIDs of the files to deactivate */
7494
7495 uint8 num = buf->ReadByte();
7496
7497 for (uint i = 0; i < num; i++) {
7498 uint32 grfid = buf->ReadDWord();
7499
7500 /* GRF is unsafe it if tries to deactivate other GRFs */
7501 if (grfid != _cur.grfconfig->ident.grfid) {
7502 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7503
7504 /* Skip remainder of GRF */
7505 _cur.skip_sprites = -1;
7506
7507 return;
7508 }
7509 }
7510 }
7511
7512 /* Action 0x0E */
7513 static void GRFInhibit(ByteReader *buf)
7514 {
7515 /* <0E> <num> <grfids...>
7516 *
7517 * B num Number of GRFIDs that follow
7518 * D grfids GRFIDs of the files to deactivate */
7519
7520 uint8 num = buf->ReadByte();
7521
7522 for (uint i = 0; i < num; i++) {
7523 uint32 grfid = buf->ReadDWord();
7524 GRFConfig *file = GetGRFConfig(grfid);
7525
7526 /* Unset activation flag */
7527 if (file != nullptr && file != _cur.grfconfig) {
7528 grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
7529 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7530 error->data = _cur.grfconfig->GetName();
7531 }
7532 }
7533 }
7534
7536 static void FeatureTownName(ByteReader *buf)
7537 {
7538 /* <0F> <id> <style-name> <num-parts> <parts>
7539 *
7540 * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7541 * V style-name Name of the style (only for final definition)
7542 * B num-parts Number of parts in this definition
7543 * V parts The parts */
7544
7545 uint32 grfid = _cur.grffile->grfid;
7546
7547 GRFTownName *townname = AddGRFTownName(grfid);
7548
7549 byte id = buf->ReadByte();
7550 grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
7551
7552 if (HasBit(id, 7)) {
7553 /* Final definition */
7554 ClrBit(id, 7);
7555 bool new_scheme = _cur.grffile->grf_version >= 7;
7556
7557 byte lang = buf->ReadByte();
7558
7559 byte nb_gen = townname->nb_gen;
7560 do {
7561 ClrBit(lang, 7);
7562
7563 const char *name = buf->ReadString();
7564
7565 std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7566 grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name.c_str());
7567
7568 townname->name[nb_gen] = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7569
7570 lang = buf->ReadByte();
7571 } while (lang != 0);
7572 townname->id[nb_gen] = id;
7573 townname->nb_gen++;
7574 }
7575
7576 byte nb = buf->ReadByte();
7577 grfmsg(6, "FeatureTownName: %u parts", nb);
7578
7579 townname->nbparts[id] = nb;
7580 townname->partlist[id] = CallocT<NamePartList>(nb);
7581
7582 for (int i = 0; i < nb; i++) {
7583 byte nbtext = buf->ReadByte();
7584 townname->partlist[id][i].bitstart = buf->ReadByte();
7585 townname->partlist[id][i].bitcount = buf->ReadByte();
7586 townname->partlist[id][i].maxprob = 0;
7587 townname->partlist[id][i].partcount = nbtext;
7588 townname->partlist[id][i].parts = CallocT<NamePart>(nbtext);
7589 grfmsg(6, "FeatureTownName: part %d contains %d texts and will use GB(seed, %d, %d)", i, nbtext, townname->partlist[id][i].bitstart, townname->partlist[id][i].bitcount);
7590
7591 for (int j = 0; j < nbtext; j++) {
7592 byte prob = buf->ReadByte();
7593
7594 if (HasBit(prob, 7)) {
7595 byte ref_id = buf->ReadByte();
7596
7597 if (townname->nbparts[ref_id] == 0) {
7598 grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
7599 DelGRFTownName(grfid);
7600 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7601 return;
7602 }
7603
7604 grfmsg(6, "FeatureTownName: part %d, text %d, uses intermediate definition 0x%02X (with probability %d)", i, j, ref_id, prob & 0x7F);
7605 townname->partlist[id][i].parts[j].data.id = ref_id;
7606 } else {
7607 const char *text = buf->ReadString();
7608 townname->partlist[id][i].parts[j].data.text = stredup(TranslateTTDPatchCodes(grfid, 0, false, text).c_str());
7609 grfmsg(6, "FeatureTownName: part %d, text %d, '%s' (with probability %d)", i, j, townname->partlist[id][i].parts[j].data.text, prob);
7610 }
7611 townname->partlist[id][i].parts[j].prob = prob;
7612 townname->partlist[id][i].maxprob += GB(prob, 0, 7);
7613 }
7614 grfmsg(6, "FeatureTownName: part %d, total probability %d", i, townname->partlist[id][i].maxprob);
7615 }
7616 }
7617
7619 static void DefineGotoLabel(ByteReader *buf)
7620 {
7621 /* <10> <label> [<comment>]
7622 *
7623 * B label The label to define
7624 * V comment Optional comment - ignored */
7625
7626 byte nfo_label = buf->ReadByte();
7627
7628 _cur.grffile->labels.emplace_back(nfo_label, _cur.nfo_line, _cur.file->GetPos());
7629
7630 grfmsg(2, "DefineGotoLabel: GOTO target with label 0x%02X", nfo_label);
7631 }
7632
7637 static void ImportGRFSound(SoundEntry *sound)
7638 {
7639 const GRFFile *file;
7640 uint32 grfid = _cur.file->ReadDword();
7641 SoundID sound_id = _cur.file->ReadWord();
7642
7643 file = GetFileByGRFID(grfid);
7644 if (file == nullptr || file->sound_offset == 0) {
7645 grfmsg(1, "ImportGRFSound: Source file not available");
7646 return;
7647 }
7648
7649 if (sound_id >= file->num_sounds) {
7650 grfmsg(1, "ImportGRFSound: Sound effect %d is invalid", sound_id);
7651 return;
7652 }
7653
7654 grfmsg(2, "ImportGRFSound: Copying sound %d (%d) from file %X", sound_id, file->sound_offset + sound_id, grfid);
7655
7656 *sound = *GetSound(file->sound_offset + sound_id);
7657
7658 /* Reset volume and priority, which TTDPatch doesn't copy */
7659 sound->volume = 128;
7660 sound->priority = 0;
7661 }
7662
7668 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7669 {
7670 /* Set default volume and priority */
7671 sound->volume = 0x80;
7672 sound->priority = 0;
7673
7674 if (offs != SIZE_MAX) {
7675 /* Sound is present in the NewGRF. */
7676 sound->file = _cur.file;
7677 sound->file_offset = offs;
7678 sound->grf_container_ver = _cur.file->GetContainerVersion();
7679 }
7680 }
7681
7682 /* Action 0x11 */
7683 static void GRFSound(ByteReader *buf)
7684 {
7685 /* <11> <num>
7686 *
7687 * W num Number of sound files that follow */
7688
7689 uint16 num = buf->ReadWord();
7690 if (num == 0) return;
7691
7692 SoundEntry *sound;
7693 if (_cur.grffile->sound_offset == 0) {
7694 _cur.grffile->sound_offset = GetNumSounds();
7695 _cur.grffile->num_sounds = num;
7696 sound = AllocateSound(num);
7697 } else {
7698 sound = GetSound(_cur.grffile->sound_offset);
7699 }
7700
7701 SpriteFile &file = *_cur.file;
7702 byte grf_container_version = file.GetContainerVersion();
7703 for (int i = 0; i < num; i++) {
7704 _cur.nfo_line++;
7705
7706 /* Check whether the index is in range. This might happen if multiple action 11 are present.
7707 * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7708 bool invalid = i >= _cur.grffile->num_sounds;
7709
7710 size_t offs = file.GetPos();
7711
7712 uint32 len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7713 byte type = file.ReadByte();
7714
7715 if (grf_container_version >= 2 && type == 0xFD) {
7716 /* Reference to sprite section. */
7717 if (invalid) {
7718 grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7719 file.SkipBytes(len);
7720 } else if (len != 4) {
7721 grfmsg(1, "GRFSound: Invalid sprite section import");
7722 file.SkipBytes(len);
7723 } else {
7724 uint32 id = file.ReadDword();
7725 if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7726 }
7727 continue;
7728 }
7729
7730 if (type != 0xFF) {
7731 grfmsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7732 file.SkipBytes(7);
7733 SkipSpriteData(*_cur.file, type, len - 8);
7734 continue;
7735 }
7736
7737 if (invalid) {
7738 grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7739 file.SkipBytes(len);
7740 }
7741
7742 byte action = file.ReadByte();
7743 switch (action) {
7744 case 0xFF:
7745 /* Allocate sound only in init stage. */
7746 if (_cur.stage == GLS_INIT) {
7747 if (grf_container_version >= 2) {
7748 grfmsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7749 } else {
7750 LoadGRFSound(offs, sound + i);
7751 }
7752 }
7753 file.SkipBytes(len - 1); // already read <action>
7754 break;
7755
7756 case 0xFE:
7757 if (_cur.stage == GLS_ACTIVATION) {
7758 /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7759 * importing sounds, so this is probably all wrong... */
7760 if (file.ReadByte() != 0) grfmsg(1, "GRFSound: Import type mismatch");
7761 ImportGRFSound(sound + i);
7762 } else {
7763 file.SkipBytes(len - 1); // already read <action>
7764 }
7765 break;
7766
7767 default:
7768 grfmsg(1, "GRFSound: Unexpected Action %x found, skipping", action);
7769 file.SkipBytes(len - 1); // already read <action>
7770 break;
7771 }
7772 }
7773 }
7774
7775 /* Action 0x11 (SKIP) */
7776 static void SkipAct11(ByteReader *buf)
7777 {
7778 /* <11> <num>
7779 *
7780 * W num Number of sound files that follow */
7781
7782 _cur.skip_sprites = buf->ReadWord();
7783
7784 grfmsg(3, "SkipAct11: Skipping %d sprites", _cur.skip_sprites);
7785 }
7786
7788 static void LoadFontGlyph(ByteReader *buf)
7789 {
7790 /* <12> <num_def> <font_size> <num_char> <base_char>
7791 *
7792 * B num_def Number of definitions
7793 * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7794 * B num_char Number of consecutive glyphs
7795 * W base_char First character index */
7796
7797 uint8 num_def = buf->ReadByte();
7798
7799 for (uint i = 0; i < num_def; i++) {
7800 FontSize size = (FontSize)buf->ReadByte();
7801 uint8 num_char = buf->ReadByte();
7802 uint16 base_char = buf->ReadWord();
7803
7804 if (size >= FS_END) {
7805 grfmsg(1, "LoadFontGlyph: Size %u is not supported, ignoring", size);
7806 }
7807
7808 grfmsg(7, "LoadFontGlyph: Loading %u glyph(s) at 0x%04X for size %u", num_char, base_char, size);
7809
7810 for (uint c = 0; c < num_char; c++) {
7811 if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
7812 _cur.nfo_line++;
7813 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
7814 }
7815 }
7816 }
7817
7819 static void SkipAct12(ByteReader *buf)
7820 {
7821 /* <12> <num_def> <font_size> <num_char> <base_char>
7822 *
7823 * B num_def Number of definitions
7824 * B font_size Size of font (0 = normal, 1 = small, 2 = large)
7825 * B num_char Number of consecutive glyphs
7826 * W base_char First character index */
7827
7828 uint8 num_def = buf->ReadByte();
7829
7830 for (uint i = 0; i < num_def; i++) {
7831 /* Ignore 'size' byte */
7832 buf->ReadByte();
7833
7834 /* Sum up number of characters */
7835 _cur.skip_sprites += buf->ReadByte();
7836
7837 /* Ignore 'base_char' word */
7838 buf->ReadWord();
7839 }
7840
7841 grfmsg(3, "SkipAct12: Skipping %d sprites", _cur.skip_sprites);
7842 }
7843
7845 static void TranslateGRFStrings(ByteReader *buf)
7846 {
7847 /* <13> <grfid> <num-ent> <offset> <text...>
7848 *
7849 * 4*B grfid The GRFID of the file whose texts are to be translated
7850 * B num-ent Number of strings
7851 * W offset First text ID
7852 * S text... Zero-terminated strings */
7853
7854 uint32 grfid = buf->ReadDWord();
7855 const GRFConfig *c = GetGRFConfig(grfid);
7856 if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
7857 grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
7858 return;
7859 }
7860
7861 if (c->status == GCS_INITIALISED) {
7862 /* If the file is not active but will be activated later, give an error
7863 * and disable this file. */
7864 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
7865
7866 error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
7867
7868 return;
7869 }
7870
7871 /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
7872 * to be added as a generic string, thus the language id of 0x7F. For this to work
7873 * new_scheme has to be true as well, which will also be implicitly the case for version 8
7874 * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
7875 * not change anything if a string has been provided specifically for this language. */
7876 byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
7877 byte num_strings = buf->ReadByte();
7878 uint16 first_id = buf->ReadWord();
7879
7880 if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
7881 grfmsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x%4X, number: 0x%2X)", first_id, num_strings);
7882 return;
7883 }
7884
7885 for (uint i = 0; i < num_strings && buf->HasData(); i++) {
7886 const char *string = buf->ReadString();
7887
7888 if (StrEmpty(string)) {
7889 grfmsg(7, "TranslateGRFString: Ignoring empty string.");
7890 continue;
7891 }
7892
7893 AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
7894 }
7895 }
7896
7898 static bool ChangeGRFName(byte langid, const char *str)
7899 {
7900 AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
7901 return true;
7902 }
7903
7905 static bool ChangeGRFDescription(byte langid, const char *str)
7906 {
7907 AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
7908 return true;
7909 }
7910
7912 static bool ChangeGRFURL(byte langid, const char *str)
7913 {
7914 AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
7915 return true;
7916 }
7917
7919 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
7920 {
7921 if (len != 1) {
7922 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
7923 buf->Skip(len);
7924 } else {
7925 _cur.grfconfig->num_valid_params = std::min<byte>(buf->ReadByte(), lengthof(_cur.grfconfig->param));
7926 }
7927 return true;
7928 }
7929
7931 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
7932 {
7933 if (len != 1) {
7934 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got " PRINTF_SIZE ", ignoring this field", len);
7935 buf->Skip(len);
7936 } else {
7937 char data = buf->ReadByte();
7938 GRFPalette pal = GRFP_GRF_UNSET;
7939 switch (data) {
7940 case '*':
7941 case 'A': pal = GRFP_GRF_ANY; break;
7942 case 'W': pal = GRFP_GRF_WINDOWS; break;
7943 case 'D': pal = GRFP_GRF_DOS; break;
7944 default:
7945 grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'PALS', ignoring this field", data);
7946 break;
7947 }
7948 if (pal != GRFP_GRF_UNSET) {
7949 _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
7950 _cur.grfconfig->palette |= pal;
7951 }
7952 }
7953 return true;
7954 }
7955
7957 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
7958 {
7959 if (len != 1) {
7960 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got " PRINTF_SIZE ", ignoring this field", len);
7961 buf->Skip(len);
7962 } else {
7963 char data = buf->ReadByte();
7964 GRFPalette pal = GRFP_BLT_UNSET;
7965 switch (data) {
7966 case '8': pal = GRFP_BLT_UNSET; break;
7967 case '3': pal = GRFP_BLT_32BPP; break;
7968 default:
7969 grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'BLTR', ignoring this field", data);
7970 return true;
7971 }
7972 _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
7973 _cur.grfconfig->palette |= pal;
7974 }
7975 return true;
7976 }
7977
7979 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
7980 {
7981 if (len != 4) {
7982 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got " PRINTF_SIZE ", ignoring this field", len);
7983 buf->Skip(len);
7984 } else {
7985 /* Set min_loadable_version as well (default to minimal compatibility) */
7986 _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7987 }
7988 return true;
7989 }
7990
7992 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
7993 {
7994 if (len != 4) {
7995 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got " PRINTF_SIZE ", ignoring this field", len);
7996 buf->Skip(len);
7997 } else {
7998 _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7999 if (_cur.grfconfig->version == 0) {
8000 grfmsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
8001 _cur.grfconfig->min_loadable_version = 0;
8002 }
8003 if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
8004 grfmsg(2, "StaticGRFInfo: 'MINV' defined as %d, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
8005 _cur.grfconfig->min_loadable_version = _cur.grfconfig->version;
8006 }
8007 }
8008 return true;
8009 }
8010
8011 static GRFParameterInfo *_cur_parameter;
8012
8014 static bool ChangeGRFParamName(byte langid, const char *str)
8015 {
8016 AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
8017 return true;
8018 }
8019
8021 static bool ChangeGRFParamDescription(byte langid, const char *str)
8022 {
8023 AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
8024 return true;
8025 }
8026
8028 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
8029 {
8030 if (len != 1) {
8031 grfmsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got " PRINTF_SIZE ", ignoring this field", len);
8032 buf->Skip(len);
8033 } else {
8034 GRFParameterType type = (GRFParameterType)buf->ReadByte();
8035 if (type < PTYPE_END) {
8036 _cur_parameter->type = type;
8037 } else {
8038 grfmsg(3, "StaticGRFInfo: unknown parameter type %d, ignoring this field", type);
8039 }
8040 }
8041 return true;
8042 }
8043
8045 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
8046 {
8047 if (_cur_parameter->type != PTYPE_UINT_ENUM) {
8048 grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8049 buf->Skip(len);
8050 } else if (len != 8) {
8051 grfmsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got " PRINTF_SIZE ", ignoring this field", len);
8052 buf->Skip(len);
8053 } else {
8054 uint32 min_value = buf->ReadDWord();
8055 uint32 max_value = buf->ReadDWord();
8056 if (min_value <= max_value) {
8057 _cur_parameter->min_value = min_value;
8058 _cur_parameter->max_value = max_value;
8059 } else {
8060 grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8061 }
8062 }
8063 return true;
8064 }
8065
8067 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
8068 {
8069 if (len < 1 || len > 3) {
8070 grfmsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got " PRINTF_SIZE ", ignoring this field", len);
8071 buf->Skip(len);
8072 } else {
8073 byte param_nr = buf->ReadByte();
8074 if (param_nr >= lengthof(_cur.grfconfig->param)) {
8075 grfmsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param %d, ignoring this field", param_nr);
8076 buf->Skip(len - 1);
8077 } else {
8078 _cur_parameter->param_nr = param_nr;
8079 if (len >= 2) _cur_parameter->first_bit = std::min<byte>(buf->ReadByte(), 31);
8080 if (len >= 3) _cur_parameter->num_bit = std::min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
8081 }
8082 }
8083
8084 return true;
8085 }
8086
8088 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
8089 {
8090 if (len != 4) {
8091 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got " PRINTF_SIZE ", ignoring this field", len);
8092 buf->Skip(len);
8093 } else {
8094 _cur_parameter->def_value = buf->ReadDWord();
8095 }
8096 _cur.grfconfig->has_param_defaults = true;
8097 return true;
8098 }
8099
8100 typedef bool (*DataHandler)(size_t, ByteReader *);
8101 typedef bool (*TextHandler)(byte, const char *str);
8102 typedef bool (*BranchHandler)(ByteReader *);
8103
8111 struct AllowedSubtags {
8113 AllowedSubtags() :
8114 id(0),
8115 type(0)
8116 {}
8117
8123 AllowedSubtags(uint32 id, DataHandler handler) :
8124 id(id),
8125 type('B')
8126 {
8127 this->handler.data = handler;
8128 }
8129
8135 AllowedSubtags(uint32 id, TextHandler handler) :
8136 id(id),
8137 type('T')
8138 {
8139 this->handler.text = handler;
8140 }
8141
8147 AllowedSubtags(uint32 id, BranchHandler handler) :
8148 id(id),
8149 type('C')
8150 {
8151 this->handler.call_handler = true;
8152 this->handler.u.branch = handler;
8153 }
8154
8160 AllowedSubtags(uint32 id, AllowedSubtags *subtags) :
8161 id(id),
8162 type('C')
8163 {
8164 this->handler.call_handler = false;
8165 this->handler.u.subtags = subtags;
8166 }
8167
8168 uint32 id;
8169 byte type;
8170 union {
8171 DataHandler data;
8172 TextHandler text;
8173 struct {
8174 union {
8175 BranchHandler branch;
8176 AllowedSubtags *subtags;
8177 } u;
8178 bool call_handler;
8179 };
8180 } handler;
8181 };
8182
8183 static bool SkipUnknownInfo(ByteReader *buf, byte type);
8184 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
8185
8192 static bool ChangeGRFParamValueNames(ByteReader *buf)
8193 {
8194 byte type = buf->ReadByte();
8195 while (type != 0) {
8196 uint32 id = buf->ReadDWord();
8197 if (type != 'T' || id > _cur_parameter->max_value) {
8198 grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8199 if (!SkipUnknownInfo(buf, type)) return false;
8200 type = buf->ReadByte();
8201 continue;
8202 }
8203
8204 byte langid = buf->ReadByte();
8205 const char *name_string = buf->ReadString();
8206
8207 std::pair<uint32, GRFTextList> *val_name = _cur_parameter->value_names.Find(id);
8208 if (val_name != _cur_parameter->value_names.End()) {
8209 AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8210 } else {
8211 GRFTextList list;
8212 AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8213 _cur_parameter->value_names.Insert(id, list);
8214 }
8215
8216 type = buf->ReadByte();
8217 }
8218 return true;
8219 }
8220
8222 AllowedSubtags _tags_parameters[] = {
8223 AllowedSubtags('NAME', ChangeGRFParamName),
8224 AllowedSubtags('DESC', ChangeGRFParamDescription),
8225 AllowedSubtags('TYPE', ChangeGRFParamType),
8226 AllowedSubtags('LIMI', ChangeGRFParamLimits),
8227 AllowedSubtags('MASK', ChangeGRFParamMask),
8228 AllowedSubtags('VALU', ChangeGRFParamValueNames),
8229 AllowedSubtags('DFLT', ChangeGRFParamDefault),
8230 AllowedSubtags()
8231 };
8232
8239 static bool HandleParameterInfo(ByteReader *buf)
8240 {
8241 byte type = buf->ReadByte();
8242 while (type != 0) {
8243 uint32 id = buf->ReadDWord();
8244 if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8245 grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8246 if (!SkipUnknownInfo(buf, type)) return false;
8247 type = buf->ReadByte();
8248 continue;
8249 }
8250
8251 if (id >= _cur.grfconfig->param_info.size()) {
8252 _cur.grfconfig->param_info.resize(id + 1);
8253 }
8254 if (_cur.grfconfig->param_info[id] == nullptr) {
8255 _cur.grfconfig->param_info[id] = new GRFParameterInfo(id);
8256 }
8257 _cur_parameter = _cur.grfconfig->param_info[id];
8258 /* Read all parameter-data and process each node. */
8259 if (!HandleNodes(buf, _tags_parameters)) return false;
8260 type = buf->ReadByte();
8261 }
8262 return true;
8263 }
8264
8266 AllowedSubtags _tags_info[] = {
8267 AllowedSubtags('NAME', ChangeGRFName),
8268 AllowedSubtags('DESC', ChangeGRFDescription),
8269 AllowedSubtags('URL_', ChangeGRFURL),
8270 AllowedSubtags('NPAR', ChangeGRFNumUsedParams),
8271 AllowedSubtags('PALS', ChangeGRFPalette),
8272 AllowedSubtags('BLTR', ChangeGRFBlitter),
8273 AllowedSubtags('VRSN', ChangeGRFVersion),
8274 AllowedSubtags('MINV', ChangeGRFMinVersion),
8275 AllowedSubtags('PARA', HandleParameterInfo),
8276 AllowedSubtags()
8277 };
8278
8280 AllowedSubtags _tags_root[] = {
8281 AllowedSubtags('INFO', _tags_info),
8282 AllowedSubtags()
8283 };
8284
8285
8292 static bool SkipUnknownInfo(ByteReader *buf, byte type)
8293 {
8294 /* type and id are already read */
8295 switch (type) {
8296 case 'C': {
8297 byte new_type = buf->ReadByte();
8298 while (new_type != 0) {
8299 buf->ReadDWord(); // skip the id
8300 if (!SkipUnknownInfo(buf, new_type)) return false;
8301 new_type = buf->ReadByte();
8302 }
8303 break;
8304 }
8305
8306 case 'T':
8307 buf->ReadByte(); // lang
8308 buf->ReadString(); // actual text
8309 break;
8310
8311 case 'B': {
8312 uint16 size = buf->ReadWord();
8313 buf->Skip(size);
8314 break;
8315 }
8316
8317 default:
8318 return false;
8319 }
8320
8321 return true;
8322 }
8323
8332 static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
8333 {
8334 uint i = 0;
8335 AllowedSubtags *tag;
8336 while ((tag = &subtags[i++])->type != 0) {
8337 if (tag->id != BSWAP32(id) || tag->type != type) continue;
8338 switch (type) {
8339 default: NOT_REACHED();
8340
8341 case 'T': {
8342 byte langid = buf->ReadByte();
8343 return tag->handler.text(langid, buf->ReadString());
8344 }
8345
8346 case 'B': {
8347 size_t len = buf->ReadWord();
8348 if (buf->Remaining() < len) return false;
8349 return tag->handler.data(len, buf);
8350 }
8351
8352 case 'C': {
8353 if (tag->handler.call_handler) {
8354 return tag->handler.u.branch(buf);
8355 }
8356 return HandleNodes(buf, tag->handler.u.subtags);
8357 }
8358 }
8359 }
8360 grfmsg(2, "StaticGRFInfo: unknown type/id combination found, type=%c, id=%x", type, id);
8361 return SkipUnknownInfo(buf, type);
8362 }
8363
8370 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
8371 {
8372 byte type = buf->ReadByte();
8373 while (type != 0) {
8374 uint32 id = buf->ReadDWord();
8375 if (!HandleNode(type, id, buf, subtags)) return false;
8376 type = buf->ReadByte();
8377 }
8378 return true;
8379 }
8380
8385 static void StaticGRFInfo(ByteReader *buf)
8386 {
8387 /* <14> <type> <id> <text/data...> */
8388 HandleNodes(buf, _tags_root);
8389 }
8390
8396 static void GRFUnsafe(ByteReader *buf)
8397 {
8398 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8399
8400 /* Skip remainder of GRF */
8401 _cur.skip_sprites = -1;
8402 }
8403
8404
8406 static void InitializeGRFSpecial()
8407 {
8408 _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1U : 0U) << 0x0C) // keepsmallairport
8409 | (1U << 0x0D) // newairports
8410 | (1U << 0x0E) // largestations
8411 | ((_settings_game.construction.max_bridge_length > 16 ? 1U : 0U) << 0x0F) // longbridges
8412 | (0U << 0x10) // loadtime
8413 | (1U << 0x12) // presignals
8414 | (1U << 0x13) // extpresignals
8415 | ((_settings_game.vehicle.never_expire_vehicles ? 1U : 0U) << 0x16) // enginespersist
8416 | (1U << 0x1B) // multihead
8417 | (1U << 0x1D) // lowmemory
8418 | (1U << 0x1E); // generalfixes
8419
8420 _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1U : 0U) << 0x07) // moreairports - based on units of noise
8421 | (1U << 0x08) // mammothtrains
8422 | (1U << 0x09) // trainrefit
8423 | (0U << 0x0B) // subsidiaries
8424 | ((_settings_game.order.gradual_loading ? 1U : 0U) << 0x0C) // gradualloading
8425 | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8426 | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8427 | (1U << 0x14) // bridgespeedlimits
8428 | (1U << 0x16) // eternalgame
8429 | (1U << 0x17) // newtrains
8430 | (1U << 0x18) // newrvs
8431 | (1U << 0x19) // newships
8432 | (1U << 0x1A) // newplanes
8433 | ((_settings_game.construction.train_signal_side == 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8434 | ((_settings_game.vehicle.disable_elrails ? 0U : 1U) << 0x1C); // electrifiedrailway
8435
8436 _ttdpatch_flags[2] = (1U << 0x01) // loadallgraphics - obsolote
8437 | (1U << 0x03) // semaphores
8438 | (1U << 0x0A) // newobjects
8439 | (0U << 0x0B) // enhancedgui
8440 | (0U << 0x0C) // newagerating
8441 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x0D) // buildonslopes
8442 | (1U << 0x0E) // fullloadany
8443 | (1U << 0x0F) // planespeed
8444 | (0U << 0x10) // moreindustriesperclimate - obsolete
8445 | (0U << 0x11) // moretoylandfeatures
8446 | (1U << 0x12) // newstations
8447 | (1U << 0x13) // tracktypecostdiff
8448 | (1U << 0x14) // manualconvert
8449 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x15) // buildoncoasts
8450 | (1U << 0x16) // canals
8451 | (1U << 0x17) // newstartyear
8452 | ((_settings_game.vehicle.freight_trains > 1 ? 1U : 0U) << 0x18) // freighttrains
8453 | (1U << 0x19) // newhouses
8454 | (1U << 0x1A) // newbridges
8455 | (1U << 0x1B) // newtownnames
8456 | (1U << 0x1C) // moreanimation
8457 | ((_settings_game.vehicle.wagon_speed_limits ? 1U : 0U) << 0x1D) // wagonspeedlimits
8458 | (1U << 0x1E) // newshistory
8459 | (0U << 0x1F); // custombridgeheads
8460
8461 _ttdpatch_flags[3] = (0U << 0x00) // newcargodistribution
8462 | (1U << 0x01) // windowsnap
8463 | ((_settings_game.economy.allow_town_roads || _generating_world ? 0U : 1U) << 0x02) // townbuildnoroad
8464 | (1U << 0x03) // pathbasedsignalling
8465 | (0U << 0x04) // aichoosechance
8466 | (1U << 0x05) // resolutionwidth
8467 | (1U << 0x06) // resolutionheight
8468 | (1U << 0x07) // newindustries
8469 | ((_settings_game.order.improved_load ? 1U : 0U) << 0x08) // fifoloading
8470 | (0U << 0x09) // townroadbranchprob
8471 | (0U << 0x0A) // tempsnowline
8472 | (1U << 0x0B) // newcargo
8473 | (1U << 0x0C) // enhancemultiplayer
8474 | (1U << 0x0D) // onewayroads
8475 | (1U << 0x0E) // irregularstations
8476 | (1U << 0x0F) // statistics
8477 | (1U << 0x10) // newsounds
8478 | (1U << 0x11) // autoreplace
8479 | (1U << 0x12) // autoslope
8480 | (0U << 0x13) // followvehicle
8481 | (1U << 0x14) // trams
8482 | (0U << 0x15) // enhancetunnels
8483 | (1U << 0x16) // shortrvs
8484 | (1U << 0x17) // articulatedrvs
8485 | ((_settings_game.vehicle.dynamic_engines ? 1U : 0U) << 0x18) // dynamic engines
8486 | (1U << 0x1E) // variablerunningcosts
8487 | (1U << 0x1F); // any switch is on
8488
8489 _ttdpatch_flags[4] = (1U << 0x00) // larger persistent storage
8490 | ((_settings_game.economy.inflation ? 1U : 0U) << 0x01) // inflation is on
8491 | (1U << 0x02); // extended string range
8492 }
8493
8495 static void ResetCustomStations()
8496 {
8497 for (GRFFile * const file : _grf_files) {
8498 StationSpec **&stations = file->stations;
8499 if (stations == nullptr) continue;
8500 for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
8501 if (stations[i] == nullptr) continue;
8502 StationSpec *statspec = stations[i];
8503
8504 /* Release this station */
8505 delete statspec;
8506 }
8507
8508 /* Free and reset the station data */
8509 free(stations);
8510 stations = nullptr;
8511 }
8512 }
8513
8515 static void ResetCustomHouses()
8516 {
8517 for (GRFFile * const file : _grf_files) {
8518 HouseSpec **&housespec = file->housespec;
8519 if (housespec == nullptr) continue;
8520 for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8521 free(housespec[i]);
8522 }
8523
8524 free(housespec);
8525 housespec = nullptr;
8526 }
8527 }
8528
8530 static void ResetCustomAirports()
8531 {
8532 for (GRFFile * const file : _grf_files) {
8533 AirportSpec **aslist = file->airportspec;
8534 if (aslist != nullptr) {
8535 for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8536 AirportSpec *as = aslist[i];
8537
8538 if (as != nullptr) {
8539 /* We need to remove the tiles layouts */
8540 for (int j = 0; j < as->num_table; j++) {
8541 /* remove the individual layouts */
8542 free(as->table[j]);
8543 }
8544 free(as->table);
8545 free(as->depot_table);
8546 free(as->rotation);
8547
8548 free(as);
8549 }
8550 }
8551 free(aslist);
8552 file->airportspec = nullptr;
8553 }
8554
8555 AirportTileSpec **&airporttilespec = file->airtspec;
8556 if (airporttilespec != nullptr) {
8557 for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8558 free(airporttilespec[i]);
8559 }
8560 free(airporttilespec);
8561 airporttilespec = nullptr;
8562 }
8563 }
8564 }
8565
8567 static void ResetCustomIndustries()
8568 {
8569 for (GRFFile * const file : _grf_files) {
8570 IndustrySpec **&industryspec = file->industryspec;
8571 IndustryTileSpec **&indtspec = file->indtspec;
8572
8573 /* We are verifiying both tiles and industries specs loaded from the grf file
8574 * First, let's deal with industryspec */
8575 if (industryspec != nullptr) {
8576 for (uint i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8577 IndustrySpec *ind = industryspec[i];
8578 delete ind;
8579 }
8580
8581 free(industryspec);
8582 industryspec = nullptr;
8583 }
8584
8585 if (indtspec == nullptr) continue;
8586 for (uint i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8587 free(indtspec[i]);
8588 }
8589
8590 free(indtspec);
8591 indtspec = nullptr;
8592 }
8593 }
8594
8596 static void ResetCustomObjects()
8597 {
8598 for (GRFFile * const file : _grf_files) {
8599 ObjectSpec **&objectspec = file->objectspec;
8600 if (objectspec == nullptr) continue;
8601 for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8602 free(objectspec[i]);
8603 }
8604
8605 free(objectspec);
8606 objectspec = nullptr;
8607 }
8608 }
8609
8611 static void ResetNewGRF()
8612 {
8613 for (GRFFile * const file : _grf_files) {
8614 delete file;
8615 }
8616
8617 _grf_files.clear();
8618 _cur.grffile = nullptr;
8619 }
8620
8622 static void ResetNewGRFErrors()
8623 {
8624 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8625 if (!HasBit(c->flags, GCF_COPY) && c->error != nullptr) {
8626 delete c->error;
8627 c->error = nullptr;
8628 }
8629 }
8630 }
8631
8635 void ResetNewGRFData()
8636 {
8637 CleanUpStrings();
8638 CleanUpGRFTownNames();
8639
8640 /* Copy/reset original engine info data */
8641 SetupEngines();
8642
8643 /* Copy/reset original bridge info data */
8644 ResetBridges();
8645
8646 /* Reset rail type information */
8647 ResetRailTypes();
8648
8649 /* Copy/reset original road type info data */
8650 ResetRoadTypes();
8651
8652 /* Allocate temporary refit/cargo class data */
8653 _gted = CallocT<GRFTempEngineData>(Engine::GetPoolSize());
8654
8655 /* Fill rail type label temporary data for default trains */
8656 for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8657 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8658 }
8659
8660 /* Reset GRM reservations */
8661 memset(&_grm_engines, 0, sizeof(_grm_engines));
8662 memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8663
8664 /* Reset generic feature callback lists */
8665 ResetGenericCallbacks();
8666
8667 /* Reset price base data */
8668 ResetPriceBaseMultipliers();
8669
8670 /* Reset the curencies array */
8671 ResetCurrencies();
8672
8673 /* Reset the house array */
8674 ResetCustomHouses();
8675 ResetHouses();
8676
8677 /* Reset the industries structures*/
8678 ResetCustomIndustries();
8679 ResetIndustries();
8680
8681 /* Reset the objects. */
8682 ObjectClass::Reset();
8683 ResetCustomObjects();
8684 ResetObjects();
8685
8686 /* Reset station classes */
8687 StationClass::Reset();
8688 ResetCustomStations();
8689
8690 /* Reset airport-related structures */
8691 AirportClass::Reset();
8692 ResetCustomAirports();
8693 AirportSpec::ResetAirports();
8694 AirportTileSpec::ResetAirportTiles();
8695
8696 /* Reset canal sprite groups and flags */
8697 memset(_water_feature, 0, sizeof(_water_feature));
8698
8699 /* Reset the snowline table. */
8700 ClearSnowLine();
8701
8702 /* Reset NewGRF files */
8703 ResetNewGRF();
8704
8705 /* Reset NewGRF errors. */
8706 ResetNewGRFErrors();
8707
8708 /* Set up the default cargo types */
8709 SetupCargoForClimate(_settings_game.game_creation.landscape);
8710
8711 /* Reset misc GRF features and train list display variables */
8712 _misc_grf_features = 0;
8713
8714 _loaded_newgrf_features.has_2CC = false;
8715 _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8716 _loaded_newgrf_features.shore = SHORE_REPLACE_NONE;
8717 _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NONE;
8718
8719 /* Clear all GRF overrides */
8720 _grf_id_overrides.clear();
8721
8722 InitializeSoundPool();
8723 _spritegroup_pool.CleanPool();
8724 }
8725
8729 void ResetPersistentNewGRFData()
8730 {
8731 /* Reset override managers */
8732 _engine_mngr.ResetToDefaultMapping();
8733 _house_mngr.ResetMapping();
8734 _industry_mngr.ResetMapping();
8735 _industile_mngr.ResetMapping();
8736 _airport_mngr.ResetMapping();
8737 _airporttile_mngr.ResetMapping();
8738 }
8739
8744 static void BuildCargoTranslationMap()
8745 {
8746 memset(_cur.grffile->cargo_map, 0xFF, sizeof(_cur.grffile->cargo_map));
8747
8748 for (CargoID c = 0; c < NUM_CARGO; c++) {
8749 const CargoSpec *cs = CargoSpec::Get(c);
8750 if (!cs->IsValid()) continue;
8751
8752 if (_cur.grffile->cargo_list.size() == 0) {
8753 /* Default translation table, so just a straight mapping to bitnum */
8754 _cur.grffile->cargo_map[c] = cs->bitnum;
8755 } else {
8756 /* Check the translation table for this cargo's label */
8757 int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8758 if (idx >= 0) _cur.grffile->cargo_map[c] = idx;
8759 }
8760 }
8761 }
8762
8767 static void InitNewGRFFile(const GRFConfig *config)
8768 {
8769 GRFFile *newfile = GetFileByFilename(config->filename);
8770 if (newfile != nullptr) {
8771 /* We already loaded it once. */
8772 _cur.grffile = newfile;
8773 return;
8774 }
8775
8776 newfile = new GRFFile(config);
8777 _grf_files.push_back(_cur.grffile = newfile);
8778 }
8779
8784 GRFFile::GRFFile(const GRFConfig *config)
8785 {
8786 this->filename = stredup(config->filename);
8787 this->grfid = config->ident.grfid;
8788
8789 /* Initialise local settings to defaults */
8790 this->traininfo_vehicle_pitch = 0;
8791 this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8792
8793 /* Mark price_base_multipliers as 'not set' */
8794 for (Price i = PR_BEGIN; i < PR_END; i++) {
8795 this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8796 }
8797
8798 /* Initialise rail type map with default rail types */
8799 std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8800 this->railtype_map[0] = RAILTYPE_RAIL;
8801 this->railtype_map[1] = RAILTYPE_ELECTRIC;
8802 this->railtype_map[2] = RAILTYPE_MONO;
8803 this->railtype_map[3] = RAILTYPE_MAGLEV;
8804
8805 /* Initialise road type map with default road types */
8806 std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8807 this->roadtype_map[0] = ROADTYPE_ROAD;
8808
8809 /* Initialise tram type map with default tram types */
8810 std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8811 this->tramtype_map[0] = ROADTYPE_TRAM;
8812
8813 /* Copy the initial parameter list
8814 * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8815 static_assert(lengthof(this->param) == lengthof(config->param) && lengthof(this->param) == 0x80);
8816
8817 assert(config->num_params <= lengthof(config->param));
8818 this->param_end = config->num_params;
8819 if (this->param_end > 0) {
8820 MemCpyT(this->param, config->param, this->param_end);
8821 }
8822 }
8823
8824 GRFFile::~GRFFile()
8825 {
8826 free(this->filename);
8827 delete[] this->language_map;
8828 }
8829
8830
8834 static void CalculateRefitMasks()
8835 {
8836 CargoTypes original_known_cargoes = 0;
8837 for (int ct = 0; ct != NUM_ORIGINAL_CARGO; ++ct) {
8838 CargoID cid = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ct));
8839 if (cid != CT_INVALID) SetBit(original_known_cargoes, cid);
8840 }
8841
8842 for (Engine *e : Engine::Iterate()) {
8843 EngineID engine = e->index;
8844 EngineInfo *ei = &e->info;
8845 bool only_defaultcargo;
8846
8847 /* If the NewGRF did not set any cargo properties, we apply default values. */
8848 if (_gted[engine].defaultcargo_grf == nullptr) {
8849 /* If the vehicle has any capacity, apply the default refit masks */
8850 if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
8851 static constexpr byte T = 1 << LT_TEMPERATE;
8852 static constexpr byte A = 1 << LT_ARCTIC;
8853 static constexpr byte S = 1 << LT_TROPIC;
8854 static constexpr byte Y = 1 << LT_TOYLAND;
8855 static const struct DefaultRefitMasks {
8856 byte climate;
8857 CargoType cargo_type;
8858 CargoTypes cargo_allowed;
8859 CargoTypes cargo_disallowed;
8860 } _default_refit_masks[] = {
8861 {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
8862 {T | A | S , CT_MAIL, CC_MAIL, 0},
8863 {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
8864 { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
8865 {T | A , CT_COAL, CC_BULK, 0},
8866 { S , CT_COPPER_ORE, CC_BULK, 0},
8867 { Y, CT_SUGAR, CC_BULK, 0},
8868 {T | A | S , CT_OIL, CC_LIQUID, 0},
8869 { Y, CT_COLA, CC_LIQUID, 0},
8870 {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8871 { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
8872 { A | S , CT_FOOD, CC_REFRIGERATED, 0},
8873 { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8874 };
8875
8876 if (e->type == VEH_AIRCRAFT) {
8877 /* Aircraft default to "light" cargoes */
8878 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
8879 _gted[engine].cargo_disallowed = CC_LIQUID;
8880 } else if (e->type == VEH_SHIP) {
8881 switch (ei->cargo_type) {
8882 case CT_PASSENGERS:
8883 /* Ferries */
8884 _gted[engine].cargo_allowed = CC_PASSENGERS;
8885 _gted[engine].cargo_disallowed = 0;
8886 break;
8887 case CT_OIL:
8888 /* Tankers */
8889 _gted[engine].cargo_allowed = CC_LIQUID;
8890 _gted[engine].cargo_disallowed = 0;
8891 break;
8892 default:
8893 /* Cargo ships */
8894 if (_settings_game.game_creation.landscape == LT_TOYLAND) {
8895 /* No tanker in toyland :( */
8896 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8897 _gted[engine].cargo_disallowed = CC_PASSENGERS;
8898 } else {
8899 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
8900 _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
8901 }
8902 break;
8903 }
8904 e->u.ship.old_refittable = true;
8905 } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
8906 /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
8907 * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
8908 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8909 _gted[engine].cargo_disallowed = 0;
8910 } else {
8911 /* Train wagons and road vehicles are classified by their default cargo type */
8912 for (const auto &drm : _default_refit_masks) {
8913 if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
8914 if (drm.cargo_type != ei->cargo_type) continue;
8915
8916 _gted[engine].cargo_allowed = drm.cargo_allowed;
8917 _gted[engine].cargo_disallowed = drm.cargo_disallowed;
8918 break;
8919 }
8920
8921 /* All original cargoes have specialised vehicles, so exclude them */
8922 _gted[engine].ctt_exclude_mask = original_known_cargoes;
8923 }
8924 }
8925 _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
8926
8927 /* Translate cargo_type using the original climate-specific cargo table. */
8928 ei->cargo_type = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ei->cargo_type));
8929 if (ei->cargo_type != CT_INVALID) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
8930 }
8931
8932 /* Compute refittability */
8933 {
8934 CargoTypes mask = 0;
8935 CargoTypes not_mask = 0;
8936 CargoTypes xor_mask = ei->refit_mask;
8937
8938 /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
8939 * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
8940 only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
8941
8942 if (_gted[engine].cargo_allowed != 0) {
8943 /* Build up the list of cargo types from the set cargo classes. */
8944 for (const CargoSpec *cs : CargoSpec::Iterate()) {
8945 if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
8946 if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
8947 }
8948 }
8949
8950 ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
8951
8952 /* Apply explicit refit includes/excludes. */
8953 ei->refit_mask |= _gted[engine].ctt_include_mask;
8954 ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
8955 }
8956
8957 /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
8958 if (ei->cargo_type != CT_INVALID && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = CT_INVALID;
8959
8960 /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
8961 * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
8962 if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && ei->cargo_type != CT_INVALID && !HasBit(ei->refit_mask, ei->cargo_type)) {
8963 ei->cargo_type = CT_INVALID;
8964 }
8965
8966 /* Check if this engine's cargo type is valid. If not, set to the first refittable
8967 * cargo type. Finally disable the vehicle, if there is still no cargo. */
8968 if (ei->cargo_type == CT_INVALID && ei->refit_mask != 0) {
8969 /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
8970 const uint8 *cargo_map_for_first_refittable = nullptr;
8971 {
8972 const GRFFile *file = _gted[engine].defaultcargo_grf;
8973 if (file == nullptr) file = e->GetGRF();
8974 if (file != nullptr && file->grf_version >= 8 && file->cargo_list.size() != 0) {
8975 cargo_map_for_first_refittable = file->cargo_map;
8976 }
8977 }
8978
8979 if (cargo_map_for_first_refittable != nullptr) {
8980 /* Use first refittable cargo from cargo translation table */
8981 byte best_local_slot = 0xFF;
8982 for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
8983 byte local_slot = cargo_map_for_first_refittable[cargo_type];
8984 if (local_slot < best_local_slot) {
8985 best_local_slot = local_slot;
8986 ei->cargo_type = cargo_type;
8987 }
8988 }
8989 }
8990
8991 if (ei->cargo_type == CT_INVALID) {
8992 /* Use first refittable cargo slot */
8993 ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
8994 }
8995 }
8996 if (ei->cargo_type == CT_INVALID) ei->climates = 0;
8997
8998 /* Clear refit_mask for not refittable ships */
8999 if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
9000 ei->refit_mask = 0;
9001 }
9002 }
9003 }
9004
9006 static void FinaliseCanals()
9007 {
9008 for (uint i = 0; i < CF_END; i++) {
9009 if (_water_feature[i].grffile != nullptr) {
9010 _water_feature[i].callback_mask = _water_feature[i].grffile->canal_local_properties[i].callback_mask;
9011 _water_feature[i].flags = _water_feature[i].grffile->canal_local_properties[i].flags;
9012 }
9013 }
9014 }
9015
9017 static void FinaliseEngineArray()
9018 {
9019 for (Engine *e : Engine::Iterate()) {
9020 if (e->GetGRF() == nullptr) {
9021 const EngineIDMapping &eid = _engine_mngr[e->index];
9022 if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
9023 e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
9024 }
9025 }
9026
9027 /* Do final mapping on variant engine ID and set appropriate flags on variant engine */
9028 if (e->info.variant_id != INVALID_ENGINE) {
9029 e->info.variant_id = GetNewEngineID(e->grf_prop.grffile, e->type, e->info.variant_id);
9030 if (e->info.variant_id != INVALID_ENGINE) {
9031 Engine::Get(e->info.variant_id)->display_flags |= EngineDisplayFlags::HasVariants | EngineDisplayFlags::IsFolded;
9032 }
9033 }
9034
9035 if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
9036
9037 /* Skip wagons, there livery is defined via the engine */
9038 if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
9039 LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, nullptr);
9040 SetBit(_loaded_newgrf_features.used_liveries, ls);
9041 /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9042
9043 if (e->type == VEH_TRAIN) {
9044 SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
9045 switch (ls) {
9046 case LS_STEAM:
9047 case LS_DIESEL:
9048 case LS_ELECTRIC:
9049 case LS_MONORAIL:
9050 case LS_MAGLEV:
9051 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
9052 break;
9053
9054 case LS_DMU:
9055 case LS_EMU:
9056 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
9057 break;
9058
9059 default: NOT_REACHED();
9060 }
9061 }
9062 }
9063 }
9064 }
9065
9067 static void FinaliseCargoArray()
9068 {
9069 for (CargoID c = 0; c < NUM_CARGO; c++) {
9070 CargoSpec *cs = CargoSpec::Get(c);
9071 if (!cs->IsValid()) {
9072 cs->name = cs->name_single = cs->units_volume = STR_NEWGRF_INVALID_CARGO;
9073 cs->quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9074 cs->abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9075 }
9076 }
9077 }
9078
9090 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
9091 {
9092 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9093 (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9094 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9095 (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9096 next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9097 hs->enabled = false;
9098 if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9099 return false;
9100 }
9101
9102 /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9103 * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9104 * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9105 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9106 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9107 hs->enabled = false;
9108 if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines multitile house {} with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
9109 return false;
9110 }
9111
9112 /* Substitute type is also used for override, and having an override with a different size causes crashes.
9113 * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9114 if (filename != nullptr && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9115 hs->enabled = false;
9116 Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9117 return false;
9118 }
9119
9120 /* Make sure that additional parts of multitile houses are not available. */
9121 if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9122 hs->enabled = false;
9123 if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
9124 return false;
9125 }
9126
9127 return true;
9128 }
9129
9136 static void EnsureEarlyHouse(HouseZones bitmask)
9137 {
9138 Year min_year = MAX_YEAR;
9139
9140 for (int i = 0; i < NUM_HOUSES; i++) {
9141 HouseSpec *hs = HouseSpec::Get(i);
9142 if (hs == nullptr || !hs->enabled) continue;
9143 if ((hs->building_availability & bitmask) != bitmask) continue;
9144 if (hs->min_year < min_year) min_year = hs->min_year;
9145 }
9146
9147 if (min_year == 0) return;
9148
9149 for (int i = 0; i < NUM_HOUSES; i++) {
9150 HouseSpec *hs = HouseSpec::Get(i);
9151 if (hs == nullptr || !hs->enabled) continue;
9152 if ((hs->building_availability & bitmask) != bitmask) continue;
9153 if (hs->min_year == min_year) hs->min_year = 0;
9154 }
9155 }
9156
9163 static void FinaliseHouseArray()
9164 {
9165 /* If there are no houses with start dates before 1930, then all houses
9166 * with start dates of 1930 have them reset to 0. This is in order to be
9167 * compatible with TTDPatch, where if no houses have start dates before
9168 * 1930 and the date is before 1930, the game pretends that this is 1930.
9169 * If there have been any houses defined with start dates before 1930 then
9170 * the dates are left alone.
9171 * On the other hand, why 1930? Just 'fix' the houses with the lowest
9172 * minimum introduction date to 0.
9173 */
9174 for (GRFFile * const file : _grf_files) {
9175 HouseSpec **&housespec = file->housespec;
9176 if (housespec == nullptr) continue;
9177
9178 for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) {
9179 HouseSpec *hs = housespec[i];
9180
9181 if (hs == nullptr) continue;
9182
9183 const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : nullptr);
9184 const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : nullptr);
9185 const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : nullptr);
9186
9187 if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9188
9189 _house_mngr.SetEntitySpec(hs);
9190 }
9191 }
9192
9193 for (int i = 0; i < NUM_HOUSES; i++) {
9194 HouseSpec *hs = HouseSpec::Get(i);
9195 const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9196 const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9197 const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9198
9199 /* We need to check all houses again to we are sure that multitile houses
9200 * did get consecutive IDs and none of the parts are missing. */
9201 if (!IsHouseSpecValid(hs, next1, next2, next3, nullptr)) {
9202 /* GetHouseNorthPart checks 3 houses that are directly before
9203 * it in the house pool. If any of those houses have multi-tile
9204 * flags set it assumes it's part of a multitile house. Since
9205 * we can have invalid houses in the pool marked as disabled, we
9206 * don't want to have them influencing valid tiles. As such set
9207 * building_flags to zero here to make sure any house following
9208 * this one in the pool is properly handled as 1x1 house. */
9209 hs->building_flags = TILE_NO_FLAG;
9210 }
9211 }
9212
9213 HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9214 EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9215 EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9216 EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9217 EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9218 EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9219
9220 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9221 EnsureEarlyHouse(HZ_ZON1 | HZ_SUBARTC_ABOVE);
9222 EnsureEarlyHouse(HZ_ZON2 | HZ_SUBARTC_ABOVE);
9223 EnsureEarlyHouse(HZ_ZON3 | HZ_SUBARTC_ABOVE);
9224 EnsureEarlyHouse(HZ_ZON4 | HZ_SUBARTC_ABOVE);
9225 EnsureEarlyHouse(HZ_ZON5 | HZ_SUBARTC_ABOVE);
9226 }
9227 }
9228
9234 static void FinaliseIndustriesArray()
9235 {
9236 for (GRFFile * const file : _grf_files) {
9237 IndustrySpec **&industryspec = file->industryspec;
9238 IndustryTileSpec **&indtspec = file->indtspec;
9239 if (industryspec != nullptr) {
9240 for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
9241 IndustrySpec *indsp = industryspec[i];
9242
9243 if (indsp != nullptr && indsp->enabled) {
9244 StringID strid;
9245 /* process the conversion of text at the end, so to be sure everything will be fine
9246 * and available. Check if it does not return undefind marker, which is a very good sign of a
9247 * substitute industry who has not changed the string been examined, thus using it as such */
9248 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9249 if (strid != STR_UNDEFINED) indsp->name = strid;
9250
9251 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9252 if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9253
9254 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9255 if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9256
9257 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9258 if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9259
9260 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9261 if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9262
9263 if (indsp->station_name != STR_NULL) {
9264 /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9265 * station's name. Don't want to lose the value, therefore, do not process. */
9266 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9267 if (strid != STR_UNDEFINED) indsp->station_name = strid;
9268 }
9269
9270 _industry_mngr.SetEntitySpec(indsp);
9271 }
9272 }
9273 }
9274
9275 if (indtspec != nullptr) {
9276 for (int i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
9277 IndustryTileSpec *indtsp = indtspec[i];
9278 if (indtsp != nullptr) {
9279 _industile_mngr.SetEntitySpec(indtsp);
9280 }
9281 }
9282 }
9283 }
9284
9285 for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
9286 IndustrySpec *indsp = &_industry_specs[j];
9287 if (indsp->enabled && indsp->grf_prop.grffile != nullptr) {
9288 for (uint i = 0; i < 3; i++) {
9289 indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
9290 }
9291 }
9292 if (!indsp->enabled) {
9293 indsp->name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9294 }
9295 }
9296 }
9297
9303 static void FinaliseObjectsArray()
9304 {
9305 for (GRFFile * const file : _grf_files) {
9306 ObjectSpec **&objectspec = file->objectspec;
9307 if (objectspec != nullptr) {
9308 for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
9309 if (objectspec[i] != nullptr && objectspec[i]->grf_prop.grffile != nullptr && objectspec[i]->enabled) {
9310 _object_mngr.SetEntitySpec(objectspec[i]);
9311 }
9312 }
9313 }
9314 }
9315 }
9316
9322 static void FinaliseAirportsArray()
9323 {
9324 for (GRFFile * const file : _grf_files) {
9325 AirportSpec **&airportspec = file->airportspec;
9326 if (airportspec != nullptr) {
9327 for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
9328 if (airportspec[i] != nullptr && airportspec[i]->enabled) {
9329 _airport_mngr.SetEntitySpec(airportspec[i]);
9330 }
9331 }
9332 }
9333
9334 AirportTileSpec **&airporttilespec = file->airtspec;
9335 if (airporttilespec != nullptr) {
9336 for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
9337 if (airporttilespec[i] != nullptr && airporttilespec[i]->enabled) {
9338 _airporttile_mngr.SetEntitySpec(airporttilespec[i]);
9339 }
9340 }
9341 }
9342 }
9343 }
9344
9345 /* Here we perform initial decoding of some special sprites (as are they
9346 * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9347 * partial implementation yet).
9348 * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9349 * a crafted invalid GRF file. We should tell that to the user somehow, or
9350 * better make this more robust in the future. */
9351 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
9352 {
9353 /* XXX: There is a difference between staged loading in TTDPatch and
9354 * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9355 * during stage 1, whilst action 3 is carried out during stage 2 (to
9356 * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9357 * IDs are valid only within a given set (action 1) block, and may be
9358 * overwritten after action 3 associates them. But overwriting happens
9359 * in an earlier stage than associating, so... We just process actions
9360 * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9361 * --pasky
9362 * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9363 * is not in memory and scanning the file every time would be too expensive.
9364 * In other stages we skip action 0x10 since it's already dealt with. */
9365 static const SpecialSpriteHandler handlers[][GLS_END] = {
9366 /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9367 /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9368 /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9369 /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9370 /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9371 /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9372 /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9373 /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9374 /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9375 /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9376 /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9377 /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9378 /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9379 /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9380 /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9381 /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9382 /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9383 /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9384 /* 0x12 */ { SkipAct12, SkipAct12, SkipAct12, SkipAct12, SkipAct12, LoadFontGlyph, },
9385 /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9386 /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9387 };
9388
9389 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9390
9391 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9392 if (it == _grf_line_to_action6_sprite_override.end()) {
9393 /* No preloaded sprite to work with; read the
9394 * pseudo sprite content. */
9395 _cur.file->ReadBlock(buf, num);
9396 } else {
9397 /* Use the preloaded sprite data. */
9398 buf = _grf_line_to_action6_sprite_override[location];
9399 grfmsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9400
9401 /* Skip the real (original) content of this action. */
9402 _cur.file->SeekTo(num, SEEK_CUR);
9403 }
9404
9405 ByteReader br(buf, buf + num);
9406 ByteReader *bufp = &br;
9407
9408 try {
9409 byte action = bufp->ReadByte();
9410
9411 if (action == 0xFF) {
9412 grfmsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9413 } else if (action == 0xFE) {
9414 grfmsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9415 } else if (action >= lengthof(handlers)) {
9416 grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
9417 } else if (handlers[action][stage] == nullptr) {
9418 grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
9419 } else {
9420 grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
9421 handlers[action][stage](bufp);
9422 }
9423 } catch (...) {
9424 grfmsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9425 DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9426 }
9427 }
9428
9435 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9436 {
9437 _cur.file = &file;
9438 _cur.grfconfig = config;
9439
9440 Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9441
9442 byte grf_container_version = file.GetContainerVersion();
9443 if (grf_container_version == 0) {
9444 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9445 return;
9446 }
9447
9448 if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9449 /* We need the sprite offsets in the init stage for NewGRF sounds
9450 * and in the activation stage for real sprites. */
9451 ReadGRFSpriteOffsets(file);
9452 } else {
9453 /* Skip sprite section offset if present. */
9454 if (grf_container_version >= 2) file.ReadDword();
9455 }
9456
9457 if (grf_container_version >= 2) {
9458 /* Read compression value. */
9459 byte compression = file.ReadByte();
9460 if (compression != 0) {
9461 Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9462 return;
9463 }
9464 }
9465
9466 /* Skip the first sprite; we don't care about how many sprites this
9467 * does contain; newest TTDPatches and George's longvehicles don't
9468 * neither, apparently. */
9469 uint32 num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9470 if (num == 4 && file.ReadByte() == 0xFF) {
9471 file.ReadDword();
9472 } else {
9473 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9474 return;
9475 }
9476
9477 _cur.ClearDataForNextFile();
9478
9479 ReusableBuffer<byte> buf;
9480
9481 while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9482 byte type = file.ReadByte();
9483 _cur.nfo_line++;
9484
9485 if (type == 0xFF) {
9486 if (_cur.skip_sprites == 0) {
9487 DecodeSpecialSprite(buf.Allocate(num), num, stage);
9488
9489 /* Stop all processing if we are to skip the remaining sprites */
9490 if (_cur.skip_sprites == -1) break;
9491
9492 continue;
9493 } else {
9494 file.SkipBytes(num);
9495 }
9496 } else {
9497 if (_cur.skip_sprites == 0) {
9498 grfmsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9499 DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9500 break;
9501 }
9502
9503 if (grf_container_version >= 2 && type == 0xFD) {
9504 /* Reference to data section. Container version >= 2 only. */
9505 file.SkipBytes(num);
9506 } else {
9507 file.SkipBytes(7);
9508 SkipSpriteData(file, type, num - 8);
9509 }
9510 }
9511
9512 if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9513 }
9514 }
9515
9524 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9525 {
9526 const char *filename = config->filename;
9527
9528 /* A .grf file is activated only if it was active when the game was
9529 * started. If a game is loaded, only its active .grfs will be
9530 * reactivated, unless "loadallgraphics on" is used. A .grf file is
9531 * considered active if its action 8 has been processed, i.e. its
9532 * action 8 hasn't been skipped using an action 7.
9533 *
9534 * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9535 * carried out. All others are ignored, because they only need to be
9536 * processed once at initialization. */
9537 if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9538 _cur.grffile = GetFileByFilename(filename);
9539 if (_cur.grffile == nullptr) usererror("File '%s' lost in cache.\n", filename);
9540 if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9541 if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9542 }
9543
9544 bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9545 if (temporary) {
9546 SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9547 LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9548 } else {
9549 LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9550 }
9551 }
9552
9560 static void ActivateOldShore()
9561 {
9562 /* Use default graphics, if no shore sprites were loaded.
9563 * Should not happen, as the base set's extra grf should include some. */
9564 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
9565
9566 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
9567 DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9568 DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9569 DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9570 DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9571 DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9572 DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9573 DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9574 DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9575 }
9576
9577 if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
9578 DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9579 DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9580 DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9581 DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9582 DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9583 DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9584 DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9585 DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9586
9587 /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9588 * If they would be used somewhen, then these grass tiles will most like not look as needed */
9589 DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9590 DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9591 }
9592 }
9593
9597 static void ActivateOldTramDepot()
9598 {
9599 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK) {
9600 DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9601 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9602 DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9603 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9604 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9605 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9606 }
9607 }
9608
9612 static void FinalisePriceBaseMultipliers()
9613 {
9614 extern const PriceBaseSpec _price_base_specs[];
9616 static const uint32 override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9617
9618 /* Evaluate grf overrides */
9619 int num_grfs = (uint)_grf_files.size();
9620 int *grf_overrides = AllocaM(int, num_grfs);
9621 for (int i = 0; i < num_grfs; i++) {
9622 grf_overrides[i] = -1;
9623
9624 GRFFile *source = _grf_files[i];
9625 uint32 override = _grf_id_overrides[source->grfid];
9626 if (override == 0) continue;
9627
9628 GRFFile *dest = GetFileByGRFID(override);
9629 if (dest == nullptr) continue;
9630
9631 grf_overrides[i] = find_index(_grf_files, dest);
9632 assert(grf_overrides[i] >= 0);
9633 }
9634
9635 /* Override features and price base multipliers of earlier loaded grfs */
9636 for (int i = 0; i < num_grfs; i++) {
9637 if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9638 GRFFile *source = _grf_files[i];
9639 GRFFile *dest = _grf_files[grf_overrides[i]];
9640
9641 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9642 source->grf_features |= features;
9643 dest->grf_features |= features;
9644
9645 for (Price p = PR_BEGIN; p < PR_END; p++) {
9646 /* No price defined -> nothing to do */
9647 if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9648 Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9649 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9650 }
9651 }
9652
9653 /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9654 for (int i = num_grfs - 1; i >= 0; i--) {
9655 if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9656 GRFFile *source = _grf_files[i];
9657 GRFFile *dest = _grf_files[grf_overrides[i]];
9658
9659 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9660 source->grf_features |= features;
9661 dest->grf_features |= features;
9662
9663 for (Price p = PR_BEGIN; p < PR_END; p++) {
9664 /* Already a price defined -> nothing to do */
9665 if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9666 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9667 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9668 }
9669 }
9670
9671 /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9672 for (int i = 0; i < num_grfs; i++) {
9673 if (grf_overrides[i] < 0) continue;
9674 GRFFile *source = _grf_files[i];
9675 GRFFile *dest = _grf_files[grf_overrides[i]];
9676
9677 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9678 source->grf_features |= features;
9679 dest->grf_features |= features;
9680
9681 for (Price p = PR_BEGIN; p < PR_END; p++) {
9682 if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9683 if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9684 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9685 }
9686 source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9687 }
9688 }
9689
9690 /* Apply fallback prices for grf version < 8 */
9691 for (GRFFile * const file : _grf_files) {
9692 if (file->grf_version >= 8) continue;
9693 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9694 for (Price p = PR_BEGIN; p < PR_END; p++) {
9695 Price fallback_price = _price_base_specs[p].fallback_price;
9696 if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9697 /* No price multiplier has been set.
9698 * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9699 price_base_multipliers[p] = price_base_multipliers[fallback_price];
9700 }
9701 }
9702 }
9703
9704 /* Decide local/global scope of price base multipliers */
9705 for (GRFFile * const file : _grf_files) {
9706 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9707 for (Price p = PR_BEGIN; p < PR_END; p++) {
9708 if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9709 /* No multiplier was set; set it to a neutral value */
9710 price_base_multipliers[p] = 0;
9711 } else {
9712 if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9713 /* The grf does not define any objects of the feature,
9714 * so it must be a difficulty setting. Apply it globally */
9715 Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9716 SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9717 price_base_multipliers[p] = 0;
9718 } else {
9719 Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9720 }
9721 }
9722 }
9723 }
9724 }
9725
9726 extern void InitGRFTownGeneratorNames();
9727
9729 static void AfterLoadGRFs()
9730 {
9731 for (StringIDMapping &it : _string_to_grf_mapping) {
9732 *it.target = MapGRFStringID(it.grfid, it.source);
9733 }
9734 _string_to_grf_mapping.clear();
9735
9736 /* Free the action 6 override sprites. */
9737 for (GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.begin(); it != _grf_line_to_action6_sprite_override.end(); it++) {
9738 free((*it).second);
9739 }
9740 _grf_line_to_action6_sprite_override.clear();
9741
9742 /* Polish cargoes */
9743 FinaliseCargoArray();
9744
9745 /* Pre-calculate all refit masks after loading GRF files. */
9746 CalculateRefitMasks();
9747
9748 /* Polish engines */
9749 FinaliseEngineArray();
9750
9751 /* Set the actually used Canal properties */
9752 FinaliseCanals();
9753
9754 /* Add all new houses to the house array. */
9755 FinaliseHouseArray();
9756
9757 /* Add all new industries to the industry array. */
9758 FinaliseIndustriesArray();
9759
9760 /* Add all new objects to the object array. */
9761 FinaliseObjectsArray();
9762
9763 InitializeSortedCargoSpecs();
9764
9765 /* Sort the list of industry types. */
9766 SortIndustryTypes();
9767
9768 /* Create dynamic list of industry legends for smallmap_gui.cpp */
9769 BuildIndustriesLegend();
9770
9771 /* Build the routemap legend, based on the available cargos */
9772 BuildLinkStatsLegend();
9773
9774 /* Add all new airports to the airports array. */
9775 FinaliseAirportsArray();
9776 BindAirportSpecs();
9777
9778 /* Update the townname generators list */
9779 InitGRFTownGeneratorNames();
9780
9781 /* Run all queued vehicle list order changes */
9782 CommitVehicleListOrderChanges();
9783
9784 /* Load old shore sprites in new position, if they were replaced by ActionA */
9785 ActivateOldShore();
9786
9787 /* Load old tram depot sprites in new position, if no new ones are present */
9788 ActivateOldTramDepot();
9789
9790 /* Set up custom rail types */
9791 InitRailTypes();
9792 InitRoadTypes();
9793
9794 for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9795 if (_gted[e->index].rv_max_speed != 0) {
9796 /* Set RV maximum speed from the mph/0.8 unit value */
9797 e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9798 }
9799
9800 RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9801
9802 const GRFFile *file = e->GetGRF();
9803 if (file == nullptr || _gted[e->index].roadtramtype == 0) {
9804 e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
9805 continue;
9806 }
9807
9808 /* Remove +1 offset. */
9809 _gted[e->index].roadtramtype--;
9810
9811 const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
9812 if (_gted[e->index].roadtramtype < list->size())
9813 {
9814 RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
9815 RoadType rt = GetRoadTypeByLabel(rtl);
9816 if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
9817 e->u.road.roadtype = rt;
9818 continue;
9819 }
9820 }
9821
9822 /* Road type is not available, so disable this engine */
9823 e->info.climates = 0;
9824 }
9825
9826 for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
9827 RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
9828 if (railtype == INVALID_RAILTYPE) {
9829 /* Rail type is not available, so disable this engine */
9830 e->info.climates = 0;
9831 } else {
9832 e->u.rail.railtype = railtype;
9833 e->u.rail.intended_railtype = railtype;
9834 }
9835 }
9836
9837 SetYearEngineAgingStops();
9838
9839 FinalisePriceBaseMultipliers();
9840
9841 /* Deallocate temporary loading data */
9842 free(_gted);
9843 _grm_sprites.clear();
9844 }
9845
9851 void LoadNewGRF(uint load_index, uint num_baseset)
9852 {
9853 /* In case of networking we need to "sync" the start values
9854 * so all NewGRFs are loaded equally. For this we use the
9855 * start date of the game and we set the counters, etc. to
9856 * 0 so they're the same too. */
9857 Date date = _date;
9858 Year year = _cur_year;
9859 DateFract date_fract = _date_fract;
9860 uint64 tick_counter = _tick_counter;
9861 byte display_opt = _display_opt;
9862
9863 if (_networking) {
9864 _cur_year = _settings_game.game_creation.starting_year;
9865 _date = ConvertYMDToDate(_cur_year, 0, 1);
9866 _date_fract = 0;
9867 _tick_counter = 0;
9868 _display_opt = 0;
9869 }
9870
9871 InitializeGRFSpecial();
9872
9873 ResetNewGRFData();
9874
9875 /*
9876 * Reset the status of all files, so we can 'retry' to load them.
9877 * This is needed when one for example rearranges the NewGRFs in-game
9878 * and a previously disabled NewGRF becomes usable. If it would not
9879 * be reset, the NewGRF would remain disabled even though it should
9880 * have been enabled.
9881 */
9882 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9883 if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
9884 }
9885
9886 _cur.spriteid = load_index;
9887
9888 /* Load newgrf sprites
9889 * in each loading stage, (try to) open each file specified in the config
9890 * and load information from it. */
9891 for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
9892 /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
9893 * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
9894 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9895 if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
9896 }
9897
9898 if (stage == GLS_RESERVE) {
9899 static const uint32 overrides[][2] = {
9900 { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
9901 { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
9902 { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
9903 };
9904 for (size_t i = 0; i < lengthof(overrides); i++) {
9905 SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
9906 }
9907 }
9908
9909 uint num_grfs = 0;
9910 uint num_non_static = 0;
9911
9912 _cur.stage = stage;
9913 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9914 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
9915 if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
9916
9917 Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
9918 if (!FioCheckFileExists(c->filename, subdir)) {
9919 Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
9920 c->status = GCS_NOT_FOUND;
9921 continue;
9922 }
9923
9924 if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
9925
9926 if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
9927 if (num_non_static == NETWORK_MAX_GRF_COUNT) {
9928 Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
9929 c->status = GCS_DISABLED;
9930 c->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9931 continue;
9932 }
9933 num_non_static++;
9934 }
9935
9936 num_grfs++;
9937
9938 LoadNewGRFFile(c, stage, subdir, false);
9939 if (stage == GLS_RESERVE) {
9940 SetBit(c->flags, GCF_RESERVED);
9941 } else if (stage == GLS_ACTIVATION) {
9942 ClrBit(c->flags, GCF_RESERVED);
9943 assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
9944 ClearTemporaryNewGRFData(_cur.grffile);
9945 BuildCargoTranslationMap();
9946 Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
9947 } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
9948 /* We're not going to activate this, so free whatever data we allocated */
9949 ClearTemporaryNewGRFData(_cur.grffile);
9950 }
9951 }
9952 }
9953
9954 /* Pseudo sprite processing is finished; free temporary stuff */
9955 _cur.ClearDataForNextFile();
9956
9957 /* Call any functions that should be run after GRFs have been loaded. */
9958 AfterLoadGRFs();
9959
9960 /* Now revert back to the original situation */
9961 _cur_year = year;
9962 _date = date;
9963 _date_fract = date_fract;
9964 _tick_counter = tick_counter;
9965 _display_opt = display_opt;
9966 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
MapLogX
static uint MapLogX()
Logarithm of the map size along the X side.
Definition: map_func.h:51
GRFConfig::version
uint32 version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
Definition: newgrf_config.h:171
ResetCustomHouses
static void ResetCustomHouses()
Reset and clear all NewGRF houses.
Definition: newgrf.cpp:8515
AirportSpec::min_year
Year min_year
first year the airport is available
Definition: newgrf_airport.h:109
RoadTypeInfo::flags
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:125
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:7898
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:8178
RoadTypeInfo::new_engine
StringID new_engine
Name of an engine for this type of road in the engine preview GUI.
Definition: road.h:106
StationChangeInfo
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
Define properties for stations.
Definition: newgrf.cpp:1916
ParamSet
static void ParamSet(ByteReader *buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:7186
GRFLocation
Definition: newgrf.cpp:360
CalculateRefitMasks
static void CalculateRefitMasks()
Precalculate refit masks from cargo classes for all vehicles.
Definition: newgrf.cpp:8834
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:102
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
AllocateSound
SoundEntry * AllocateSound(uint num)
Allocate sound slots.
Definition: newgrf_sound.cpp:31
GRFTempEngineData::UpdateRefittability
void UpdateRefittability(bool non_empty)
Update the summary refittability on setting a refittability property.
Definition: newgrf.cpp:339
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:203
EngineInfo::base_life
Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life.
Definition: engine_type.h:146
YearMonthDay::day
Day day
Day (1..31)
Definition: date_type.h:107
Action5Type::sprite_base
SpriteID sprite_base
Load the sprites starting from this sprite.
Definition: newgrf.cpp:6190
OrderSettings::improved_load
bool improved_load
improved loading algorithm
Definition: settings_type.h:478
MAX_NUM_GENDERS
static const uint8 MAX_NUM_GENDERS
Maximum number of supported genders.
Definition: language.h:20
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:25
RoadTypeInfo
Definition: road.h:76
GRFConfig::num_valid_params
uint8 num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
Definition: newgrf_config.h:178
DuplicateTileTable
static void DuplicateTileTable(AirportSpec *as)
Create a copy of the tile table so it can be freed later without problems.
Definition: newgrf.cpp:3841
IsInsideMM
static 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:230
NUM_STATIONS_PER_GRF
static const uint NUM_STATIONS_PER_GRF
Number of StationSpecs per NewGRF; limited to 255 to allow extending Action3 with an extended byte la...
Definition: newgrf.cpp:314
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:167
CargoSpec::callback_mask
uint8 callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:69
AllowedSubtags::AllowedSubtags
AllowedSubtags()
Create empty subtags object used to identify the end of a list.
Definition: newgrf.cpp:8113
GameCreationSettings::generation_seed
uint32 generation_seed
noise seed for world generation
Definition: settings_type.h:312
GRFFileProps::override
uint16 override
id of the entity been replaced by
Definition: newgrf_commons.h:333
NUM_INDUSTRYTYPES
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like INV...
Definition: industry_type.h:26
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:26
RAILTYPE_MAGLEV
@ RAILTYPE_MAGLEV
Maglev.
Definition: rail_type.h:32
ResetCustomObjects
static void ResetCustomObjects()
Reset and clear all NewObjects.
Definition: newgrf.cpp:8596
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:173
IndustrySpec::map_colour
byte map_colour
colour used for the small map
Definition: industrytype.h:126
EngineDisplayFlags::HasVariants
@ HasVariants
Set if engine has variants.
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:92
RailtypeInfo::max_speed
uint16 max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:228
newgrf_station.h
newgrf_house.h
GRFFile::language_map
struct LanguageMap * language_map
Mappings related to the languages.
Definition: newgrf.h:141
GRFFile::roadtype_list
std::vector< RoadTypeLabel > roadtype_list
Roadtype translation table (road)
Definition: newgrf.h:133
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
EngineOverrideManager::ResetToDefaultMapping
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition: engine.cpp:479
CargoSpec::label
CargoLabel label
Unique label of the cargo type.
Definition: cargotype.h:59
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:160
LanguageMap::case_map
std::vector< Mapping > case_map
Mapping of NewGRF and OpenTTD IDs for cases.
Definition: newgrf_text.h:72
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
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, AllowedSubtags *subtags)
Create a branch node with a list of sub-nodes.
Definition: newgrf.cpp:8160
GRFConfig::error
GRFError * error
NOSAVE: Error/Warning during GRF loading (Action 0x0B)
Definition: newgrf_config.h:169
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:598
WChar
char32_t WChar
Type for wide characters, i.e.
Definition: string_type.h:36
ResetCustomAirports
static void ResetCustomAirports()
Reset and clear all NewGRF airports.
Definition: newgrf.cpp:8530
GRFTextList
std::vector< GRFText > GRFTextList
A GRF text with a list of translations.
Definition: newgrf_text.h:31
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:4095
EngineIDMapping::grfid
uint32 grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:180
RoadTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: road.h:103
IndustryProductionSpriteGroup::subtract_input
int16 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
usererror
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:105
DeterministicSpriteGroupRange
Definition: newgrf_spritegroup.h:160
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition: newgrf_station.h:148
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
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
SPR_SHORE_BASE
static const SpriteID SPR_SHORE_BASE
shore tiles - action 05-0D
Definition: sprites.h:224
TLF_DODRAW
@ TLF_DODRAW
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
Definition: newgrf_commons.h:36
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:103
OBJECT_FLAG_2CC_COLOUR
@ OBJECT_FLAG_2CC_COLOUR
Object wants 2CC colour mapping.
Definition: newgrf_object.h:34
ShipVehicleChangeInfo
static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for ships.
Definition: newgrf.cpp:1566
GetRoadTypeByLabel
RoadType GetRoadTypeByLabel(RoadTypeLabel label, bool allow_alternate_labels)
Get the road type for a given label.
Definition: road.cpp:243
HouseSpec::random_colour
byte random_colour[4]
4 "random" colours
Definition: house.h:116
PROP_ROADVEH_COST_FACTOR
@ PROP_ROADVEH_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:35
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
CanalProperties::callback_mask
uint8 callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf.h:40
RailtypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: rail.h:175
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:104
ObjectFlags
ObjectFlags
Various object behaviours.
Definition: newgrf_object.h:24
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:52
ObjectSpec::build_cost_multiplier
uint8 build_cost_multiplier
Build cost multiplier per tile.
Definition: newgrf_object.h:68
BridgeSpec::avail_year
Year avail_year
the year where it becomes available
Definition: bridge.h:42
ResetCustomIndustries
static void ResetCustomIndustries()
Reset and clear all NewGRF industries.
Definition: newgrf.cpp:8567
PROP_TRAIN_RUNNING_COST_FACTOR
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:23
smallmap_gui.h
_grf_files
static std::vector< GRFFile * > _grf_files
List of all loaded GRF files.
Definition: newgrf.cpp:67
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1523
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:328
StringIDMapping::grfid
uint32 grfid
Source NewGRF.
Definition: newgrf.cpp:468
ShipVehicleInfo::canal_speed_frac
byte canal_speed_frac
Fraction of maximum speed for canal/river tiles.
Definition: engine_type.h:77
TLF_CHILD_X_OFFSET
@ TLF_CHILD_X_OFFSET
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:44
RoadTypeInfo::introduces_roadtypes
RoadTypes introduces_roadtypes
Bitmask of which other roadtypes are introduced when this roadtype is introduced.
Definition: road.h:175
TE_GOODS
@ TE_GOODS
Cargo behaves goods/candy-like.
Definition: cargotype.h:31
_engine_counts
const uint8 _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:51
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:8123
GRFFile::price_base_multipliers
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:147
FeatureTownName
static void FeatureTownName(ByteReader *buf)
Action 0x0F - Define Town names.
Definition: newgrf.cpp:7536
grfmsg
void CDECL grfmsg(int severity, const char *str,...)
Debug() function dedicated to newGRF debugging messages Function is essentially the same as Debug(grf...
Definition: newgrf.cpp:391
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
IndustriesChangeInfo
static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
Define properties for industries.
Definition: newgrf.cpp:3461
DeterministicSpriteGroup
Definition: newgrf_spritegroup.h:167
TileLayoutRegisters::sprite
uint8 sprite
Register specifying a signed offset for the sprite.
Definition: newgrf_commons.h:94
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:8175
HandleNodes
static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
Handle the contents of a 'C' choice of an Action14.
Definition: newgrf.cpp:8370
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:180
CargoSpec::initial_payment
int32 initial_payment
Initial payment rate before inflation is applied.
Definition: cargotype.h:64
AirportSpec::size_y
byte size_y
size of airport in y direction
Definition: newgrf_airport.h:106
CargoSpec::town_effect
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:68
NewGRFSpriteLayout::AllocateRegisters
void AllocateRegisters()
Allocate memory for register modifiers.
Definition: newgrf_commons.cpp:636
Pool::CleanPool
virtual void CleanPool()
Virtual method that deletes all items in the pool.
PALETTE_MODIFIER_COLOUR
@ PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition: sprites.h:1538
BASESET_DIR
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
currency.h
GRFConfig::num_params
uint8 num_params
Number of used parameters.
Definition: newgrf_config.h:177
GetNewEngine
static Engine * GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access=false)
Returns the engine associated to a certain internal_id, resp.
Definition: newgrf.cpp:605
_date_fract
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
TileLayoutRegisters::parent
uint8 parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
Definition: newgrf_commons.h:99
NamePart::prob
byte prob
The relative probability of the following name to appear in the bottom 7 bits.
Definition: newgrf_townname.h:20
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:74
PROP_AIRCRAFT_MAIL_CAPACITY
@ PROP_AIRCRAFT_MAIL_CAPACITY
Mail Capacity.
Definition: newgrf_properties.h:53
AirportSpec::name
StringID name
name of this airport
Definition: newgrf_airport.h:111
CC_EXPRESS
@ CC_EXPRESS
Express cargo (Goods, Food, Candy, but also possible for passengers)
Definition: cargotype.h:43
FinaliseCanals
static void FinaliseCanals()
Set to use the correct action0 properties for each canal feature.
Definition: newgrf.cpp:9006
RailtypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: rail.h:177
GRFFile::grf_features
uint32 grf_features
Bitset of GrfSpecFeature the grf uses.
Definition: newgrf.h:146
LanguageMap::plural_form
int plural_form
The plural form used for this language.
Definition: newgrf_text.h:73
ConstructionSettings::map_height_limit
uint8 map_height_limit
the maximum allowed heightlevel
Definition: settings_type.h:342
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:87
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:193
AircraftVehicleInfo::passenger_capacity
uint16 passenger_capacity
Passenger capacity (persons).
Definition: engine_type.h:108
IndustrySpec::removal_cost_multiplier
uint32 removal_cost_multiplier
Base removal cost multiplier.
Definition: industrytype.h:110
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:96
A5BLOCK_INVALID
@ A5BLOCK_INVALID
unknown/not-implemented type
Definition: newgrf.cpp:6185
Action5BlockType
Action5BlockType
The type of action 5 type.
Definition: newgrf.cpp:6182
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:8045
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
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:51
IsValidNewGRFImageIndex
static bool IsValidNewGRFImageIndex(uint8 image_index)
Helper to check whether an image index is valid for a particular NewGRF vehicle.
Definition: newgrf.cpp:205
AirportSpec::max_year
Year max_year
last year the airport is available
Definition: newgrf_airport.h:110
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
IndustryProductionSpriteGroup::num_input
uint8 num_input
How many subtract_input values are valid.
Definition: newgrf_spritegroup.h:272
ResetPersistentNewGRFData
void ResetPersistentNewGRFData()
Reset NewGRF data which is stored persistently in savegames.
Definition: newgrf.cpp:8729
PROP_SHIP_CARGO_CAPACITY
@ PROP_SHIP_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:45
TileLayoutRegisters::palette_var10
uint8 palette_var10
Value for variable 10 when resolving the palette.
Definition: newgrf_commons.h:103
HouseExtraFlags
HouseExtraFlags
Definition: house.h:88
_bridge
BridgeSpec _bridge[MAX_BRIDGES]
The specification of all bridges.
Definition: tunnelbridge_cmd.cpp:51
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:115
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:107
ChangeGRFVersion
static bool ChangeGRFVersion(size_t len, ByteReader *buf)
Callback function for 'INFO'->'VRSN' to the version of the NewGRF.
Definition: newgrf.cpp:7979
SortIndustryTypes
void SortIndustryTypes()
Initialize the list of sorted industry types.
Definition: industry_gui.cpp:209
FindFirstBit
uint8 FindFirstBit(uint64 x)
Search the first set bit in a 64 bit variable.
Definition: bitmath_func.cpp:37
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
ResetPriceBaseMultipliers
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:882
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:8014
ResetRailTypes
void ResetRailTypes()
Reset all rail type information to its default values.
Definition: rail_cmd.cpp:64
GrfProcessingState::spritesets
std::map< uint, SpriteSet > spritesets[GSF_END]
Currently referenceable spritesets.
Definition: newgrf.cpp:95
GrfProcessingState::spriteid
SpriteID spriteid
First available SpriteID for loading realsprites.
Definition: newgrf.cpp:100
RailtypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:124
WaterFeature::callback_mask
uint8 callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf_canal.h:25
ClrBit
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
VehicleSettings::wagon_speed_limits
bool wagon_speed_limits
enable wagon speed limits
Definition: settings_type.h:493
CIR_INVALID_ID
@ CIR_INVALID_ID
Attempt to modify an invalid ID.
Definition: newgrf.cpp:996
GRFParameterInfo::param_nr
byte param_nr
GRF parameter to store content in.
Definition: newgrf_config.h:143
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:39
RailtypeInfo::grffile
const GRFFile * grffile[RTSG_END]
NewGRF providing the Action3 for the railtype.
Definition: rail.h:273
SetNewGRFOverride
static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
Set the override for a NewGRF.
Definition: newgrf.cpp:591
_tags_info
AllowedSubtags _tags_info[]
Action14 tags for the INFO node.
Definition: newgrf.cpp:8266
Year
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
Definition: date_type.h:18
vehicle_base.h
GRFUnsafe
static void GRFUnsafe(ByteReader *buf)
Set the current NewGRF as unsafe for static use.
Definition: newgrf.cpp:8396
GRFParameterInfo::def_value
uint32 def_value
Default value of this parameter.
Definition: newgrf_config.h:142
fileio_func.h
GCS_NOT_FOUND
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:37
ConvertTTDBasePrice
static void ConvertTTDBasePrice(uint32 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:971
newgrf_airport.h
SetupCargoForClimate
void SetupCargoForClimate(LandscapeID l)
Set up the default cargo types for the given landscape type.
Definition: cargotype.cpp:40
build_industry.h
GRFTempEngineData::ctt_include_mask
CargoTypes ctt_include_mask
Cargo types always included in the refit mask.
Definition: newgrf.cpp:332
HouseSpec::building_name
StringID building_name
building name
Definition: house.h:104
ObjectSpec::end_of_life_date
Date end_of_life_date
When can't this object be built anymore.
Definition: newgrf_object.h:71
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:174
SetupEngines
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:535
OverrideManagerBase::GetID
virtual uint16 GetID(uint8 grf_local_id, uint32 grfid) const
Return the ID (if ever available) of a previously inserted entity.
Definition: newgrf_commons.cpp:102
GRFConfig::ident
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
Definition: newgrf_config.h:163
newgrf_townname.h
AircraftVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
Definition: engine_type.h:106
LiveryScheme
LiveryScheme
List of different livery schemes.
Definition: livery.h:20
AirportSpec::ResetAirports
static void ResetAirports()
This function initializes the airportspec array.
Definition: newgrf_airport.cpp:153
GCF_COPY
@ GCF_COPY
The data is copied from a grf in _all_grfs.
Definition: newgrf_config.h:27
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:57
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, TextHandler handler)
Create a text leaf node.
Definition: newgrf.cpp:8135
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:174
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:86
town.h
ORIGINAL_BASE_YEAR
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: date_type.h:50
NUM_OBJECTS_PER_GRF
static const ObjectType NUM_OBJECTS_PER_GRF
Number of supported objects per NewGRF; limited to 255 to allow extending Action3 with an extended by...
Definition: object_type.h:22
RailVehicleInfo::power
uint16 power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition: engine_type.h:49
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition: cargotype.h:47
GRFP_GRF_UNSET
@ GRFP_GRF_UNSET
The NewGRF provided no information.
Definition: newgrf_config.h:70
EngineInfo
Information about a vehicle.
Definition: engine_type.h:143
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:8028
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:103
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:132
CreateGroupFromGroupID
static const SpriteGroup * CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
Helper function to either create a callback or a result sprite group.
Definition: newgrf.cpp:5017
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
OverrideManagerBase::Add
void Add(uint8 local_id, uint32 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:72
EngineInfo::base_intro
Date base_intro
Basic date of engine introduction (without random parts).
Definition: engine_type.h:144
CIR_SUCCESS
@ CIR_SUCCESS
Variable was parsed and read.
Definition: newgrf.cpp:992
MAX_SPRITEGROUP
static const uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
Definition: newgrf.cpp:83
GRFLoadedFeatures::used_liveries
uint64 used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:177
HouseSpec::max_year
Year max_year
last year it can be built
Definition: house.h:101
VehicleSettings::road_side
byte road_side
the side of the road vehicles drive on
Definition: settings_type.h:504
RoadTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: road.h:105
AllowedSubtags::text
TextHandler text
Callback function for a text node, only valid if type == 'T'.
Definition: newgrf.cpp:8172
VSG_SCOPE_PARENT
@ VSG_SCOPE_PARENT
Related object of the resolved one.
Definition: newgrf_spritegroup.h:101
RailtypeInfo::fallback_railtype
byte fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition: rail.h:198
Engine
Definition: engine_base.h:36
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:41
EngineIDMapping::internal_id
uint16 internal_id
The internal ID within the GRF file.
Definition: engine_base.h:181
GRFParameterInfo::type
GRFParameterType type
The type of this parameter.
Definition: newgrf_config.h:139
SoundEffectChangeInfo
static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
Define properties for sound effects.
Definition: newgrf.cpp:3105
_tags_parameters
AllowedSubtags _tags_parameters[]
Action14 parameter tags.
Definition: newgrf.cpp:8222
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:127
SpriteFile::GetContainerVersion
byte GetContainerVersion() const
Get the version number of container type used by the file.
Definition: sprite_file_type.hpp:38
RoadTypeInfo::introduction_date
Date introduction_date
Introduction date.
Definition: road.h:164
SoundEntry::grf_container_ver
byte grf_container_ver
NewGRF container version if the sound is from a NewGRF.
Definition: sound_type.h:22
fios.h
TranslateGRFStrings
static void TranslateGRFStrings(ByteReader *buf)
Action 0x13.
Definition: newgrf.cpp:7845
SmallMap::Insert
bool Insert(const T &key, const U &data)
Adds new item to this map.
Definition: smallmap_type.hpp:127
BridgeSpec::speed
uint16 speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: bridge.h:46
FinalisePriceBaseMultipliers
static void FinalisePriceBaseMultipliers()
Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them...
Definition: newgrf.cpp:9612
RandomAccessFile::ReadBlock
void ReadBlock(void *ptr, size_t size)
Read a block.
Definition: random_access_file.cpp:138
TranslateTTDPatchCodes
std::string TranslateTTDPatchCodes(uint32 grfid, uint8 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:241
MemCpyT
static void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:23
TLF_BB_Z_OFFSET
@ TLF_BB_Z_OFFSET
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:42
GFX_WATERTILE_SPECIALCHECK
@ GFX_WATERTILE_SPECIALCHECK
not really a tile, but rather a very special check
Definition: industry_map.h:54
GRFTempEngineData::rv_max_speed
uint8 rv_max_speed
Temporary storage of RV prop 15, maximum speed in mph/0.8.
Definition: newgrf.cpp:331
ObjectSpec::size
uint8 size
The size of this objects; low nibble for X, high nibble for Y.
Definition: newgrf_object.h:67
GRFFile::GetParam
uint32 GetParam(uint number) const
Get GRF Parameter with range checking.
Definition: newgrf.h:153
AirportSpec
Defines the data structure for an airport.
Definition: newgrf_airport.h:98
EngineOverrideManager::GetID
EngineID GetID(VehicleType type, uint16 grf_local_id, uint32 grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:502
ObjectSpec::callback_mask
uint16 callback_mask
Bitmask of requested/allowed callbacks.
Definition: newgrf_object.h:74
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:27
genworld.h
RailtypeInfo::sorting_order
byte sorting_order
The sorting order of this railtype for the toolbar dropdown.
Definition: rail.h:268
TileLayoutRegisters
Additional modifiers for items in sprite layouts.
Definition: newgrf_commons.h:91
AnimationInfo::speed
uint8 speed
The speed, i.e. the amount of time between frames.
Definition: newgrf_animation_type.h:21
TileLayoutRegisters::dodraw
uint8 dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
Definition: newgrf_commons.h:93
GRFIdentifier::grfid
uint32 grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:84
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:100
CargoLabel
uint32 CargoLabel
Globally unique label of a cargo type.
Definition: cargotype.h:23
ObjectSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_object.h:73
CIR_UNHANDLED
@ CIR_UNHANDLED
Variable was parsed but unread.
Definition: newgrf.cpp:994
RoadVehicleInfo::air_drag
uint8 air_drag
Coefficient of air drag.
Definition: engine_type.h:124
AirportSpec::maintenance_cost
uint16 maintenance_cost
maintenance cost multiplier
Definition: newgrf_airport.h:115
VSG_SCOPE_SELF
@ VSG_SCOPE_SELF
Resolved object itself.
Definition: newgrf_spritegroup.h:100
CargoSpec::bitnum
uint8 bitnum
Cargo bit number, is INVALID_CARGO for a non-used spec.
Definition: cargotype.h:58
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
industry_map.h
DeterministicSpriteGroupAdjustOperation
DeterministicSpriteGroupAdjustOperation
Definition: newgrf_spritegroup.h:120
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:587
GRFParameterInfo::num_bit
byte num_bit
Number of bits to use for this parameter.
Definition: newgrf_config.h:145
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:141
AirportChangeInfo
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
Define properties for airports.
Definition: newgrf.cpp:3870
IndustryTileLayout
std::vector< IndustryTileLayoutTile > IndustryTileLayout
A complete tile layout for an industry is a list of tiles.
Definition: industrytype.h:102
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
AddGRFString
StringID AddGRFString(uint32 grfid, uint16 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:551
GetFileByGRFID
static GRFFile * GetFileByGRFID(uint32 grfid)
Obtain a NewGRF file by its grfID.
Definition: newgrf.cpp:408
SpriteID
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
ObjectSpec::introduction_date
Date introduction_date
From when can this object be built.
Definition: newgrf_object.h:70
StringIDMapping::target
StringID * target
Destination for mapping result.
Definition: newgrf.cpp:470
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:258
RandomAccessFile::SkipBytes
void SkipBytes(int n)
Skip n bytes ahead in the file.
Definition: random_access_file.cpp:148
BridgeSpec
Struct containing information about a single bridge type.
Definition: bridge.h:41
RailtypeInfo::name
StringID name
Name of this rail type.
Definition: rail.h:173
IndustrySpec::closure_text
StringID closure_text
Message appearing when the industry closes.
Definition: industrytype.h:129
EngineInfo::lifelength
Year lifelength
Lifetime of a single vehicle.
Definition: engine_type.h:145
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:154
GrfProcessingState::SpriteSet::sprite
SpriteID sprite
SpriteID of the first sprite of the set.
Definition: newgrf.cpp:90
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:143
AirportTileSpec::ResetAirportTiles
static void ResetAirportTiles()
This function initializes the tile array of AirportTileSpec.
Definition: newgrf_airporttiles.cpp:57
TLF_KNOWN_FLAGS
@ TLF_KNOWN_FLAGS
Known flags. Any unknown set flag will disable the GRF.
Definition: newgrf_commons.h:50
ShipVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:75
RoadVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:119
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
GetRailTypeInfo
static const RailtypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:304
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition: newgrf_airporttiles.h:66
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:95
IndustryTileSpec::special_flags
IndustryTileSpecialFlags special_flags
Bitmask of extra flags used by the tile.
Definition: industrytype.h:170
StationSpec::cls_id
StationClassID cls_id
The class to which this spec belongs.
Definition: newgrf_station.h:126
EC_MAGLEV
@ EC_MAGLEV
Maglev engine.
Definition: engine_type.h:38
GRFTempEngineData::Refittability
Refittability
Summary state of refittability properties.
Definition: newgrf.cpp:319
NFO_UTF8_IDENTIFIER
static const WChar NFO_UTF8_IDENTIFIER
This character, the thorn ('þ'), indicates a unicode string to NFO.
Definition: newgrf_text.h:22
IndustryProductionSpriteGroup::num_output
uint8 num_output
How many add_output values are valid.
Definition: newgrf_spritegroup.h:275
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:594
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:358
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
InitGRFTownGeneratorNames
void InitGRFTownGeneratorNames()
Allocate memory for the NewGRF town names.
Definition: newgrf_townname.cpp:109
GRFP_GRF_DOS
@ GRFP_GRF_DOS
The NewGRF says the DOS palette can be used.
Definition: newgrf_config.h:71
_grm_engines
static uint32 _grm_engines[256]
Contains the GRF ID of the owner of a vehicle if it has been reserved.
Definition: newgrf.cpp:355
MAX_CATCHMENT
@ MAX_CATCHMENT
Maximum catchment for airports with "modified catchment" enabled.
Definition: station_type.h:85
AnimationInfo::frames
uint8 frames
The number of frames.
Definition: newgrf_animation_type.h:19
DrawTileSeqStruct::delta_x
int8 delta_x
0x80 is sequence terminator
Definition: sprite.h:26
GRFLoadedFeatures::has_2CC
bool has_2CC
Set if any vehicle is loaded which uses 2cc (two company colours).
Definition: newgrf.h:176
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
TileIndexDiffC::y
int16 y
The y value of the coordinate.
Definition: map_type.h:59
GrfProcessingState::HasValidSpriteSets
bool HasValidSpriteSets(byte feature) const
Check whether there are any valid spritesets for a feature.
Definition: newgrf.cpp:151
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:6620
LoadNewGRF
void LoadNewGRF(uint load_index, uint num_baseset)
Load all the NewGRFs.
Definition: newgrf.cpp:9851
AirportSpec::rotation
const Direction * rotation
the rotation of each tiletable
Definition: newgrf_airport.h:101
EngineID
uint16 EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
LoadNewGRFFile
void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
Load a particular NewGRF.
Definition: newgrf.cpp:9524
SHORE_REPLACE_NONE
@ SHORE_REPLACE_NONE
No shore sprites were replaced.
Definition: newgrf.h:163
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
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:530
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:178
_gted
static GRFTempEngineData * _gted
Temporary engine data used during NewGRF loading.
Definition: newgrf.cpp:349
TE_NONE
@ TE_NONE
Cargo has no effect.
Definition: cargotype.h:28
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:120
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
IndustryTileSpec::acceptance
int8 acceptance[INDUSTRY_NUM_INPUTS]
Level of acceptance per cargo type (signed, may be negative!)
Definition: industrytype.h:158
BindAirportSpecs
void BindAirportSpecs()
Tie all airportspecs to their class.
Definition: newgrf_airport.cpp:165
LoadNextSprite
bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
Definition: spritecache.cpp:611
VE_TYPE_START
@ VE_TYPE_START
First bit used for the type of effect.
Definition: vehicle_base.h:85
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
GRFFile::tramtype_list
std::vector< RoadTypeLabel > tramtype_list
Roadtype translation table (tram)
Definition: newgrf.h:136
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:656
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:329
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
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
LanguageMap::GetLanguageMap
static const LanguageMap * GetLanguageMap(uint32 grfid, uint8 language_id)
Get the language map associated with a given NewGRF and language.
Definition: newgrf.cpp:2613
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:155
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
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
HasExactlyOneBit
static bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition: bitmath_func.hpp:274
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:34
DrawTileSeqStruct::delta_z
int8 delta_z
0x80 identifies child sprites
Definition: sprite.h:28
StringIDMapping::source
StringID source
Source StringID (GRF local).
Definition: newgrf.cpp:469
AirportSpec::num_table
byte num_table
number of elements in the table
Definition: newgrf_airport.h:102
SetPriceBaseMultiplier
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:894
IndustrySpec::conflicting
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:112
CurrencySpec::suffix
std::string suffix
Suffix to apply when formatting money in this currency.
Definition: currency.h:77
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:41
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
MIN_YEAR
static const Year MIN_YEAR
The absolute minimum & maximum years in OTTD.
Definition: date_type.h:84
StationSpec::layouts
std::vector< std::vector< std::vector< byte > > > layouts
Custom platform layouts.
Definition: newgrf_station.h:176
OverrideManagerBase::ResetMapping
void ResetMapping()
Resets the mapping, which is used while initializing game.
Definition: newgrf_commons.cpp:82
FinaliseIndustriesArray
static void FinaliseIndustriesArray()
Add all new industries to the industry array.
Definition: newgrf.cpp:9234
TLF_CHILD_Y_OFFSET
@ TLF_CHILD_Y_OFFSET
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:45
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
YearMonthDay::month
Month month
Month (0..11)
Definition: date_type.h:106
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:8239
StationSpec::pylons
byte pylons
Bitmask of base tiles (0 - 7) which should contain elrail pylons.
Definition: newgrf_station.h:162
AirportTileTable::gfx
StationGfx gfx
AirportTile to use for this tile.
Definition: newgrf_airport.h:25
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:273
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:73
CargoSpec::IsValid
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:99
RailtypeInfo::alternate_labels
RailTypeLabelList alternate_labels
Rail type labels this type provides in addition to the main label.
Definition: rail.h:238
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:109
RoadVehicleInfo
Information about a road vehicle.
Definition: engine_type.h:113
CC_PIECE_GOODS
@ CC_PIECE_GOODS
Piece goods (Livestock, Wood, Steel, Paper)
Definition: cargotype.h:46
GRFConfig::flags
uint8 flags
NOSAVE: GCF_Flags, bitset.
Definition: newgrf_config.h:173
BranchHandler
bool(* BranchHandler)(ByteReader *)
Type of callback function for branch nodes.
Definition: newgrf.cpp:8102
LanguageMap::Mapping::openttd_id
byte openttd_id
OpenTTD's internal ID for a case/gender.
Definition: newgrf_text.h:62
SB
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
RoadVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:125
IndustryProductionSpriteGroup
Definition: newgrf_spritegroup.h:268
ConvertYMDToDate
Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: date.cpp:149
IndustrySpec::layouts
std::vector< IndustryTileLayout > layouts
List of possible tile layouts for the industry.
Definition: industrytype.h:108
SPRITE_MODIFIER_OPAQUE
@ SPRITE_MODIFIER_OPAQUE
Set when a sprite must not ever be displayed transparently.
Definition: sprites.h:1536
IndustrySpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 accepted cargoes.
Definition: industrytype.h:121
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
GetGRFSpriteOffset
size_t GetGRFSpriteOffset(uint32 id)
Get the file offset for a specific sprite in the sprite section of a GRF.
Definition: spritecache.cpp:546
EF_USES_2CC
@ EF_USES_2CC
Vehicle uses two company colours.
Definition: engine_type.h:168
SHORE_REPLACE_ONLY_NEW
@ SHORE_REPLACE_ONLY_NEW
Only corner-shores were loaded by Action5 (openttd(w/d).grf only).
Definition: newgrf.h:166
IndustrySpec::number_of_sounds
uint8 number_of_sounds
Number of sounds available in the sounds array.
Definition: industrytype.h:135
find_index
int find_index(std::vector< T > const &vec, T const &item)
Helper function to get the index of an item Consider using std::set, std::unordered_set or std::flat_...
Definition: smallvec_type.hpp:44
BridgeSpec::transport_name
StringID transport_name[2]
description of the bridge, when built for road or rail
Definition: bridge.h:50
CC_BULK
@ CC_BULK
Bulk cargo (Coal, Grain etc., Ores, Fruit)
Definition: cargotype.h:45
_cargo_mask
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition: cargotype.cpp:29
AircraftVehicleInfo::max_range
uint16 max_range
Maximum range of this aircraft.
Definition: engine_type.h:109
AddGenericCallback
void AddGenericCallback(uint8 feature, const GRFFile *file, const SpriteGroup *group)
Add a generic feature callback sprite group to the appropriate feature list.
Definition: newgrf_generic.cpp:109
SP_CUSTOM
@ SP_CUSTOM
No profile, special "custom" highscore.
Definition: settings_type.h:45
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:130
CleanUpStrings
void CleanUpStrings()
House cleaning.
Definition: newgrf_text.cpp:695
Date
int32 Date
The type to store our dates in.
Definition: date_type.h:14
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:9136
GrfProcessingState::SpriteSet
Definition of a single Action1 spriteset.
Definition: newgrf.cpp:89
LoadNewGRFFileFromFile
static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
Load a particular NewGRF from a SpriteFile.
Definition: newgrf.cpp:9435
IndustrySpec::input_cargo_multiplier
uint16 input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes)
Definition: industrytype.h:122
CargoSpec::grffile
const struct GRFFile * grffile
NewGRF where #group belongs to.
Definition: cargotype.h:80
StaticGRFInfo
static void StaticGRFInfo(ByteReader *buf)
Handle Action 0x14.
Definition: newgrf.cpp:8385
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
NewGRFClass
Struct containing information relating to NewGRF classes for stations and airports.
Definition: newgrf_class.h:19
StationSettings::never_expire_airports
bool never_expire_airports
never expire airports
Definition: settings_type.h:562
AfterLoadGRFs
static void AfterLoadGRFs()
Finish loading NewGRFs and execute needed post-processing.
Definition: newgrf.cpp:9729
_cur_parameter
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:8011
IndustrySpec::minimal_cargo
byte minimal_cargo
minimum amount of cargo transported to the stations.
Definition: industrytype.h:120
RoadTypeInfo::group
const SpriteGroup * group[ROTSG_END]
Sprite groups for resolving sprites.
Definition: road.h:190
LanguageMap::gender_map
std::vector< Mapping > gender_map
Mapping of NewGRF and OpenTTD IDs for genders.
Definition: newgrf_text.h:71
SHORE_REPLACE_ACTION_5
@ SHORE_REPLACE_ACTION_5
Shore sprites were replaced by Action5.
Definition: newgrf.h:164
StringIDMapping
Information for mapping static StringIDs.
Definition: newgrf.cpp:467
RailtypeInfo::introduction_date
Date introduction_date
Introduction date.
Definition: rail.h:252
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:54
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
ANIM_STATUS_NO_ANIMATION
static const uint8 ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
ValidateIndustryLayout
static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
Validate the industry layout; e.g.
Definition: newgrf.cpp:3428
RoadTypeInfo::alternate_labels
RoadTypeLabelList alternate_labels
Road type labels this type provides in addition to the main label.
Definition: road.h:150
MapNewGRFIndustryType
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32 grf_id)
Map the GRF local type to an industry type.
Definition: newgrf_industries.cpp:39
ChangeGRFURL
static bool ChangeGRFURL(byte langid, const char *str)
Callback function for 'INFO'->'URL_' to set the newgrf url.
Definition: newgrf.cpp:7912
_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:194
GRFParameterInfo
Information about one grf parameter.
Definition: newgrf_config.h:134
CargoSpec::sprite
SpriteID sprite
Icon to display this cargo type, may be 0xFFF (which means to resolve an action123 chain).
Definition: cargotype.h:77
ConvertDateToYMD
void ConvertDateToYMD(Date date, YearMonthDay *ymd)
Converts a Date to a Year, Month & Day.
Definition: date.cpp:94
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:596
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:112
PROP_SHIP_CARGO_AGE_PERIOD
@ PROP_SHIP_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:47
HandleNode
static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
Handle the nodes of an Action14.
Definition: newgrf.cpp:8332
TileLayoutRegisters::child
uint8 child[2]
Registers for signed offsets for the position of child sprites.
Definition: newgrf_commons.h:100
_action5_types
static const Action5Type _action5_types[]
The information about action 5 types.
Definition: newgrf.cpp:6197
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition: newgrf_commons.h:113
MAX_LANG
static const uint MAX_LANG
Maximum number of languages supported by the game, and the NewGRF specs.
Definition: strings_type.h:19
safeguards.h
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:8067
StationSpec::name
StringID name
Name of this station.
Definition: newgrf_station.h:127
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:315
GRFP_BLT_32BPP
@ GRFP_BLT_32BPP
The NewGRF prefers a 32 bpp blitter.
Definition: newgrf_config.h:77
HouseSpec::callback_mask
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:115
IndustryTileSpec::slopes_refused
Slope slopes_refused
slope pattern on which this tile cannot be built
Definition: industrytype.h:159
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:8192
ImportGRFSound
static void ImportGRFSound(SoundEntry *sound)
Process a sound import from another GRF file.
Definition: newgrf.cpp:7637
GRFConfig::has_param_defaults
bool has_param_defaults
NOSAVE: did this newgrf specify any defaults for it's parameters.
Definition: newgrf_config.h:181
GRFFile::param_end
uint param_end
one more than the highest set parameter
Definition: newgrf.h:123
TLR_MAX_VAR10
static const uint TLR_MAX_VAR10
Maximum value for var 10.
Definition: newgrf_commons.h:106
GetGRFStringID
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:601
ttd_strnlen
static size_t ttd_strnlen(const char *str, size_t maxlen)
Get the length of a string, within a limited buffer.
Definition: string_func.h:79
GrfProcessingState
Temporary data during loading of GRFs.
Definition: newgrf.cpp:86
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1535
IndustryTileSpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:171
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:67
_tags_root
AllowedSubtags _tags_root[]
Action14 root tags.
Definition: newgrf.cpp:8280
CargoSpec::weight
uint8 weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:62
FinaliseObjectsArray
static void FinaliseObjectsArray()
Add all new objects to the object array.
Definition: newgrf.cpp:9303
GRFTempEngineData::EMPTY
@ EMPTY
GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
Definition: newgrf.cpp:321
TranslateRefitMask
static CargoTypes TranslateRefitMask(uint32 refit_mask)
Translate the refit mask.
Definition: newgrf.cpp:954
ObjectSpec::height
uint8 height
The height of this structure, in heightlevels; max MAX_TILE_HEIGHT.
Definition: newgrf_object.h:75
WaterFeature::flags
uint8 flags
Flags controlling display.
Definition: newgrf_canal.h:26
NamePart::text
char * text
If probability bit 7 is clear.
Definition: newgrf_townname.h:22
EngineInfo::callback_mask
uint16 callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:154
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
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:58
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:24
TTDPAirportType
TTDPAirportType
Allow incrementing of AirportClassID variables.
Definition: newgrf_airport.h:81
CanalChangeInfo
static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for water features.
Definition: newgrf.cpp:2145
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:2630
GlobalVarChangeInfo
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
Define properties for global variables.
Definition: newgrf.cpp:2670
newgrf_text.h
road.h
vseprintf
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:62
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:101
error.h
GrfProcessingState::GetSprite
SpriteID GetSprite(byte feature, uint set) const
Returns the first sprite of a spriteset.
Definition: newgrf.cpp:176
RailVehicleChangeInfo
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for rail vehicles.
Definition: newgrf.cpp:1051
CargoSpec::is_freight
bool is_freight
Cargo type is considered to be freight (affects train freight multiplier).
Definition: cargotype.h:67
HZ_ZON5
@ HZ_ZON5
center of town
Definition: house.h:77
GRFTempEngineData::ctt_exclude_mask
CargoTypes ctt_exclude_mask
Cargo types always excluded from the refit mask.
Definition: newgrf.cpp:333
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:329
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:157
EngineIDMapping
Definition: engine_base.h:179
AirportTileTable
Tile-offset / AirportTileID pair.
Definition: newgrf_airport.h:23
IndustrySpec::appear_creation
byte appear_creation[NUM_LANDSCAPE]
Probability of appearance during map creation.
Definition: industrytype.h:134
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:81
language.h
IndustryTileSpec::anim_production
byte anim_production
Animation frame to start when goods are produced.
Definition: industrytype.h:160
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:27
EngineInfo::retire_early
int8 retire_early
Number of years early to retire vehicle.
Definition: engine_type.h:155
GetNewEngineID
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
Return the ID of a new engine.
Definition: newgrf.cpp:701
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:144
EngineIDMapping::substitute_id
uint8 substitute_id
The (original) entity ID to use if this GRF is not available (currently not used)
Definition: engine_base.h:183
CargoChangeInfo
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
Define properties for cargoes.
Definition: newgrf.cpp:2966
date_func.h
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:133
stdafx.h
GrfProcessingState::grfconfig
GRFConfig * grfconfig
Config of the currently processed GRF file.
Definition: newgrf.cpp:105
TLF_NON_GROUND_FLAGS
@ TLF_NON_GROUND_FLAGS
Flags which do not work for the (first) ground sprite.
Definition: newgrf_commons.h:56
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
IsLeapYear
static bool IsLeapYear(Year yr)
Checks whether the given year is a leap year or not.
Definition: date_func.h:30
landscape.h
ObjectSpec::enabled
bool enabled
Is this spec enabled?
Definition: newgrf_object.h:78
RailVehicleInfo::pow_wag_power
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:56
RailtypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: rail.h:174
OTTDByteReaderSignal
Definition: newgrf.cpp:210
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:107
RailVehicleInfo::weight
uint16 weight
Weight of vehicle (tons); For multiheaded engines the weight of each single engine.
Definition: engine_type.h:50
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:172
BSWAP32
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:390
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:1537
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:3338
GRFTempEngineData::refittability
Refittability refittability
Did the newgrf set any refittability property? If not, default refittability will be applied.
Definition: newgrf.cpp:330
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:153
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:6183
GRFTownName
Definition: newgrf_townname.h:35
RandomAccessFile::ReadWord
uint16 ReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: random_access_file.cpp:117
A5BLOCK_ALLOW_OFFSET
@ A5BLOCK_ALLOW_OFFSET
Allow replacing any subset by specifiing an offset.
Definition: newgrf.cpp:6184
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
RailtypeInfo::powered_railtypes
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
Definition: rail.h:185
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:60
RandomAccessFile::ReadDword
uint32 ReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: random_access_file.cpp:127
BuildCargoTranslationMap
static void BuildCargoTranslationMap()
Construct the Cargo Mapping.
Definition: newgrf.cpp:8744
Utf8Decode
size_t Utf8Decode(WChar *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:593
HouseSpec::cargo_acceptance
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:107
RailtypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: rail.h:243
WaterFeature::grffile
const GRFFile * grffile
NewGRF where 'group' belongs to.
Definition: newgrf_canal.h:24
_engine_offsets
const uint8 _engine_offsets[4]
Offset of the first engine of each vehicle type in original engine data.
Definition: engine.cpp:59
ShipVehicleInfo::old_refittable
bool old_refittable
Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
Definition: engine_type.h:74
AllowedSubtags::type
byte type
The type of the node, must be one of 'C', 'B' or 'T'.
Definition: newgrf.cpp:8169
GRFParameterInfo::first_bit
byte first_bit
First bit to use in the GRF parameter.
Definition: newgrf_config.h:144
BuildIndustriesLegend
void BuildIndustriesLegend()
Fills an array for the industries legends.
Definition: smallmap_gui.cpp:169
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:637
newgrf_object.h
BridgeSpec::min_length
byte min_length
the minimum length (not counting start and end tile)
Definition: bridge.h:43
IndustryProductionSpriteGroup::add_output
uint16 add_output[INDUSTRY_NUM_OUTPUTS]
Add this much output cargo when successful (unsigned, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:276
ObjectSpec::name
StringID name
The name for this object.
Definition: newgrf_object.h:64
ChangeGRFBlitter
static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
Callback function for 'INFO'->'BLTR' to set the blitter info.
Definition: newgrf.cpp:7957
RandomAccessFile::GetPos
size_t GetPos() const
Get position in the file.
Definition: random_access_file.cpp:73
AirportSpec::size_x
byte size_x
size of airport in x direction
Definition: newgrf_airport.h:105
FinaliseEngineArray
static void FinaliseEngineArray()
Check for invalid engines.
Definition: newgrf.cpp:9017
GRFParameterType
GRFParameterType
The possible types of a newgrf parameter.
Definition: newgrf_config.h:127
ChangeGRFNumUsedParams
static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
Callback function for 'INFO'->'NPAR' to set the number of valid parameters.
Definition: newgrf.cpp:7919
GRFTempEngineData::UNSET
@ UNSET
No properties assigned. Default refit masks shall be activated.
Definition: newgrf.cpp:320
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:7992
TileLayoutRegisters::sprite_var10
uint8 sprite_var10
Value for variable 10 when resolving the sprite.
Definition: newgrf_commons.h:102
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:61
GCS_UNKNOWN
@ GCS_UNKNOWN
The status of this grf file is unknown.
Definition: newgrf_config.h:35
ConstructionSettings::max_bridge_length
uint16 max_bridge_length
maximum length of bridges
Definition: settings_type.h:345
ObjectSpec::clear_cost_multiplier
uint8 clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_object.h:69
SpriteFile
RandomAccessFile with some extra information specific for sprite files.
Definition: sprite_file_type.hpp:19
LanguagePackHeader::GetGenderIndex
uint8 GetGenderIndex(const char *gender_str) const
Get the index for the given gender.
Definition: language.h:68
DeterministicSpriteGroupAdjust
Definition: newgrf_spritegroup.h:147
PriceBaseSpec
Describes properties of price bases.
Definition: economy_type.h:190
IndustryTileSpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
Cargo accepted by this tile.
Definition: industrytype.h:157
YearMonthDay::year
Year year
Year (0...)
Definition: date_type.h:105
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:140
ObjectSpec::generate_amount
uint8 generate_amount
Number of objects which are attempted to be generated per 256^2 map during world generation.
Definition: newgrf_object.h:77
GRFFile::canal_local_properties
CanalProperties canal_local_properties[CF_END]
Canal properties as set by this NewGRF.
Definition: newgrf.h:139
GRFError
Information about why GRF had problems during initialisation.
Definition: newgrf_config.h:112
RoadTypeInfo::grffile
const GRFFile * grffile[ROTSG_END]
NewGRF providing the Action3 for the roadtype.
Definition: road.h:185
RailtypeInfo::acceleration_type
uint8 acceleration_type
Acceleration type of this rail type.
Definition: rail.h:223
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:7905
GCS_DISABLED
@ GCS_DISABLED
GRF file is disabled.
Definition: newgrf_config.h:36
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
SetUnicodeGlyph
static void SetUnicodeGlyph(FontSize size, WChar key, SpriteID sprite)
Map a SpriteID to the font size and key.
Definition: fontcache.h:163
CIR_DISABLED
@ CIR_DISABLED
GRF was disabled due to error.
Definition: newgrf.cpp:993
GRFParameterInfo::max_value
uint32 max_value
The maximal value of this parameter.
Definition: newgrf_config.h:141
AllocateRailType
RailType AllocateRailType(RailTypeLabel label)
Allocate a new rail type label.
Definition: rail_cmd.cpp:159
ORIGINAL_MAX_YEAR
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: date_type.h:54
vehicle_func.h
rev.h
CURRENCY_END
@ CURRENCY_END
always the last item
Definition: currency.h:68
LanguagePackHeader::GetCaseIndex
uint8 GetCaseIndex(const char *case_str) const
Get the index for the given case.
Definition: language.h:81
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:8784
RailtypeInfo::flags
RailTypeFlags flags
Bit mask of rail type flags.
Definition: rail.h:208
VehicleSettings::dynamic_engines
bool dynamic_engines
enable dynamic allocation of engine data
Definition: settings_type.h:501
newgrf_sound.h
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
RoadVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:126
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:386
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:321
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:59
StationSpec
Station specification.
Definition: newgrf_station.h:113
CLEAN_RANDOMSOUNDS
@ CLEAN_RANDOMSOUNDS
Free the dynamically allocated sounds table.
Definition: industrytype.h:24
AirportSpec::enabled
bool enabled
Entity still available (by default true). Newgrf can disable it, though.
Definition: newgrf_airport.h:117
LanguageMap
Mapping of language data between a NewGRF and OpenTTD.
Definition: newgrf_text.h:58
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:28
IsHouseSpecValid
static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
Check if a given housespec is valid and disable it if it's not.
Definition: newgrf.cpp:9090
IndustrytilesChangeInfo
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
Define properties for industry tiles.
Definition: newgrf.cpp:3200
RailVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:48
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:108
GRFParameterInfo::value_names
SmallMap< uint32, GRFTextList > value_names
Names for each value.
Definition: newgrf_config.h:146
bridge.h
NEW_AIRPORT_OFFSET
@ NEW_AIRPORT_OFFSET
Number of the first newgrf airport.
Definition: airport.h:39
TileLayoutRegisters::palette
uint8 palette
Register specifying a signed offset for the palette.
Definition: newgrf_commons.h:95
GRFTempEngineData
Temporary engine data used when loading only.
Definition: newgrf.cpp:317
CC_ARMOURED
@ CC_ARMOURED
Armoured cargo (Valuables, Gold, Diamonds)
Definition: cargotype.h:44
ResetNewGRFErrors
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8622
GRFConfig::name
GRFTextWrapper name
NOSAVE: GRF name (Action 0x08)
Definition: newgrf_config.h:166
ResetNewGRF
static void ResetNewGRF()
Reset and clear all NewGRFs.
Definition: newgrf.cpp:8611
GRFLoadedFeatures::tram
TramReplacement tram
In which way tram depots were replaced.
Definition: newgrf.h:179
TileLayoutRegisters::max_palette_offset
uint16 max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset)
Definition: newgrf_commons.h:97
BridgeSpec::max_length
uint16 max_length
the maximum length (not counting start and end tile)
Definition: bridge.h:44
GRFParameterInfo::desc
GRFTextList desc
The description of this parameter.
Definition: newgrf_config.h:138
AllowedSubtags
Data structure to store the allowed id/type combinations for action 14.
Definition: newgrf.cpp:8111
FinaliseAirportsArray
static void FinaliseAirportsArray()
Add all new airports to the airport array.
Definition: newgrf.cpp:9322
IndustrySpec::cost_multiplier
uint8 cost_multiplier
Base construction cost multiplier.
Definition: industrytype.h:109
SHORE_REPLACE_ACTION_A
@ SHORE_REPLACE_ACTION_A
Shore sprites were replaced by ActionA (using grass tiles for the corner-shores).
Definition: newgrf.h:165
GCF_RESERVED
@ GCF_RESERVED
GRF file passed GLS_RESERVE stage.
Definition: newgrf_config.h:29
BridgeSpec::price
uint16 price
the price multiplier
Definition: bridge.h:45
SanitizeSpriteOffset
static uint16 SanitizeSpriteOffset(uint16 &num, uint16 offset, int max_sprites, const char *name)
Sanitize incoming sprite offsets for Action 5 graphics replacements.
Definition: newgrf.cpp:6160
GRFConfig::min_loadable_version
uint32 min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
Definition: newgrf_config.h:172
ObjectSpec::views
uint8 views
The number of views.
Definition: newgrf_object.h:76
TRAMWAY_REPLACE_DEPOT_WITH_TRACK
@ TRAMWAY_REPLACE_DEPOT_WITH_TRACK
Electrified depot graphics with tram track were loaded.
Definition: newgrf.h:171
IndustryTileSpec::animation
AnimationInfo animation
Information about the animation (is it looping, how many loops etc)
Definition: industrytype.h:169
AirportTileSpec::callback_mask
uint8 callback_mask
Bitmask telling which grf callback is set.
Definition: newgrf_airporttiles.h:69
MapSpriteMappingRecolour
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
Map the colour modifiers of TTDPatch to those that Open is using.
Definition: newgrf.cpp:717
GetGlobalVariable
bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
Definition: newgrf.cpp:6338
RAILTYPE_END
@ RAILTYPE_END
Used for iterations.
Definition: rail_type.h:33
CC_REFRIGERATED
@ CC_REFRIGERATED
Refrigerated cargo (Food, Fruit)
Definition: cargotype.h:48
CanalProperties::flags
uint8 flags
Flags controlling display.
Definition: newgrf.h:41
PaletteID
uint32 PaletteID
The number of the palette.
Definition: gfx_type.h:18
CommonVehicleChangeInfo
static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
Define properties common to all vehicles.
Definition: newgrf.cpp:1008
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:343
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:8176
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:8101
Action5Type::block_type
Action5BlockType block_type
How is this Action5 type processed?
Definition: newgrf.cpp:6189
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition: newgrf_airport.h:118
CargoSpec::quantifier
StringID quantifier
Text for multiple units of cargo of this type.
Definition: cargotype.h:74
SPR_AIRPORT_PREVIEW_BASE
static const SpriteID SPR_AIRPORT_PREVIEW_BASE
Airport preview sprites.
Definition: sprites.h:248
Action5Type::min_sprites
uint16 min_sprites
If the Action5 contains less sprites, the whole block will be ignored.
Definition: newgrf.cpp:6191
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:183
industrytype.h
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition: engine_type.h:28
GetEngineLiveryScheme
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
Definition: vehicle.cpp:1883
GetDefaultCargoID
CargoID GetDefaultCargoID(LandscapeID l, CargoType ct)
Get the cargo ID of a default cargo, if present.
Definition: cargotype.cpp:87
InitializeSortedCargoSpecs
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
Definition: cargotype.cpp:189
EngineInfo::variant_id
EngineID variant_id
Engine variant ID. If set, will be treated specially in purchase lists.
Definition: engine_type.h:158
GrfProcessingState::AddSpriteSets
void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
Records new spritesets.
Definition: newgrf.cpp:135
CurrencySpec::rate
uint16 rate
The conversion rate compared to the base currency.
Definition: currency.h:73
SPR_OPENTTD_BASE
static const SpriteID SPR_OPENTTD_BASE
Extra graphic spritenumbers.
Definition: sprites.h:56
IndustrySpec::production_down_text
StringID production_down_text
Message appearing when the industry's production is decreasing.
Definition: industrytype.h:131
TRAMWAY_REPLACE_DEPOT_NONE
@ TRAMWAY_REPLACE_DEPOT_NONE
No tram depot graphics were loaded.
Definition: newgrf.h:170
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:1298
CargoSpec::classes
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:79
RoadVehicleChangeInfo
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for road vehicles.
Definition: newgrf.cpp:1360
AirportTileSpec::enabled
bool enabled
entity still available (by default true). newgrf can disable it, though
Definition: newgrf_airporttiles.h:71
IndustrySpec::cleanup_flag
uint8 cleanup_flag
flags indicating which data should be freed upon cleaning up
Definition: industrytype.h:139
IndustrySpec::appear_ingame
byte appear_ingame[NUM_LANDSCAPE]
Probability of appearance in game.
Definition: industrytype.h:133
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:141
TRAMWAY_REPLACE_DEPOT_NO_TRACK
@ TRAMWAY_REPLACE_DEPOT_NO_TRACK
Electrified depot graphics without tram track were loaded.
Definition: newgrf.h:172
RoadTypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: road.h:155
NewGRFSpriteLayout::consistent_max_offset
uint consistent_max_offset
Number of sprites in all referenced spritesets.
Definition: newgrf_commons.h:120
HouseSpec::watched_cargoes
CargoTypes watched_cargoes
Cargo types watched for acceptance.
Definition: house.h:123
NUM_CARGO
@ NUM_CARGO
Maximal number of cargo types in a game.
Definition: cargo_type.h:65
IsSnowLineSet
bool IsSnowLineSet()
Has a snow line table already been loaded.
Definition: landscape.cpp:627
RailTypeFlags
RailTypeFlags
Railtype flags.
Definition: rail.h:25
RailtypeInfo::label
RailTypeLabel label
Unique 32 bit rail type identifier.
Definition: rail.h:233
StationClassID
StationClassID
Definition: newgrf_station.h:83
GetCargoTranslation
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:79
IndustrySpec::prospecting_chance
uint32 prospecting_chance
Chance prospecting succeeds.
Definition: industrytype.h:111
ConstructionSettings::train_signal_side
byte train_signal_side
show signals on left / driving / right side
Definition: settings_type.h:348
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:137
GRFFile::cargo_map
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:128
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:307
IndustryTileLayoutTile
Definition of one tile in an industry tile layout.
Definition: industrytype.h:96
RailtypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: rail.h:176
VehicleSettings::disable_elrails
bool disable_elrails
when true, the elrails are disabled
Definition: settings_type.h:494
InitNewGRFFile
static void InitNewGRFFile(const GRFConfig *config)
Prepare loading a NewGRF file with its config.
Definition: newgrf.cpp:8767
CommitVehicleListOrderChanges
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
Definition: newgrf_engine.cpp:1328
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
NewGRFClass::name
StringID name
Name of this class.
Definition: newgrf_class.h:39
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:22
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
IndustryProductionSpriteGroup::version
uint8 version
Production callback version used, or 0xFF if marked invalid.
Definition: newgrf_spritegroup.h:271
AirportSpec::GetWithoutOverride
static AirportSpec * GetWithoutOverride(byte type)
Retrieve airport spec for the given airport.
Definition: newgrf_airport.cpp:117
TileLayoutFlags
TileLayoutFlags
Flags to enable register usage in sprite layouts.
Definition: newgrf_commons.h:33
CargoSpec::name
StringID name
Name of this type of cargo.
Definition: cargotype.h:71
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:8635
AircraftVehicleChangeInfo
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for aircraft.
Definition: newgrf.cpp:1750
GRFFile::cargo_list
std::vector< CargoLabel > cargo_list
Cargo translation table (local ID -> label)
Definition: newgrf.h:127
GameCreationSettings::starting_year
Year starting_year
starting date
Definition: settings_type.h:313
TE_MAIL
@ TE_MAIL
Cargo behaves mail-like.
Definition: cargotype.h:30
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:168
GRFFile::labels
std::vector< GRFLabel > labels
List of labels.
Definition: newgrf.h:125
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:9597
HZ_CLIMALL
@ HZ_CLIMALL
Bitmask of all climate bits.
Definition: house.h:84
RoadVehicleInfo::tractive_effort
uint8 tractive_effort
Coefficient of tractive effort.
Definition: engine_type.h:123
GrfProcessingState::stage
GrfLoadingStage stage
Current loading stage.
Definition: newgrf.cpp:99
ExtraEngineFlags
ExtraEngineFlags
Definition: engine_type.h:130
ORIGINAL_SAMPLE_COUNT
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition: sound_type.h:116
IndustrySpec::callback_mask
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:138
AnimationInfo::triggers
uint16 triggers
The triggers that trigger animation.
Definition: newgrf_animation_type.h:22
IgnoreObjectProperty
static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
Ignore properties for objects.
Definition: newgrf.cpp:4049
CHECK_NOTHING
@ CHECK_NOTHING
Always succeeds.
Definition: industrytype.h:40
AircraftVehicleInfo::mail_capacity
byte mail_capacity
Mail capacity (bags).
Definition: engine_type.h:107
CargoSpec::name_single
StringID name_single
Name of a single entity of this type of cargo.
Definition: cargotype.h:72
PTYPE_END
@ PTYPE_END
Invalid parameter type.
Definition: newgrf_config.h:130
IndustrySpec::random_sounds
const uint8 * random_sounds
array of random sounds.
Definition: industrytype.h:136
GrfProcessingState::GetNumEnts
uint GetNumEnts(byte feature, uint set) const
Returns the number of sprites in a spriteset.
Definition: newgrf.cpp:188
CargoSpec::abbrev
StringID abbrev
Two letter abbreviation for this cargo type.
Definition: cargotype.h:75
ReallocT
static 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
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:123
RoadVehicleInfo::weight
uint8 weight
Weight in 1/4t units.
Definition: engine_type.h:121
Action5Type::name
const char * name
Name for error messages.
Definition: newgrf.cpp:6193
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, byte type, uint16 num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:126
abs
static T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:21
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
FinaliseHouseArray
static void FinaliseHouseArray()
Add all new houses to the house array.
Definition: newgrf.cpp:9163
GRFConfig::palette
uint8 palette
GRFPalette, bitset.
Definition: newgrf_config.h:179
RailVehicleInfo::intended_railtype
RailType intended_railtype
Intended railtype, regardless of elrail being enabled or disabled.
Definition: engine_type.h:47
CargoSpec::multiplier
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:63
IndustryTileSpec::callback_mask
uint8 callback_mask
Bitmask of industry tile callbacks that have to be called.
Definition: industrytype.h:168
_grm_cargoes
static uint32 _grm_cargoes[NUM_CARGO *2]
Contains the GRF ID of the owner of a cargo if it has been reserved.
Definition: newgrf.cpp:358
NewGRFSpriteLayout::Clone
void Clone(const DrawTileSeqStruct *source)
Clone the building sprites of a spritelayout.
Definition: newgrf_commons.cpp:586
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:134
StationSpec::cargo_threshold
uint16 cargo_threshold
Cargo threshold for choosing between little and lots of cargo.
Definition: newgrf_station.h:154
RandomAccessFile::SeekTo
void SeekTo(size_t pos, int mode)
Seek in the current file.
Definition: random_access_file.cpp:83
RailVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:59
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:171
RoadTypeInfo::cost_multiplier
uint16 cost_multiplier
Cost multiplier for building this road type.
Definition: road.h:130
SmallMap::Find
std::vector< Pair >::const_iterator Find(const T &key) const
Finds given key in this map.
Definition: smallmap_type.hpp:41
CurrencySpec::to_euro
Year to_euro
Year of switching to the Euro. May also be CF_NOEURO or CF_ISEURO.
Definition: currency.h:75
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:995
GRFTempEngineData::NONEMPTY
@ NONEMPTY
GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not av...
Definition: newgrf.cpp:322
AllowedSubtags::id
uint32 id
The identifier for this node.
Definition: newgrf.cpp:8168
IndustrySpec::behaviour
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Definition: industrytype.h:125
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
AnimationInfo::status
uint8 status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition: newgrf_animation_type.h:20
ResetObjects
void ResetObjects()
This function initialize the spec arrays of objects.
Definition: newgrf_object.cpp:94
SetBit
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
TE_WATER
@ TE_WATER
Cargo behaves water-like.
Definition: cargotype.h:32
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
HouseSpec::min_year
Year min_year
introduction year of the house
Definition: house.h:100
CurrencySpec::separator
std::string separator
The thousands separator for this currency.
Definition: currency.h:74
YearMonthDay
Data structure to convert between Date and triplet (year, month, and day).
Definition: date_type.h:104
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:125
NewGRFClass::Get
static NewGRFClass * Get(Tid cls_id)
Get a particular class.
Definition: newgrf_class_func.h:103
RoadTypeInfo::max_speed
uint16 max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:140
InitializeGRFSpecial
static void InitializeGRFSpecial()
Initialize the TTDPatch flags.
Definition: newgrf.cpp:8406
DataHandler
bool(* DataHandler)(size_t, ByteReader *)
Type of callback function for binary nodes.
Definition: newgrf.cpp:8100
RandomizedSpriteGroup::lowest_randbit
byte lowest_randbit
Look for this in the per-object randomized bitmask:
Definition: newgrf_spritegroup.h:199
RailtypeInfo::new_loco
StringID new_loco
Name of an engine for this type of rail in the engine preview GUI.
Definition: rail.h:178
ActivateOldShore
static void ActivateOldShore()
Relocates the old shore sprites at new positions.
Definition: newgrf.cpp:9560
BridgeSpec::material
StringID material
the string that contains the bridge description
Definition: bridge.h:49
RoadVehicleInfo::power
uint8 power
Power in 10hp units.
Definition: engine_type.h:122
TileLayoutRegisters::flags
TileLayoutFlags flags
Flags defining which members are valid and to be used.
Definition: newgrf_commons.h:92
AirportSpec::depot_table
const HangarTileTable * depot_table
gives the position of the depots on the airports
Definition: newgrf_airport.h:103
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:8292
RailtypeInfo::compatible_railtypes
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition: rail.h:188
CT_PURCHASE_OBJECT
static const CargoID CT_PURCHASE_OBJECT
Mapping of purchase for objects.
Definition: newgrf_object.h:161
newgrf_canal.h
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:2294
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:25
MemSetT
static void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
VehicleSettings::never_expire_vehicles
bool never_expire_vehicles
never expire vehicles
Definition: settings_type.h:502
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:113
GrfProcessingState::SpriteSet::num_sprites
uint num_sprites
Number of sprites in the set.
Definition: newgrf.cpp:91
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:24
RoadTypeFlags
RoadTypeFlags
Roadtype flags.
Definition: road.h:38
OverrideManagerBase::AddEntityID
virtual uint16 AddEntityID(byte grf_local_id, uint32 grfid, byte substitute_id)
Reserves a place in the mapping array for an entity to be installed.
Definition: newgrf_commons.cpp:123
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:991
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
BridgeChangeInfo
static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
Define properties for bridges.
Definition: newgrf.cpp:2183
fontcache.h
_object_mngr
ObjectOverrideManager _object_mngr
The override manager for our objects.
HouseZones
HouseZones
Definition: house.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:2652
VehicleSettings::plane_speed
uint8 plane_speed
divisor for speed of aircraft
Definition: settings_type.h:499
RailtypeInfo::maintenance_multiplier
uint16 maintenance_multiplier
Cost multiplier for maintenance of this rail type.
Definition: rail.h:218
RailTypeChangeInfo
static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for railtypes.
Definition: newgrf.cpp:4231
Engine::grf_prop
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:76
RAILVEH_SINGLEHEAD
@ RAILVEH_SINGLEHEAD
indicates a "standalone" locomotive
Definition: engine_type.h:27
IndustryTileSpecialFlags
IndustryTileSpecialFlags
Flags for miscellaneous industry tile specialities.
Definition: industrytype.h:88
IndustrySpec::check_proc
byte check_proc
Index to a procedure to check for conflicting circumstances.
Definition: industrytype.h:113
ReadGRFSpriteOffsets
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Definition: spritecache.cpp:555
ShipVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:70
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:167
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
GRFFilePropsBase::local_id
uint16 local_id
id defined by the grf file for this entity
Definition: newgrf_commons.h:319
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:510
FinaliseCargoArray
static void FinaliseCargoArray()
Check for invalid cargoes.
Definition: newgrf.cpp:9067
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:588
GrfProcessingState::IsValidSpriteSet
bool IsValidSpriteSet(byte feature, uint set) const
Check whether a specific set is defined.
Definition: newgrf.cpp:164
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:595
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:202
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:65
TLF_SPRITE
@ TLF_SPRITE
Add signed offset to sprite from register TileLayoutRegisters::sprite.
Definition: newgrf_commons.h:37
ClearTemporaryNewGRFData
static void ClearTemporaryNewGRFData(GRFFile *gf)
Reset all NewGRFData that was used only while processing data.
Definition: newgrf.cpp:430
EngineInfo::climates
byte climates
Climates supported by the engine.
Definition: engine_type.h:149
TLF_PALETTE
@ TLF_PALETTE
Add signed offset to palette from register TileLayoutRegisters::palette.
Definition: newgrf_commons.h:38
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:128
AirportSpec::nof_depots
byte nof_depots
the number of hangar tiles in this airport
Definition: newgrf_airport.h:104
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:689
ResetRoadTypes
void ResetRoadTypes()
Reset all road type information to its default values.
Definition: road_cmd.cpp:65
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:158
PROP_ROADVEH_POWER
@ PROP_ROADVEH_POWER
Power in 10 HP.
Definition: newgrf_properties.h:36
TE_FOOD
@ TE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:33
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
RandomizedSpriteGroup
Definition: newgrf_spritegroup.h:190
RailtypeInfo::group
const SpriteGroup * group[RTSG_END]
Sprite groups for resolving sprites.
Definition: rail.h:278
IndustrySpec::name
StringID name
Displayed name of the industry.
Definition: industrytype.h:127
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:8088
IndustryBehaviour
IndustryBehaviour
Various industry behaviours mostly to represent original TTD specialities.
Definition: industrytype.h:61
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:128
StationSpec::disallowed_lengths
byte disallowed_lengths
Bitmask of platform lengths available for the station.
Definition: newgrf_station.h:138
_misc_grf_features
byte _misc_grf_features
Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E.
Definition: newgrf.cpp:75
RailtypeInfo::strings
struct RailtypeInfo::@39 strings
Strings associated with the rail type.
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:7619
ByteReader
Class to read from a NewGRF file.
Definition: newgrf.cpp:213
LoadGRFSound
static void LoadGRFSound(size_t offs, SoundEntry *sound)
Load a sound from a file.
Definition: newgrf.cpp:7668
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, BranchHandler handler)
Create a branch node with a callback handler.
Definition: newgrf.cpp:8147
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:493
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:320
PROP_AIRCRAFT_SPEED
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
Definition: newgrf_properties.h:50
AirportTileSpec::name
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
Definition: newgrf_airporttiles.h:68
CanalProperties
Canal properties local to the NewGRF.
Definition: newgrf.h:39
ResetBridges
void ResetBridges()
Reset the data been eventually changed by the grf loaded.
Definition: tunnelbridge_cmd.cpp:85
RailtypeInfo::cost_multiplier
uint16 cost_multiplier
Cost multiplier for building this rail type.
Definition: rail.h:213
DateFract
uint16 DateFract
The fraction of a date we're in, i.e. the number of ticks since the last date changeover.
Definition: date_type.h:15
AllowedSubtags::data
DataHandler data
Callback function for a binary node, only valid if type == 'B'.
Definition: newgrf.cpp:8171
OBJECT_SIZE_1X1
static const uint8 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
AirportTileTable::ti
TileIndexDiffC ti
Tile offset from the top-most airport tile.
Definition: newgrf_airport.h:24
GRFConfig::filename
char * filename
Filename - either with or without full path.
Definition: newgrf_config.h:165
EngineInfo::string_id
StringID string_id
Default name of engine.
Definition: engine_type.h:156
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition: engine_type.h:99
GetLanguage
const LanguageMetadata * GetLanguage(byte newgrflangid)
Get the language with the given NewGRF language ID.
Definition: strings.cpp:1933
ObjectSpec::climate
uint8 climate
In which climates is this object available?
Definition: newgrf_object.h:66
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
AirportSpec::table
const AirportTileTable *const * table
list of the tiles composing the airport
Definition: newgrf_airport.h:100
HangarTileTable
A list of all hangar tiles in an airport.
Definition: newgrf_airport.h:89
CT_INVALID
@ CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:69
_tick_counter
uint64 _tick_counter
Ever incrementing tick counter for setting off various events.
Definition: date.cpp:30
MapGRFStringID
StringID MapGRFStringID(uint32 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:557
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:36
TownHouseChangeInfo
static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
Define properties for houses.
Definition: newgrf.cpp:2361
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:260
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:75
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
VehicleSettings::freight_trains
uint8 freight_trains
value to multiply the weight of cargo by
Definition: settings_type.h:500
ChangeGRFPalette
static bool ChangeGRFPalette(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PALS' to set the number of valid parameters.
Definition: newgrf.cpp:7931
LoadFontGlyph
static void LoadFontGlyph(ByteReader *buf)
Action 0x12.
Definition: newgrf.cpp:7788
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
IndustryTileSpec::anim_next
byte anim_next
Next frame in an animation.
Definition: industrytype.h:161
IndustryTileSpec
Defines the data structure of each individual tile of an industry.
Definition: industrytype.h:156
GRFLoadedFeatures
Definition: newgrf.h:175
TLF_DRAWING_FLAGS
@ TLF_DRAWING_FLAGS
Flags which are still required after loading the GRF.
Definition: newgrf_commons.h:53
TLF_PALETTE_VAR10
@ TLF_PALETTE_VAR10
Resolve palette with a specific value in variable 10.
Definition: newgrf_commons.h:48
InitRailTypes
void InitRailTypes()
Resolve sprites of custom rail types.
Definition: rail_cmd.cpp:139
CurrencySpec::prefix
std::string prefix
Prefix to apply when formatting money in this currency.
Definition: currency.h:76
CC_MAIL
@ CC_MAIL
Mail.
Definition: cargotype.h:42
HouseSpec::remove_rating_decrease
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:105
DisableGrf
static GRFError * DisableGrf(StringID message=STR_NULL, GRFConfig *config=nullptr)
Disable a GRF.
Definition: newgrf.cpp:441
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition: newgrf_airporttiles.h:72
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:62
InitRoadTypes
void InitRoadTypes()
Resolve sprites of custom road types.
Definition: road_cmd.cpp:121
RoadTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: road.h:104
GetFileByFilename
static GRFFile * GetFileByFilename(const char *filename)
Obtain a NewGRF file by its filename.
Definition: newgrf.cpp:421
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:109
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:96
ResetCustomStations
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8495
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:47
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
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:528
MAX_NUM_CASES
static const uint8 MAX_NUM_CASES
Maximum number of supported cases.
Definition: language.h:21
_ttdpatch_flags
static uint32 _ttdpatch_flags[8]
32 * 8 = 256 flags.
Definition: newgrf.cpp:78
BuildLinkStatsLegend
void BuildLinkStatsLegend()
Populate legend table for the link stat view.
Definition: smallmap_gui.cpp:199
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:8021
EngineInfo::cargo_age_period
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:157
GrfProcessingState::nfo_line
uint32 nfo_line
Currently processed pseudo sprite number in the GRF.
Definition: newgrf.cpp:106
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:170
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:859
GetCargoIDByLabel
CargoID GetCargoIDByLabel(CargoLabel cl)
Get the cargo ID by cargo label.
Definition: cargotype.cpp:108
newgrf_cargo.h
SetYearEngineAgingStops
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:627
RailtypeInfo::curve_speed
byte curve_speed
Multiplier for curve maximum speed advantage.
Definition: rail.h:203
MapLogY
static uint MapLogY()
Logarithm of the map size along the y side.
Definition: map_func.h:62
GRFFile::railtype_list
std::vector< RailTypeLabel > railtype_list
Railtype translation table.
Definition: newgrf.h:130
AirportSpec::catchment
byte catchment
catchment area of this airport
Definition: newgrf_airport.h:108
RandomizedSpriteGroup::groups
std::vector< const SpriteGroup * > groups
Take the group with appropriate index:
Definition: newgrf_spritegroup.h:201
ReadSpriteLayoutSprite
static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16 *max_sprite_offset=nullptr, uint16 *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:748
StationSpec::cargo_triggers
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
Definition: newgrf_station.h:156
SpriteGroup
Definition: newgrf_spritegroup.h:57
GRFLabel
Definition: newgrf.h:97
SkipAct12
static void SkipAct12(ByteReader *buf)
Action 0x12 (SKIP)
Definition: newgrf.cpp:7819
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:480
GetGRFConfig
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:771
ResetGenericCallbacks
void ResetGenericCallbacks()
Reset all generic feature callback sprite groups.
Definition: newgrf_generic.cpp:95
Action5Type
Information about a single action 5 type.
Definition: newgrf.cpp:6188
_currency_specs
CurrencySpec _currency_specs[CURRENCY_END]
Array of currencies used by the system.
Definition: currency.cpp:74
NamePart::id
byte id
If probability bit 7 is set.
Definition: newgrf_townname.h:23
LanguageMap::Mapping::newgrf_id
byte newgrf_id
NewGRF's internal ID for a case/gender.
Definition: newgrf_text.h:61
RailVehicleInfo::curve_speed_mod
int16 curve_speed_mod
Modifier to maximum speed in curves (fixed-point binary with 8 fractional bits)
Definition: engine_type.h:63
StationSpec::wires
byte wires
Bitmask of base tiles (0 - 7) which should contain elrail wires.
Definition: newgrf_station.h:163
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:493
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:70
OrderSettings::gradual_loading
bool gradual_loading
load vehicles gradually
Definition: settings_type.h:479
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:624
Action5Type::max_sprites
uint16 max_sprites
If the Action5 contains more sprites, only the first max_sprites sprites will be used.
Definition: newgrf.cpp:6192
GRFConfig::param_info
std::vector< GRFParameterInfo * > param_info
NOSAVE: extra information about the parameters.
Definition: newgrf_config.h:180
IndustryLifeType
IndustryLifeType
Available types of industry lifetimes.
Definition: industrytype.h:28
GRFFile
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:106
ObjectSpec::cls_id
ObjectClassID cls_id
The class to which this spec belongs.
Definition: newgrf_object.h:63
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:76
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:55
TE_PASSENGERS
@ TE_PASSENGERS
Cargo behaves passenger-like.
Definition: cargotype.h:29
IgnoreIndustryTileProperty
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
Ignore an industry tile property.
Definition: newgrf.cpp:3160
StationSpec::blocked
byte blocked
Bitmask of base tiles (0 - 7) which are blocked to trains.
Definition: newgrf_station.h:164
debug.h
GRFConfig::param
uint32 param[0x80]
GRF parameters.
Definition: newgrf_config.h:176
DAYS_TILL_ORIGINAL_BASE_YEAR
#define DAYS_TILL_ORIGINAL_BASE_YEAR
The offset in days from the '_date == 0' till 'ConvertYMDToDate(ORIGINAL_BASE_YEAR,...
Definition: date_type.h:81
GRFParameterInfo::min_value
uint32 min_value
The minimal value this parameter can have.
Definition: newgrf_config.h:140
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:105
RoadTypeInfo::maintenance_multiplier
uint16 maintenance_multiplier
Cost multiplier for maintenance of this road type.
Definition: road.h:135
PROP_ROADVEH_WEIGHT
@ PROP_ROADVEH_WEIGHT
Weight in 1/4 t.
Definition: newgrf_properties.h:37
TileLayoutRegisters::max_sprite_offset
uint16 max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset)
Definition: newgrf_commons.h:96
SPR_TRAMWAY_BASE
static const SpriteID SPR_TRAMWAY_BASE
Tramway sprites.
Definition: sprites.h:272
engine_func.h
AirportTileSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_airporttiles.h:67
RoadTypeInfo::strings
struct RoadTypeInfo::@42 strings
Strings associated with the rail type.
EC_MONORAIL
@ EC_MONORAIL
Mono rail engine.
Definition: engine_type.h:37
WaterFeature::group
const SpriteGroup * group
Sprite group to start resolving.
Definition: newgrf_canal.h:23
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
ObjectSpec::flags
ObjectFlags flags
Flags/settings related to the object.
Definition: newgrf_object.h:72
RoadTypeChangeInfo
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
Define properties for roadtypes.
Definition: newgrf.cpp:4449
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:176
RailtypeInfo::introduces_railtypes
RailTypes introduces_railtypes
Bitmask of which other railtypes are introduced when this railtype is introduced.
Definition: rail.h:263
MAX_YEAR
static const Year MAX_YEAR
MAX_YEAR, nicely rounded value of the number of years that can be encoded in a single 32 bits date,...
Definition: date_type.h:95
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132
SNOW_LINE_MONTHS
static const uint SNOW_LINE_MONTHS
Number of months in the snow line table.
Definition: landscape.h:16
CanalFeature
CanalFeature
List of different canal 'features'.
Definition: newgrf.h:25
TileIndexDiffC::x
int16 x
The x value of the coordinate.
Definition: map_type.h:58
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:806
GRFP_BLT_MASK
@ GRFP_BLT_MASK
Bitmask to only get the blitter information.
Definition: newgrf_config.h:78