OpenTTD Source: src/newgrf.cpp Source File

OpenTTD Source 12.2

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 "newgrf_canal.h"
31 #include "newgrf_townname.h"
32 #include "newgrf_industries.h"
33 #include "newgrf_airporttiles.h"
34 #include "newgrf_airport.h"
35 #include "newgrf_object.h"
36 #include "rev.h"
37 #include "fios.h"
38 #include "strings_func.h"
39 #include "date_func.h"
40 #include "string_func.h"
41 #include "network/core/config.h"
42 #include <map>
43 #include "smallmap_gui.h"
44 #include "genworld.h"
45 #include "error.h"
46 #include "vehicle_func.h"
47 #include "language.h"
48 #include "vehicle_base.h"
49 #include "road.h"
50
51 #include "table/strings.h"
52 #include "table/build_industry.h"
53
54 #include "safeguards.h"
55
56 /* TTDPatch extended GRF format codec
57 * (c) Petr Baudis 2004 (GPL'd)
58 * Changes by Florian octo Forster are (c) by the OpenTTD development team.
59 *
60 * Contains portions of documentation by TTDPatch team.
61 * Thanks especially to Josef Drexler for the documentation as well as a lot
62 * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
63 * served as subject to the initial testing of this codec. */
64
66 static std::vector<GRFFile *> _grf_files;
67
68 const std::vector<GRFFile *> &GetAllGRFFiles()
69 {
70 return _grf_files;
71 }
72
74 byte _misc_grf_features = 0;
75
77 static uint32 _ttdpatch_flags[8];
78
80 GRFLoadedFeatures _loaded_newgrf_features;
81
82 static const uint MAX_SPRITEGROUP = UINT8_MAX;
83
85 struct GrfProcessingState {
86 private:
88 struct SpriteSet {
89 SpriteID sprite;
90 uint num_sprites;
91 };
92
94 std::map<uint, SpriteSet> spritesets[GSF_END];
95
96 public:
97 /* Global state */
98 GrfLoadingStage stage;
99 SpriteID spriteid;
100
101 /* Local state in the file */
102 SpriteFile *file;
103 GRFFile *grffile;
104 GRFConfig *grfconfig;
105 uint32 nfo_line;
106
107 /* Kind of return values when processing certain actions */
108 int skip_sprites;
109
110 /* Currently referenceable spritegroups */
111 const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
112
114 void ClearDataForNextFile()
115 {
116 this->nfo_line = 0;
117 this->skip_sprites = 0;
118
119 for (uint i = 0; i < GSF_END; i++) {
120 this->spritesets[i].clear();
121 }
122
123 memset(this->spritegroups, 0, sizeof(this->spritegroups));
124 }
125
134 void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
135 {
136 assert(feature < GSF_END);
137 for (uint i = 0; i < numsets; i++) {
138 SpriteSet &set = this->spritesets[feature][first_set + i];
139 set.sprite = first_sprite + i * numents;
140 set.num_sprites = numents;
141 }
142 }
143
150 bool HasValidSpriteSets(byte feature) const
151 {
152 assert(feature < GSF_END);
153 return !this->spritesets[feature].empty();
154 }
155
163 bool IsValidSpriteSet(byte feature, uint set) const
164 {
165 assert(feature < GSF_END);
166 return this->spritesets[feature].find(set) != this->spritesets[feature].end();
167 }
168
175 SpriteID GetSprite(byte feature, uint set) const
176 {
177 assert(IsValidSpriteSet(feature, set));
178 return this->spritesets[feature].find(set)->second.sprite;
179 }
180
187 uint GetNumEnts(byte feature, uint set) const
188 {
189 assert(IsValidSpriteSet(feature, set));
190 return this->spritesets[feature].find(set)->second.num_sprites;
191 }
192 };
193
194 static GrfProcessingState _cur;
195
196
203 template <VehicleType T>
204 static inline bool IsValidNewGRFImageIndex(uint8 image_index)
205 {
206 return image_index == 0xFD || IsValidImageIndex<T>(image_index);
207 }
208
209 class OTTDByteReaderSignal { };
210
212 class ByteReader {
213 protected:
214 byte *data;
215 byte *end;
216
217 public:
218 ByteReader(byte *data, byte *end) : data(data), end(end) { }
219
220 inline byte *ReadBytes(size_t size)
221 {
222 if (data + size >= end) {
223 /* Put data at the end, as would happen if every byte had been individually read. */
224 data = end;
225 throw OTTDByteReaderSignal();
226 }
227
228 byte *ret = data;
229 data += size;
230 return ret;
231 }
232
233 inline byte ReadByte()
234 {
235 if (data < end) return *(data)++;
236 throw OTTDByteReaderSignal();
237 }
238
239 uint16 ReadWord()
240 {
241 uint16 val = ReadByte();
242 return val | (ReadByte() << 8);
243 }
244
245 uint16 ReadExtendedByte()
246 {
247 uint16 val = ReadByte();
248 return val == 0xFF ? ReadWord() : val;
249 }
250
251 uint32 ReadDWord()
252 {
253 uint32 val = ReadWord();
254 return val | (ReadWord() << 16);
255 }
256
257 uint32 ReadVarSize(byte size)
258 {
259 switch (size) {
260 case 1: return ReadByte();
261 case 2: return ReadWord();
262 case 4: return ReadDWord();
263 default:
264 NOT_REACHED();
265 return 0;
266 }
267 }
268
269 const char *ReadString()
270 {
271 char *string = reinterpret_cast<char *>(data);
272 size_t string_length = ttd_strnlen(string, Remaining());
273
274 if (string_length == Remaining()) {
275 /* String was not NUL terminated, so make sure it is now. */
276 string[string_length - 1] = '\0';
277 grfmsg(7, "String was not terminated with a zero byte.");
278 } else {
279 /* Increase the string length to include the NUL byte. */
280 string_length++;
281 }
282 Skip(string_length);
283
284 return string;
285 }
286
287 inline size_t Remaining() const
288 {
289 return end - data;
290 }
291
292 inline bool HasData(size_t count = 1) const
293 {
294 return data + count <= end;
295 }
296
297 inline byte *Data()
298 {
299 return data;
300 }
301
302 inline void Skip(size_t len)
303 {
304 data += len;
305 /* It is valid to move the buffer to exactly the end of the data,
306 * as there may not be any more data read. */
307 if (data > end) throw OTTDByteReaderSignal();
308 }
309 };
310
311 typedef void (*SpecialSpriteHandler)(ByteReader *buf);
312
313 static const uint NUM_STATIONS_PER_GRF = 255;
314
316 struct GRFTempEngineData {
318 enum Refittability {
319 UNSET = 0,
320 EMPTY,
321 NONEMPTY,
322 };
323
324 uint16 cargo_allowed;
325 uint16 cargo_disallowed;
326 RailTypeLabel railtypelabel;
327 uint8 roadtramtype;
328 const GRFFile *defaultcargo_grf;
329 Refittability refittability;
330 bool prop27_set;
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 /* Clear the GOTO labels used for GRF processing */
433 for (GRFLabel *l = gf->label; l != nullptr;) {
434 GRFLabel *l2 = l->next;
435 free(l);
436 l = l2;
437 }
438 gf->label = nullptr;
439 }
440
447 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
448 {
449 GRFFile *file;
450 if (config != nullptr) {
451 file = GetFileByGRFID(config->ident.grfid);
452 } else {
453 config = _cur.grfconfig;
454 file = _cur.grffile;
455 }
456
457 config->status = GCS_DISABLED;
458 if (file != nullptr) ClearTemporaryNewGRFData(file);
459 if (config == _cur.grfconfig) _cur.skip_sprites = -1;
460
461 if (message != STR_NULL) {
462 delete config->error;
463 config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, message);
464 if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
465 }
466
467 return config->error;
468 }
469
473 struct StringIDMapping {
474 uint32 grfid;
475 StringID source;
476 StringID *target;
477 };
478 typedef std::vector<StringIDMapping> StringIDMappingVector;
479 static StringIDMappingVector _string_to_grf_mapping;
480
486 static void AddStringForMapping(StringID source, StringID *target)
487 {
488 *target = STR_UNDEFINED;
489 _string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
490 }
491
499 static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
500 {
501 /* StringID table for TextIDs 0x4E->0x6D */
502 static const StringID units_volume[] = {
503 STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
504 STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
505 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
506 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
507 STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
508 STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
509 STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
510 STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
511 };
512
513 /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
514 assert(!IsInsideMM(str, 0xD000, 0xD7FF));
515
516 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
517 static_assert(stringend - stringid == end - begin); \
518 if (str >= begin && str <= end) return str + (stringid - begin)
519
520 /* We have some changes in our cargo strings, resulting in some missing. */
521 TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
522 TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
523 if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
524 TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
525 TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
526 TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
527
528 /* Map building names according to our lang file changes. There are several
529 * ranges of house ids, all of which need to be remapped to allow newgrfs
530 * to use original house names. */
531 TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
532 TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
533 TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
534
535 /* Same thing for industries */
536 TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
537 TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
538 TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
539 TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
540 TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
541
542 switch (str) {
543 case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
544 case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
545 case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
546 }
547 #undef TEXTID_TO_STRINGID
548
549 if (str == STR_NULL) return STR_EMPTY;
550
551 Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
552
553 return STR_EMPTY;
554 }
555
563 StringID MapGRFStringID(uint32 grfid, StringID str)
564 {
565 if (IsInsideMM(str, 0xD800, 0xE000)) {
566 /* General text provided by NewGRF.
567 * In the specs this is called the 0xDCxx range (misc persistent texts),
568 * but we meanwhile extended the range to 0xD800-0xDFFF.
569 * Note: We are not involved in the "persistent" business, since we do not store
570 * any NewGRF strings in savegames. */
571 return GetGRFStringID(grfid, str);
572 } else if (IsInsideMM(str, 0xD000, 0xD800)) {
573 /* Callback text provided by NewGRF.
574 * In the specs this is called the 0xD0xx range (misc graphics texts).
575 * These texts can be returned by various callbacks.
576 *
577 * Due to how TTDP implements the GRF-local- to global-textid translation
578 * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
579 * We do not care about that difference and just mask out the 0x400 bit.
580 */
581 str &= ~0x400;
582 return GetGRFStringID(grfid, str);
583 } else {
584 /* The NewGRF wants to include/reference an original TTD string.
585 * Try our best to find an equivalent one. */
586 return TTDPStringIDToOTTDStringIDMapping(str);
587 }
588 }
589
590 static std::map<uint32, uint32> _grf_id_overrides;
591
597 static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
598 {
599 _grf_id_overrides[source_grfid] = target_grfid;
600 grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
601 }
602
611 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access = false)
612 {
613 /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
614 * them use the same engine slots. */
615 uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
616 if (_settings_game.vehicle.dynamic_engines) {
617 /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
618 scope_grfid = file->grfid;
619 uint32 override = _grf_id_overrides[file->grfid];
620 if (override != 0) {
621 scope_grfid = override;
622 const GRFFile *grf_match = GetFileByGRFID(override);
623 if (grf_match == nullptr) {
624 grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
625 } else {
626 grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
627 }
628 }
629
630 /* Check if the engine is registered in the override manager */
631 EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
632 if (engine != INVALID_ENGINE) {
633 Engine *e = Engine::Get(engine);
634 if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
635 return e;
636 }
637 }
638
639 /* Check if there is an unreserved slot */
640 EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
641 if (engine != INVALID_ENGINE) {
642 Engine *e = Engine::Get(engine);
643
644 if (e->grf_prop.grffile == nullptr) {
645 e->grf_prop.grffile = file;
646 grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
647 }
648
649 /* Reserve the engine slot */
650 if (!static_access) {
651 EngineIDMapping *eid = _engine_mngr.data() + engine;
652 eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
653 }
654
655 return e;
656 }
657
658 if (static_access) return nullptr;
659
660 if (!Engine::CanAllocateItem()) {
661 grfmsg(0, "Can't allocate any more engines");
662 return nullptr;
663 }
664
665 size_t engine_pool_size = Engine::GetPoolSize();
666
667 /* ... it's not, so create a new one based off an existing engine */
668 Engine *e = new Engine(type, internal_id);
669 e->grf_prop.grffile = file;
670
671 /* Reserve the engine slot */
672 assert(_engine_mngr.size() == e->index);
673 _engine_mngr.push_back({
674 scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
675 internal_id,
676 type,
677 std::min<uint8>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
678 });
679
680 if (engine_pool_size != Engine::GetPoolSize()) {
681 /* Resize temporary engine data ... */
682 _gted = ReallocT(_gted, Engine::GetPoolSize());
683
684 /* and blank the new block. */
685 size_t len = (Engine::GetPoolSize() - engine_pool_size) * sizeof(*_gted);
686 memset(_gted + engine_pool_size, 0, len);
687 }
688 if (type == VEH_TRAIN) {
689 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
690 }
691
692 grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
693
694 return e;
695 }
696
707 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
708 {
709 uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
710 if (_settings_game.vehicle.dynamic_engines) {
711 scope_grfid = file->grfid;
712 uint32 override = _grf_id_overrides[file->grfid];
713 if (override != 0) scope_grfid = override;
714 }
715
716 return _engine_mngr.GetID(type, internal_id, scope_grfid);
717 }
718
723 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
724 {
725 if (HasBit(grf_sprite->pal, 14)) {
726 ClrBit(grf_sprite->pal, 14);
727 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
728 }
729
730 if (HasBit(grf_sprite->sprite, 14)) {
731 ClrBit(grf_sprite->sprite, 14);
732 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
733 }
734
735 if (HasBit(grf_sprite->sprite, 15)) {
736 ClrBit(grf_sprite->sprite, 15);
737 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
738 }
739 }
740
754 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)
755 {
756 grf_sprite->sprite = buf->ReadWord();
757 grf_sprite->pal = buf->ReadWord();
758 TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
759
760 MapSpriteMappingRecolour(grf_sprite);
761
762 bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
763 ClrBit(grf_sprite->pal, 15);
764 if (custom_sprite) {
765 /* Use sprite from Action 1 */
766 uint index = GB(grf_sprite->sprite, 0, 14);
767 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
768 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d", index);
769 grf_sprite->sprite = SPR_IMG_QUERY;
770 grf_sprite->pal = PAL_NONE;
771 } else {
772 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
773 if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
774 SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
775 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
776 }
777 } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
778 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
779 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
780 return flags;
781 }
782
783 if (flags & TLF_CUSTOM_PALETTE) {
784 /* Use palette from Action 1 */
785 uint index = GB(grf_sprite->pal, 0, 14);
786 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
787 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d for 'palette'", index);
788 grf_sprite->pal = PAL_NONE;
789 } else {
790 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
791 if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
792 SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
793 SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
794 }
795 } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
796 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
797 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
798 return flags;
799 }
800
801 return flags;
802 }
803
812 static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
813 {
814 if (!(flags & TLF_DRAWING_FLAGS)) return;
815
816 if (dts->registers == nullptr) dts->AllocateRegisters();
817 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
818 regs.flags = flags & TLF_DRAWING_FLAGS;
819
820 if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
821 if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
822 if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
823
824 if (is_parent) {
825 if (flags & TLF_BB_XY_OFFSET) {
826 regs.delta.parent[0] = buf->ReadByte();
827 regs.delta.parent[1] = buf->ReadByte();
828 }
829 if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
830 } else {
831 if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
832 if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
833 }
834
835 if (flags & TLF_SPRITE_VAR10) {
836 regs.sprite_var10 = buf->ReadByte();
837 if (regs.sprite_var10 > TLR_MAX_VAR10) {
838 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.sprite_var10, TLR_MAX_VAR10);
839 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
840 return;
841 }
842 }
843
844 if (flags & TLF_PALETTE_VAR10) {
845 regs.palette_var10 = buf->ReadByte();
846 if (regs.palette_var10 > TLR_MAX_VAR10) {
847 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.palette_var10, TLR_MAX_VAR10);
848 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
849 return;
850 }
851 }
852 }
853
865 static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
866 {
867 bool has_flags = HasBit(num_building_sprites, 6);
868 ClrBit(num_building_sprites, 6);
869 TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
870 if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
871 dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
872
873 uint16 *max_sprite_offset = AllocaM(uint16, num_building_sprites + 1);
874 uint16 *max_palette_offset = AllocaM(uint16, num_building_sprites + 1);
875 MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
876 MemSetT(max_palette_offset, 0, num_building_sprites + 1);
877
878 /* Groundsprite */
879 TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
880 if (_cur.skip_sprites < 0) return true;
881
882 if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
883 grfmsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x%x for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
884 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
885 return true;
886 }
887
888 ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
889 if (_cur.skip_sprites < 0) return true;
890
891 for (uint i = 0; i < num_building_sprites; i++) {
892 DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
893
894 flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
895 if (_cur.skip_sprites < 0) return true;
896
897 if (flags & ~valid_flags) {
898 grfmsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x%x", flags & ~valid_flags);
899 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
900 return true;
901 }
902
903 seq->delta_x = buf->ReadByte();
904 seq->delta_y = buf->ReadByte();
905
906 if (!no_z_position) seq->delta_z = buf->ReadByte();
907
908 if (seq->IsParentSprite()) {
909 seq->size_x = buf->ReadByte();
910 seq->size_y = buf->ReadByte();
911 seq->size_z = buf->ReadByte();
912 }
913
914 ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
915 if (_cur.skip_sprites < 0) return true;
916 }
917
918 /* Check if the number of sprites per spriteset is consistent */
919 bool is_consistent = true;
920 dts->consistent_max_offset = 0;
921 for (uint i = 0; i < num_building_sprites + 1; i++) {
922 if (max_sprite_offset[i] > 0) {
923 if (dts->consistent_max_offset == 0) {
924 dts->consistent_max_offset = max_sprite_offset[i];
925 } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
926 is_consistent = false;
927 break;
928 }
929 }
930 if (max_palette_offset[i] > 0) {
931 if (dts->consistent_max_offset == 0) {
932 dts->consistent_max_offset = max_palette_offset[i];
933 } else if (dts->consistent_max_offset != max_palette_offset[i]) {
934 is_consistent = false;
935 break;
936 }
937 }
938 }
939
940 /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
941 assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
942
943 if (!is_consistent || dts->registers != nullptr) {
944 dts->consistent_max_offset = 0;
945 if (dts->registers == nullptr) dts->AllocateRegisters();
946
947 for (uint i = 0; i < num_building_sprites + 1; i++) {
948 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
949 regs.max_sprite_offset = max_sprite_offset[i];
950 regs.max_palette_offset = max_palette_offset[i];
951 }
952 }
953
954 return false;
955 }
956
960 static CargoTypes TranslateRefitMask(uint32 refit_mask)
961 {
962 CargoTypes result = 0;
963 for (uint8 bit : SetBitIterator(refit_mask)) {
964 CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
965 if (cargo != CT_INVALID) SetBit(result, cargo);
966 }
967 return result;
968 }
969
977 static void ConvertTTDBasePrice(uint32 base_pointer, const char *error_location, Price *index)
978 {
979 /* Special value for 'none' */
980 if (base_pointer == 0) {
981 *index = INVALID_PRICE;
982 return;
983 }
984
985 static const uint32 start = 0x4B34;
986 static const uint32 size = 6;
987
988 if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
989 grfmsg(1, "%s: Unsupported running cost base 0x%04X, ignoring", error_location, base_pointer);
990 return;
991 }
992
993 *index = (Price)((base_pointer - start) / size);
994 }
995
997 enum ChangeInfoResult {
998 CIR_SUCCESS,
999 CIR_DISABLED,
1000 CIR_UNHANDLED,
1001 CIR_UNKNOWN,
1002 CIR_INVALID_ID,
1003 };
1004
1005 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader *buf);
1006
1014 static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
1015 {
1016 switch (prop) {
1017 case 0x00: // Introduction date
1018 ei->base_intro = buf->ReadWord() + DAYS_TILL_ORIGINAL_BASE_YEAR;
1019 break;
1020
1021 case 0x02: // Decay speed
1022 ei->decay_speed = buf->ReadByte();
1023 break;
1024
1025 case 0x03: // Vehicle life
1026 ei->lifelength = buf->ReadByte();
1027 break;
1028
1029 case 0x04: // Model life
1030 ei->base_life = buf->ReadByte();
1031 break;
1032
1033 case 0x06: // Climates available
1034 ei->climates = buf->ReadByte();
1035 break;
1036
1037 case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1038 /* Amount of cargo loaded during a vehicle's "loading tick" */
1039 ei->load_amount = buf->ReadByte();
1040 break;
1041
1042 default:
1043 return CIR_UNKNOWN;
1044 }
1045
1046 return CIR_SUCCESS;
1047 }
1048
1057 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1058 {
1059 ChangeInfoResult ret = CIR_SUCCESS;
1060
1061 for (int i = 0; i < numinfo; i++) {
1062 Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1063 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1064
1065 EngineInfo *ei = &e->info;
1066 RailVehicleInfo *rvi = &e->u.rail;
1067
1068 switch (prop) {
1069 case 0x05: { // Track type
1070 uint8 tracktype = buf->ReadByte();
1071
1072 if (tracktype < _cur.grffile->railtype_list.size()) {
1073 _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1074 break;
1075 }
1076
1077 switch (tracktype) {
1078 case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_ELECTRIC_LABEL : RAILTYPE_RAIL_LABEL; break;
1079 case 1: _gted[e->index].railtypelabel = RAILTYPE_MONO_LABEL; break;
1080 case 2: _gted[e->index].railtypelabel = RAILTYPE_MAGLEV_LABEL; break;
1081 default:
1082 grfmsg(1, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring", tracktype);
1083 break;
1084 }
1085 break;
1086 }
1087
1088 case 0x08: // AI passenger service
1089 /* Tells the AI that this engine is designed for
1090 * passenger services and shouldn't be used for freight. */
1091 rvi->ai_passenger_only = buf->ReadByte();
1092 break;
1093
1094 case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1095 uint16 speed = buf->ReadWord();
1096 if (speed == 0xFFFF) speed = 0;
1097
1098 rvi->max_speed = speed;
1099 break;
1100 }
1101
1102 case PROP_TRAIN_POWER: // 0x0B Power
1103 rvi->power = buf->ReadWord();
1104
1105 /* Set engine / wagon state based on power */
1106 if (rvi->power != 0) {
1107 if (rvi->railveh_type == RAILVEH_WAGON) {
1108 rvi->railveh_type = RAILVEH_SINGLEHEAD;
1109 }
1110 } else {
1111 rvi->railveh_type = RAILVEH_WAGON;
1112 }
1113 break;
1114
1115 case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1116 rvi->running_cost = buf->ReadByte();
1117 break;
1118
1119 case 0x0E: // Running cost base
1120 ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1121 break;
1122
1123 case 0x12: { // Sprite ID
1124 uint8 spriteid = buf->ReadByte();
1125 uint8 orig_spriteid = spriteid;
1126
1127 /* TTD sprite IDs point to a location in a 16bit array, but we use it
1128 * as an array index, so we need it to be half the original value. */
1129 if (spriteid < 0xFD) spriteid >>= 1;
1130
1131 if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1132 rvi->image_index = spriteid;
1133 } else {
1134 grfmsg(1, "RailVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1135 rvi->image_index = 0;
1136 }
1137 break;
1138 }
1139
1140 case 0x13: { // Dual-headed
1141 uint8 dual = buf->ReadByte();
1142
1143 if (dual != 0) {
1144 rvi->railveh_type = RAILVEH_MULTIHEAD;
1145 } else {
1146 rvi->railveh_type = rvi->power == 0 ?
1147 RAILVEH_WAGON : RAILVEH_SINGLEHEAD;
1148 }
1149 break;
1150 }
1151
1152 case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1153 rvi->capacity = buf->ReadByte();
1154 break;
1155
1156 case 0x15: { // Cargo type
1157 _gted[e->index].defaultcargo_grf = _cur.grffile;
1158 uint8 ctype = buf->ReadByte();
1159
1160 if (ctype == 0xFF) {
1161 /* 0xFF is specified as 'use first refittable' */
1162 ei->cargo_type = CT_INVALID;
1163 } else if (_cur.grffile->grf_version >= 8) {
1164 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1165 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1166 } else if (ctype < NUM_CARGO) {
1167 /* Use untranslated cargo. */
1168 ei->cargo_type = ctype;
1169 } else {
1170 ei->cargo_type = CT_INVALID;
1171 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1172 }
1173 break;
1174 }
1175
1176 case PROP_TRAIN_WEIGHT: // 0x16 Weight
1177 SB(rvi->weight, 0, 8, buf->ReadByte());
1178 break;
1179
1180 case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1181 rvi->cost_factor = buf->ReadByte();
1182 break;
1183
1184 case 0x18: // AI rank
1185 grfmsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1186 buf->ReadByte();
1187 break;
1188
1189 case 0x19: { // Engine traction type
1190 /* What do the individual numbers mean?
1191 * 0x00 .. 0x07: Steam
1192 * 0x08 .. 0x27: Diesel
1193 * 0x28 .. 0x31: Electric
1194 * 0x32 .. 0x37: Monorail
1195 * 0x38 .. 0x41: Maglev
1196 */
1197 uint8 traction = buf->ReadByte();
1198 EngineClass engclass;
1199
1200 if (traction <= 0x07) {
1201 engclass = EC_STEAM;
1202 } else if (traction <= 0x27) {
1203 engclass = EC_DIESEL;
1204 } else if (traction <= 0x31) {
1205 engclass = EC_ELECTRIC;
1206 } else if (traction <= 0x37) {
1207 engclass = EC_MONORAIL;
1208 } else if (traction <= 0x41) {
1209 engclass = EC_MAGLEV;
1210 } else {
1211 break;
1212 }
1213
1214 if (_cur.grffile->railtype_list.size() == 0) {
1215 /* Use traction type to select between normal and electrified
1216 * rail only when no translation list is in place. */
1217 if (_gted[e->index].railtypelabel == RAILTYPE_RAIL_LABEL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_ELECTRIC_LABEL;
1218 if (_gted[e->index].railtypelabel == RAILTYPE_ELECTRIC_LABEL && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_RAIL_LABEL;
1219 }
1220
1221 rvi->engclass = engclass;
1222 break;
1223 }
1224
1225 case 0x1A: // Alter purchase list sort order
1226 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1227 break;
1228
1229 case 0x1B: // Powered wagons power bonus
1230 rvi->pow_wag_power = buf->ReadWord();
1231 break;
1232
1233 case 0x1C: // Refit cost
1234 ei->refit_cost = buf->ReadByte();
1235 break;
1236
1237 case 0x1D: { // Refit cargo
1238 uint32 mask = buf->ReadDWord();
1239 _gted[e->index].UpdateRefittability(mask != 0);
1240 ei->refit_mask = TranslateRefitMask(mask);
1241 _gted[e->index].defaultcargo_grf = _cur.grffile;
1242 break;
1243 }
1244
1245 case 0x1E: // Callback
1246 ei->callback_mask = buf->ReadByte();
1247 break;
1248
1249 case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1250 rvi->tractive_effort = buf->ReadByte();
1251 break;
1252
1253 case 0x20: // Air drag
1254 rvi->air_drag = buf->ReadByte();
1255 break;
1256
1257 case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1258 rvi->shorten_factor = buf->ReadByte();
1259 break;
1260
1261 case 0x22: // Visual effect
1262 rvi->visual_effect = buf->ReadByte();
1263 /* Avoid accidentally setting visual_effect to the default value
1264 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1265 if (rvi->visual_effect == VE_DEFAULT) {
1266 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1267 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1268 }
1269 break;
1270
1271 case 0x23: // Powered wagons weight bonus
1272 rvi->pow_wag_weight = buf->ReadByte();
1273 break;
1274
1275 case 0x24: { // High byte of vehicle weight
1276 byte weight = buf->ReadByte();
1277
1278 if (weight > 4) {
1279 grfmsg(2, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring", weight << 8);
1280 } else {
1281 SB(rvi->weight, 8, 8, weight);
1282 }
1283 break;
1284 }
1285
1286 case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1287 rvi->user_def_data = buf->ReadByte();
1288 break;
1289
1290 case 0x26: // Retire vehicle early
1291 ei->retire_early = buf->ReadByte();
1292 break;
1293
1294 case 0x27: // Miscellaneous flags
1295 ei->misc_flags = buf->ReadByte();
1296 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1297 _gted[e->index].prop27_set = true;
1298 break;
1299
1300 case 0x28: // Cargo classes allowed
1301 _gted[e->index].cargo_allowed = buf->ReadWord();
1302 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1303 _gted[e->index].defaultcargo_grf = _cur.grffile;
1304 break;
1305
1306 case 0x29: // Cargo classes disallowed
1307 _gted[e->index].cargo_disallowed = buf->ReadWord();
1308 _gted[e->index].UpdateRefittability(false);
1309 break;
1310
1311 case 0x2A: // Long format introduction date (days since year 0)
1312 ei->base_intro = buf->ReadDWord();
1313 break;
1314
1315 case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1316 ei->cargo_age_period = buf->ReadWord();
1317 break;
1318
1319 case 0x2C: // CTT refit include list
1320 case 0x2D: { // CTT refit exclude list
1321 uint8 count = buf->ReadByte();
1322 _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1323 if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1324 CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1325 ctt = 0;
1326 while (count--) {
1327 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1328 if (ctype == CT_INVALID) continue;
1329 SetBit(ctt, ctype);
1330 }
1331 break;
1332 }
1333
1334 case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1335 rvi->curve_speed_mod = buf->ReadWord();
1336 break;
1337
1338 default:
1339 ret = CommonVehicleChangeInfo(ei, prop, buf);
1340 break;
1341 }
1342 }
1343
1344 return ret;
1345 }
1346
1355 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1356 {
1357 ChangeInfoResult ret = CIR_SUCCESS;
1358
1359 for (int i = 0; i < numinfo; i++) {
1360 Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1361 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1362
1363 EngineInfo *ei = &e->info;
1364 RoadVehicleInfo *rvi = &e->u.road;
1365
1366 switch (prop) {
1367 case 0x05: // Road/tram type
1368 /* RoadTypeLabel is looked up later after the engine's road/tram
1369 * flag is set, however 0 means the value has not been set. */
1370 _gted[e->index].roadtramtype = buf->ReadByte() + 1;
1371 break;
1372
1373 case 0x08: // Speed (1 unit is 0.5 kmh)
1374 rvi->max_speed = buf->ReadByte();
1375 break;
1376
1377 case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1378 rvi->running_cost = buf->ReadByte();
1379 break;
1380
1381 case 0x0A: // Running cost base
1382 ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1383 break;
1384
1385 case 0x0E: { // Sprite ID
1386 uint8 spriteid = buf->ReadByte();
1387 uint8 orig_spriteid = spriteid;
1388
1389 /* cars have different custom id in the GRF file */
1390 if (spriteid == 0xFF) spriteid = 0xFD;
1391
1392 if (spriteid < 0xFD) spriteid >>= 1;
1393
1394 if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1395 rvi->image_index = spriteid;
1396 } else {
1397 grfmsg(1, "RoadVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1398 rvi->image_index = 0;
1399 }
1400 break;
1401 }
1402
1403 case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1404 rvi->capacity = buf->ReadByte();
1405 break;
1406
1407 case 0x10: { // Cargo type
1408 _gted[e->index].defaultcargo_grf = _cur.grffile;
1409 uint8 ctype = buf->ReadByte();
1410
1411 if (ctype == 0xFF) {
1412 /* 0xFF is specified as 'use first refittable' */
1413 ei->cargo_type = CT_INVALID;
1414 } else if (_cur.grffile->grf_version >= 8) {
1415 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1416 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1417 } else if (ctype < NUM_CARGO) {
1418 /* Use untranslated cargo. */
1419 ei->cargo_type = ctype;
1420 } else {
1421 ei->cargo_type = CT_INVALID;
1422 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1423 }
1424 break;
1425 }
1426
1427 case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1428 rvi->cost_factor = buf->ReadByte();
1429 break;
1430
1431 case 0x12: // SFX
1432 rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1433 break;
1434
1435 case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1436 rvi->power = buf->ReadByte();
1437 break;
1438
1439 case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1440 rvi->weight = buf->ReadByte();
1441 break;
1442
1443 case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1444 _gted[e->index].rv_max_speed = buf->ReadByte();
1445 break;
1446
1447 case 0x16: { // Cargoes available for refitting
1448 uint32 mask = buf->ReadDWord();
1449 _gted[e->index].UpdateRefittability(mask != 0);
1450 ei->refit_mask = TranslateRefitMask(mask);
1451 _gted[e->index].defaultcargo_grf = _cur.grffile;
1452 break;
1453 }
1454
1455 case 0x17: // Callback mask
1456 ei->callback_mask = buf->ReadByte();
1457 break;
1458
1459 case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1460 rvi->tractive_effort = buf->ReadByte();
1461 break;
1462
1463 case 0x19: // Air drag
1464 rvi->air_drag = buf->ReadByte();
1465 break;
1466
1467 case 0x1A: // Refit cost
1468 ei->refit_cost = buf->ReadByte();
1469 break;
1470
1471 case 0x1B: // Retire vehicle early
1472 ei->retire_early = buf->ReadByte();
1473 break;
1474
1475 case 0x1C: // Miscellaneous flags
1476 ei->misc_flags = buf->ReadByte();
1477 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1478 break;
1479
1480 case 0x1D: // Cargo classes allowed
1481 _gted[e->index].cargo_allowed = buf->ReadWord();
1482 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1483 _gted[e->index].defaultcargo_grf = _cur.grffile;
1484 break;
1485
1486 case 0x1E: // Cargo classes disallowed
1487 _gted[e->index].cargo_disallowed = buf->ReadWord();
1488 _gted[e->index].UpdateRefittability(false);
1489 break;
1490
1491 case 0x1F: // Long format introduction date (days since year 0)
1492 ei->base_intro = buf->ReadDWord();
1493 break;
1494
1495 case 0x20: // Alter purchase list sort order
1496 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1497 break;
1498
1499 case 0x21: // Visual effect
1500 rvi->visual_effect = buf->ReadByte();
1501 /* Avoid accidentally setting visual_effect to the default value
1502 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1503 if (rvi->visual_effect == VE_DEFAULT) {
1504 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1505 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1506 }
1507 break;
1508
1509 case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1510 ei->cargo_age_period = buf->ReadWord();
1511 break;
1512
1513 case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1514 rvi->shorten_factor = buf->ReadByte();
1515 break;
1516
1517 case 0x24: // CTT refit include list
1518 case 0x25: { // CTT refit exclude list
1519 uint8 count = buf->ReadByte();
1520 _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1521 if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1522 CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1523 ctt = 0;
1524 while (count--) {
1525 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1526 if (ctype == CT_INVALID) continue;
1527 SetBit(ctt, ctype);
1528 }
1529 break;
1530 }
1531
1532 default:
1533 ret = CommonVehicleChangeInfo(ei, prop, buf);
1534 break;
1535 }
1536 }
1537
1538 return ret;
1539 }
1540
1549 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1550 {
1551 ChangeInfoResult ret = CIR_SUCCESS;
1552
1553 for (int i = 0; i < numinfo; i++) {
1554 Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1555 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1556
1557 EngineInfo *ei = &e->info;
1558 ShipVehicleInfo *svi = &e->u.ship;
1559
1560 switch (prop) {
1561 case 0x08: { // Sprite ID
1562 uint8 spriteid = buf->ReadByte();
1563 uint8 orig_spriteid = spriteid;
1564
1565 /* ships have different custom id in the GRF file */
1566 if (spriteid == 0xFF) spriteid = 0xFD;
1567
1568 if (spriteid < 0xFD) spriteid >>= 1;
1569
1570 if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1571 svi->image_index = spriteid;
1572 } else {
1573 grfmsg(1, "ShipVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1574 svi->image_index = 0;
1575 }
1576 break;
1577 }
1578
1579 case 0x09: // Refittable
1580 svi->old_refittable = (buf->ReadByte() != 0);
1581 break;
1582
1583 case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1584 svi->cost_factor = buf->ReadByte();
1585 break;
1586
1587 case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h)
1588 svi->max_speed = buf->ReadByte();
1589 break;
1590
1591 case 0x0C: { // Cargo type
1592 _gted[e->index].defaultcargo_grf = _cur.grffile;
1593 uint8 ctype = buf->ReadByte();
1594
1595 if (ctype == 0xFF) {
1596 /* 0xFF is specified as 'use first refittable' */
1597 ei->cargo_type = CT_INVALID;
1598 } else if (_cur.grffile->grf_version >= 8) {
1599 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1600 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1601 } else if (ctype < NUM_CARGO) {
1602 /* Use untranslated cargo. */
1603 ei->cargo_type = ctype;
1604 } else {
1605 ei->cargo_type = CT_INVALID;
1606 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1607 }
1608 break;
1609 }
1610
1611 case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1612 svi->capacity = buf->ReadWord();
1613 break;
1614
1615 case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1616 svi->running_cost = buf->ReadByte();
1617 break;
1618
1619 case 0x10: // SFX
1620 svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1621 break;
1622
1623 case 0x11: { // Cargoes available for refitting
1624 uint32 mask = buf->ReadDWord();
1625 _gted[e->index].UpdateRefittability(mask != 0);
1626 ei->refit_mask = TranslateRefitMask(mask);
1627 _gted[e->index].defaultcargo_grf = _cur.grffile;
1628 break;
1629 }
1630
1631 case 0x12: // Callback mask
1632 ei->callback_mask = buf->ReadByte();
1633 break;
1634
1635 case 0x13: // Refit cost
1636 ei->refit_cost = buf->ReadByte();
1637 break;
1638
1639 case 0x14: // Ocean speed fraction
1640 svi->ocean_speed_frac = buf->ReadByte();
1641 break;
1642
1643 case 0x15: // Canal speed fraction
1644 svi->canal_speed_frac = buf->ReadByte();
1645 break;
1646
1647 case 0x16: // Retire vehicle early
1648 ei->retire_early = buf->ReadByte();
1649 break;
1650
1651 case 0x17: // Miscellaneous flags
1652 ei->misc_flags = buf->ReadByte();
1653 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1654 break;
1655
1656 case 0x18: // Cargo classes allowed
1657 _gted[e->index].cargo_allowed = buf->ReadWord();
1658 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1659 _gted[e->index].defaultcargo_grf = _cur.grffile;
1660 break;
1661
1662 case 0x19: // Cargo classes disallowed
1663 _gted[e->index].cargo_disallowed = buf->ReadWord();
1664 _gted[e->index].UpdateRefittability(false);
1665 break;
1666
1667 case 0x1A: // Long format introduction date (days since year 0)
1668 ei->base_intro = buf->ReadDWord();
1669 break;
1670
1671 case 0x1B: // Alter purchase list sort order
1672 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1673 break;
1674
1675 case 0x1C: // Visual effect
1676 svi->visual_effect = buf->ReadByte();
1677 /* Avoid accidentally setting visual_effect to the default value
1678 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1679 if (svi->visual_effect == VE_DEFAULT) {
1680 assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1681 SB(svi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1682 }
1683 break;
1684
1685 case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1686 ei->cargo_age_period = buf->ReadWord();
1687 break;
1688
1689 case 0x1E: // CTT refit include list
1690 case 0x1F: { // CTT refit exclude list
1691 uint8 count = buf->ReadByte();
1692 _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1693 if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1694 CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1695 ctt = 0;
1696 while (count--) {
1697 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1698 if (ctype == CT_INVALID) continue;
1699 SetBit(ctt, ctype);
1700 }
1701 break;
1702 }
1703
1704 default:
1705 ret = CommonVehicleChangeInfo(ei, prop, buf);
1706 break;
1707 }
1708 }
1709
1710 return ret;
1711 }
1712
1721 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1722 {
1723 ChangeInfoResult ret = CIR_SUCCESS;
1724
1725 for (int i = 0; i < numinfo; i++) {
1726 Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1727 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1728
1729 EngineInfo *ei = &e->info;
1730 AircraftVehicleInfo *avi = &e->u.air;
1731
1732 switch (prop) {
1733 case 0x08: { // Sprite ID
1734 uint8 spriteid = buf->ReadByte();
1735 uint8 orig_spriteid = spriteid;
1736
1737 /* aircraft have different custom id in the GRF file */
1738 if (spriteid == 0xFF) spriteid = 0xFD;
1739
1740 if (spriteid < 0xFD) spriteid >>= 1;
1741
1742 if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1743 avi->image_index = spriteid;
1744 } else {
1745 grfmsg(1, "AircraftVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1746 avi->image_index = 0;
1747 }
1748 break;
1749 }
1750
1751 case 0x09: // Helicopter
1752 if (buf->ReadByte() == 0) {
1753 avi->subtype = AIR_HELI;
1754 } else {
1755 SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1756 }
1757 break;
1758
1759 case 0x0A: // Large
1760 SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1761 break;
1762
1763 case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1764 avi->cost_factor = buf->ReadByte();
1765 break;
1766
1767 case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1768 avi->max_speed = (buf->ReadByte() * 128) / 10;
1769 break;
1770
1771 case 0x0D: // Acceleration
1772 avi->acceleration = buf->ReadByte();
1773 break;
1774
1775 case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1776 avi->running_cost = buf->ReadByte();
1777 break;
1778
1779 case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1780 avi->passenger_capacity = buf->ReadWord();
1781 break;
1782
1783 case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1784 avi->mail_capacity = buf->ReadByte();
1785 break;
1786
1787 case 0x12: // SFX
1788 avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1789 break;
1790
1791 case 0x13: { // Cargoes available for refitting
1792 uint32 mask = buf->ReadDWord();
1793 _gted[e->index].UpdateRefittability(mask != 0);
1794 ei->refit_mask = TranslateRefitMask(mask);
1795 _gted[e->index].defaultcargo_grf = _cur.grffile;
1796 break;
1797 }
1798
1799 case 0x14: // Callback mask
1800 ei->callback_mask = buf->ReadByte();
1801 break;
1802
1803 case 0x15: // Refit cost
1804 ei->refit_cost = buf->ReadByte();
1805 break;
1806
1807 case 0x16: // Retire vehicle early
1808 ei->retire_early = buf->ReadByte();
1809 break;
1810
1811 case 0x17: // Miscellaneous flags
1812 ei->misc_flags = buf->ReadByte();
1813 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1814 break;
1815
1816 case 0x18: // Cargo classes allowed
1817 _gted[e->index].cargo_allowed = buf->ReadWord();
1818 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1819 _gted[e->index].defaultcargo_grf = _cur.grffile;
1820 break;
1821
1822 case 0x19: // Cargo classes disallowed
1823 _gted[e->index].cargo_disallowed = buf->ReadWord();
1824 _gted[e->index].UpdateRefittability(false);
1825 break;
1826
1827 case 0x1A: // Long format introduction date (days since year 0)
1828 ei->base_intro = buf->ReadDWord();
1829 break;
1830
1831 case 0x1B: // Alter purchase list sort order
1832 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1833 break;
1834
1835 case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1836 ei->cargo_age_period = buf->ReadWord();
1837 break;
1838
1839 case 0x1D: // CTT refit include list
1840 case 0x1E: { // CTT refit exclude list
1841 uint8 count = buf->ReadByte();
1842 _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1843 if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1844 CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1845 ctt = 0;
1846 while (count--) {
1847 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1848 if (ctype == CT_INVALID) continue;
1849 SetBit(ctt, ctype);
1850 }
1851 break;
1852 }
1853
1854 case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1855 avi->max_range = buf->ReadWord();
1856 break;
1857
1858 default:
1859 ret = CommonVehicleChangeInfo(ei, prop, buf);
1860 break;
1861 }
1862 }
1863
1864 return ret;
1865 }
1866
1875 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
1876 {
1877 ChangeInfoResult ret = CIR_SUCCESS;
1878
1879 if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1880 grfmsg(1, "StationChangeInfo: Station %u is invalid, max %u, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1881 return CIR_INVALID_ID;
1882 }
1883
1884 /* Allocate station specs if necessary */
1885 if (_cur.grffile->stations == nullptr) _cur.grffile->stations = CallocT<StationSpec*>(NUM_STATIONS_PER_GRF);
1886
1887 for (int i = 0; i < numinfo; i++) {
1888 StationSpec *statspec = _cur.grffile->stations[stid + i];
1889
1890 /* Check that the station we are modifying is defined. */
1891 if (statspec == nullptr && prop != 0x08) {
1892 grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
1893 return CIR_INVALID_ID;
1894 }
1895
1896 switch (prop) {
1897 case 0x08: { // Class ID
1898 StationSpec **spec = &_cur.grffile->stations[stid + i];
1899
1900 /* Property 0x08 is special; it is where the station is allocated */
1901 if (*spec == nullptr) *spec = new StationSpec();
1902
1903 /* Swap classid because we read it in BE meaning WAYP or DFLT */
1904 uint32 classid = buf->ReadDWord();
1905 (*spec)->cls_id = StationClass::Allocate(BSWAP32(classid));
1906 break;
1907 }
1908
1909 case 0x09: { // Define sprite layout
1910 uint16 tiles = buf->ReadExtendedByte();
1911 statspec->renderdata.clear(); // delete earlier loaded stuff
1912 statspec->renderdata.reserve(tiles);
1913
1914 for (uint t = 0; t < tiles; t++) {
1915 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1916 dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1917
1918 if (buf->HasData(4) && *(uint32*)buf->Data() == 0) {
1919 buf->Skip(4);
1920 extern const DrawTileSprites _station_display_datas_rail[8];
1921 dts->Clone(&_station_display_datas_rail[t % 8]);
1922 continue;
1923 }
1924
1925 ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1926 /* On error, bail out immediately. Temporary GRF data was already freed */
1927 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1928
1929 static std::vector<DrawTileSeqStruct> tmp_layout;
1930 tmp_layout.clear();
1931 for (;;) {
1932 /* no relative bounding box support */
1933 DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1934 MemSetT(&dtss, 0);
1935
1936 dtss.delta_x = buf->ReadByte();
1937 if (dtss.IsTerminator()) break;
1938 dtss.delta_y = buf->ReadByte();
1939 dtss.delta_z = buf->ReadByte();
1940 dtss.size_x = buf->ReadByte();
1941 dtss.size_y = buf->ReadByte();
1942 dtss.size_z = buf->ReadByte();
1943
1944 ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1945 /* On error, bail out immediately. Temporary GRF data was already freed */
1946 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1947 }
1948 dts->Clone(tmp_layout.data());
1949 }
1950 break;
1951 }
1952
1953 case 0x0A: { // Copy sprite layout
1954 byte srcid = buf->ReadByte();
1955 const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
1956
1957 if (srcstatspec == nullptr) {
1958 grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy sprite layout to %u.", srcid, stid + i);
1959 continue;
1960 }
1961
1962 statspec->renderdata.clear(); // delete earlier loaded stuff
1963 statspec->renderdata.reserve(srcstatspec->renderdata.size());
1964
1965 for (const auto &it : srcstatspec->renderdata) {
1966 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1967 dts->Clone(&it);
1968 }
1969 break;
1970 }
1971
1972 case 0x0B: // Callback mask
1973 statspec->callback_mask = buf->ReadByte();
1974 break;
1975
1976 case 0x0C: // Disallowed number of platforms
1977 statspec->disallowed_platforms = buf->ReadByte();
1978 break;
1979
1980 case 0x0D: // Disallowed platform lengths
1981 statspec->disallowed_lengths = buf->ReadByte();
1982 break;
1983
1984 case 0x0E: // Define custom layout
1985 while (buf->HasData()) {
1986 byte length = buf->ReadByte();
1987 byte number = buf->ReadByte();
1988
1989 if (length == 0 || number == 0) break;
1990
1991 if (statspec->layouts.size() < length) statspec->layouts.resize(length);
1992 if (statspec->layouts[length - 1].size() < number) statspec->layouts[length - 1].resize(number);
1993
1994 const byte *layout = buf->ReadBytes(length * number);
1995 statspec->layouts[length - 1][number - 1].assign(layout, layout + length * number);
1996
1997 /* Validate tile values are only the permitted 00, 02, 04 and 06. */
1998 for (auto &tile : statspec->layouts[length - 1][number - 1]) {
1999 if ((tile & 6) != tile) {
2000 grfmsg(1, "StationChangeInfo: Invalid tile %u in layout %ux%u", tile, length, number);
2001 tile &= 6;
2002 }
2003 }
2004 }
2005 break;
2006
2007 case 0x0F: { // Copy custom layout
2008 byte srcid = buf->ReadByte();
2009 const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
2010
2011 if (srcstatspec == nullptr) {
2012 grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy tile layout to %u.", srcid, stid + i);
2013 continue;
2014 }
2015
2016 statspec->layouts = srcstatspec->layouts;
2017 break;
2018 }
2019
2020 case 0x10: // Little/lots cargo threshold
2021 statspec->cargo_threshold = buf->ReadWord();
2022 break;
2023
2024 case 0x11: // Pylon placement
2025 statspec->pylons = buf->ReadByte();
2026 break;
2027
2028 case 0x12: // Cargo types for random triggers
2029 if (_cur.grffile->grf_version >= 7) {
2030 statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
2031 } else {
2032 statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
2033 }
2034 break;
2035
2036 case 0x13: // General flags
2037 statspec->flags = buf->ReadByte();
2038 break;
2039
2040 case 0x14: // Overhead wire placement
2041 statspec->wires = buf->ReadByte();
2042 break;
2043
2044 case 0x15: // Blocked tiles
2045 statspec->blocked = buf->ReadByte();
2046 break;
2047
2048 case 0x16: // Animation info
2049 statspec->animation.frames = buf->ReadByte();
2050 statspec->animation.status = buf->ReadByte();
2051 break;
2052
2053 case 0x17: // Animation speed
2054 statspec->animation.speed = buf->ReadByte();
2055 break;
2056
2057 case 0x18: // Animation triggers
2058 statspec->animation.triggers = buf->ReadWord();
2059 break;
2060
2061 case 0x1A: { // Advanced sprite layout
2062 uint16 tiles = buf->ReadExtendedByte();
2063 statspec->renderdata.clear(); // delete earlier loaded stuff
2064 statspec->renderdata.reserve(tiles);
2065
2066 for (uint t = 0; t < tiles; t++) {
2067 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2068 uint num_building_sprites = buf->ReadByte();
2069 /* On error, bail out immediately. Temporary GRF data was already freed */
2070 if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2071 }
2072 break;
2073 }
2074
2075 default:
2076 ret = CIR_UNKNOWN;
2077 break;
2078 }
2079 }
2080
2081 return ret;
2082 }
2083
2092 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
2093 {
2094 ChangeInfoResult ret = CIR_SUCCESS;
2095
2096 if (id + numinfo > CF_END) {
2097 grfmsg(1, "CanalChangeInfo: Canal feature 0x%02X is invalid, max %u, ignoring", id + numinfo, CF_END);
2098 return CIR_INVALID_ID;
2099 }
2100
2101 for (int i = 0; i < numinfo; i++) {
2102 CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2103
2104 switch (prop) {
2105 case 0x08:
2106 cp->callback_mask = buf->ReadByte();
2107 break;
2108
2109 case 0x09:
2110 cp->flags = buf->ReadByte();
2111 break;
2112
2113 default:
2114 ret = CIR_UNKNOWN;
2115 break;
2116 }
2117 }
2118
2119 return ret;
2120 }
2121
2130 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
2131 {
2132 ChangeInfoResult ret = CIR_SUCCESS;
2133
2134 if (brid + numinfo > MAX_BRIDGES) {
2135 grfmsg(1, "BridgeChangeInfo: Bridge %u is invalid, max %u, ignoring", brid + numinfo, MAX_BRIDGES);
2136 return CIR_INVALID_ID;
2137 }
2138
2139 for (int i = 0; i < numinfo; i++) {
2140 BridgeSpec *bridge = &_bridge[brid + i];
2141
2142 switch (prop) {
2143 case 0x08: { // Year of availability
2144 /* We treat '0' as always available */
2145 byte year = buf->ReadByte();
2146 bridge->avail_year = (year > 0 ? ORIGINAL_BASE_YEAR + year : 0);
2147 break;
2148 }
2149
2150 case 0x09: // Minimum length
2151 bridge->min_length = buf->ReadByte();
2152 break;
2153
2154 case 0x0A: // Maximum length
2155 bridge->max_length = buf->ReadByte();
2156 if (bridge->max_length > 16) bridge->max_length = 0xFFFF;
2157 break;
2158
2159 case 0x0B: // Cost factor
2160 bridge->price = buf->ReadByte();
2161 break;
2162
2163 case 0x0C: // Maximum speed
2164 bridge->speed = buf->ReadWord();
2165 break;
2166
2167 case 0x0D: { // Bridge sprite tables
2168 byte tableid = buf->ReadByte();
2169 byte numtables = buf->ReadByte();
2170
2171 if (bridge->sprite_table == nullptr) {
2172 /* Allocate memory for sprite table pointers and zero out */
2173 bridge->sprite_table = CallocT<PalSpriteID*>(7);
2174 }
2175
2176 for (; numtables-- != 0; tableid++) {
2177 if (tableid >= 7) { // skip invalid data
2178 grfmsg(1, "BridgeChangeInfo: Table %d >= 7, skipping", tableid);
2179 for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
2180 continue;
2181 }
2182
2183 if (bridge->sprite_table[tableid] == nullptr) {
2184 bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2185 }
2186
2187 for (byte sprite = 0; sprite < 32; sprite++) {
2188 SpriteID image = buf->ReadWord();
2189 PaletteID pal = buf->ReadWord();
2190
2191 bridge->sprite_table[tableid][sprite].sprite = image;
2192 bridge->sprite_table[tableid][sprite].pal = pal;
2193
2194 MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2195 }
2196 }
2197 break;
2198 }
2199
2200 case 0x0E: // Flags; bit 0 - disable far pillars
2201 bridge->flags = buf->ReadByte();
2202 break;
2203
2204 case 0x0F: // Long format year of availability (year since year 0)
2205 bridge->avail_year = Clamp(buf->ReadDWord(), MIN_YEAR, MAX_YEAR);
2206 break;
2207
2208 case 0x10: { // purchase string
2209 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2210 if (newone != STR_UNDEFINED) bridge->material = newone;
2211 break;
2212 }
2213
2214 case 0x11: // description of bridge with rails or roads
2215 case 0x12: {
2216 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2217 if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2218 break;
2219 }
2220
2221 case 0x13: // 16 bits cost multiplier
2222 bridge->price = buf->ReadWord();
2223 break;
2224
2225 default:
2226 ret = CIR_UNKNOWN;
2227 break;
2228 }
2229 }
2230
2231 return ret;
2232 }
2233
2240 static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
2241 {
2242 ChangeInfoResult ret = CIR_SUCCESS;
2243
2244 switch (prop) {
2245 case 0x09:
2246 case 0x0B:
2247 case 0x0C:
2248 case 0x0D:
2249 case 0x0E:
2250 case 0x0F:
2251 case 0x11:
2252 case 0x14:
2253 case 0x15:
2254 case 0x16:
2255 case 0x18:
2256 case 0x19:
2257 case 0x1A:
2258 case 0x1B:
2259 case 0x1C:
2260 case 0x1D:
2261 case 0x1F:
2262 buf->ReadByte();
2263 break;
2264
2265 case 0x0A:
2266 case 0x10:
2267 case 0x12:
2268 case 0x13:
2269 case 0x21:
2270 case 0x22:
2271 buf->ReadWord();
2272 break;
2273
2274 case 0x1E:
2275 buf->ReadDWord();
2276 break;
2277
2278 case 0x17:
2279 for (uint j = 0; j < 4; j++) buf->ReadByte();
2280 break;
2281
2282 case 0x20: {
2283 byte count = buf->ReadByte();
2284 for (byte j = 0; j < count; j++) buf->ReadByte();
2285 break;
2286 }
2287
2288 case 0x23:
2289 buf->Skip(buf->ReadByte() * 2);
2290 break;
2291
2292 default:
2293 ret = CIR_UNKNOWN;
2294 break;
2295 }
2296 return ret;
2297 }
2298
2307 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
2308 {
2309 ChangeInfoResult ret = CIR_SUCCESS;
2310
2311 if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2312 grfmsg(1, "TownHouseChangeInfo: Too many houses loaded (%u), max (%u). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2313 return CIR_INVALID_ID;
2314 }
2315
2316 /* Allocate house specs if they haven't been allocated already. */
2317 if (_cur.grffile->housespec == nullptr) {
2318 _cur.grffile->housespec = CallocT<HouseSpec*>(NUM_HOUSES_PER_GRF);
2319 }
2320
2321 for (int i = 0; i < numinfo; i++) {
2322 HouseSpec *housespec = _cur.grffile->housespec[hid + i];
2323
2324 if (prop != 0x08 && housespec == nullptr) {
2325 /* If the house property 08 is not yet set, ignore this property */
2326 ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2327 if (cir > ret) ret = cir;
2328 continue;
2329 }
2330
2331 switch (prop) {
2332 case 0x08: { // Substitute building type, and definition of a new house
2333 HouseSpec **house = &_cur.grffile->housespec[hid + i];
2334 byte subs_id = buf->ReadByte();
2335
2336 if (subs_id == 0xFF) {
2337 /* Instead of defining a new house, a substitute house id
2338 * of 0xFF disables the old house with the current id. */
2339 HouseSpec::Get(hid + i)->enabled = false;
2340 continue;
2341 } else if (subs_id >= NEW_HOUSE_OFFSET) {
2342 /* The substitute id must be one of the original houses. */
2343 grfmsg(2, "TownHouseChangeInfo: Attempt to use new house %u as substitute house for %u. Ignoring.", subs_id, hid + i);
2344 continue;
2345 }
2346
2347 /* Allocate space for this house. */
2348 if (*house == nullptr) *house = CallocT<HouseSpec>(1);
2349
2350 housespec = *house;
2351
2352 MemCpyT(housespec, HouseSpec::Get(subs_id));
2353
2354 housespec->enabled = true;
2355 housespec->grf_prop.local_id = hid + i;
2356 housespec->grf_prop.subst_id = subs_id;
2357 housespec->grf_prop.grffile = _cur.grffile;
2358 housespec->random_colour[0] = 0x04; // those 4 random colours are the base colour
2359 housespec->random_colour[1] = 0x08; // for all new houses
2360 housespec->random_colour[2] = 0x0C; // they stand for red, blue, orange and green
2361 housespec->random_colour[3] = 0x06;
2362
2363 /* Make sure that the third cargo type is valid in this
2364 * climate. This can cause problems when copying the properties
2365 * of a house that accepts food, where the new house is valid
2366 * in the temperate climate. */
2367 if (!CargoSpec::Get(housespec->accepts_cargo[2])->IsValid()) {
2368 housespec->cargo_acceptance[2] = 0;
2369 }
2370 break;
2371 }
2372
2373 case 0x09: // Building flags
2374 housespec->building_flags = (BuildingFlags)buf->ReadByte();
2375 break;
2376
2377 case 0x0A: { // Availability years
2378 uint16 years = buf->ReadWord();
2379 housespec->min_year = GB(years, 0, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2380 housespec->max_year = GB(years, 8, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2381 break;
2382 }
2383
2384 case 0x0B: // Population
2385 housespec->population = buf->ReadByte();
2386 break;
2387
2388 case 0x0C: // Mail generation multiplier
2389 housespec->mail_generation = buf->ReadByte();
2390 break;
2391
2392 case 0x0D: // Passenger acceptance
2393 case 0x0E: // Mail acceptance
2394 housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
2395 break;
2396
2397 case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2398 int8 goods = buf->ReadByte();
2399
2400 /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2401 * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2402 CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_CANDY : CT_GOODS) :
2403 ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_FIZZY_DRINKS : CT_FOOD);
2404
2405 /* Make sure the cargo type is valid in this climate. */
2406 if (!CargoSpec::Get(cid)->IsValid()) goods = 0;
2407
2408 housespec->accepts_cargo[2] = cid;
2409 housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2410 break;
2411 }
2412
2413 case 0x10: // Local authority rating decrease on removal
2414 housespec->remove_rating_decrease = buf->ReadWord();
2415 break;
2416
2417 case 0x11: // Removal cost multiplier
2418 housespec->removal_cost = buf->ReadByte();
2419 break;
2420
2421 case 0x12: // Building name ID
2422 AddStringForMapping(buf->ReadWord(), &housespec->building_name);
2423 break;
2424
2425 case 0x13: // Building availability mask
2426 housespec->building_availability = (HouseZones)buf->ReadWord();
2427 break;
2428
2429 case 0x14: // House callback mask
2430 housespec->callback_mask |= buf->ReadByte();
2431 break;
2432
2433 case 0x15: { // House override byte
2434 byte override = buf->ReadByte();
2435
2436 /* The house being overridden must be an original house. */
2437 if (override >= NEW_HOUSE_OFFSET) {
2438 grfmsg(2, "TownHouseChangeInfo: Attempt to override new house %u with house id %u. Ignoring.", override, hid + i);
2439 continue;
2440 }
2441
2442 _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2443 break;
2444 }
2445
2446 case 0x16: // Periodic refresh multiplier
2447 housespec->processing_time = std::min<byte>(buf->ReadByte(), 63u);
2448 break;
2449
2450 case 0x17: // Four random colours to use
2451 for (uint j = 0; j < 4; j++) housespec->random_colour[j] = buf->ReadByte();
2452 break;
2453
2454 case 0x18: // Relative probability of appearing
2455 housespec->probability = buf->ReadByte();
2456 break;
2457
2458 case 0x19: // Extra flags
2459 housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
2460 break;
2461
2462 case 0x1A: // Animation frames
2463 housespec->animation.frames = buf->ReadByte();
2464 housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2465 SB(housespec->animation.frames, 7, 1, 0);
2466 break;
2467
2468 case 0x1B: // Animation speed
2469 housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
2470 break;
2471
2472 case 0x1C: // Class of the building type
2473 housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
2474 break;
2475
2476 case 0x1D: // Callback mask part 2
2477 housespec->callback_mask |= (buf->ReadByte() << 8);
2478 break;
2479
2480 case 0x1E: { // Accepted cargo types
2481 uint32 cargotypes = buf->ReadDWord();
2482
2483 /* Check if the cargo types should not be changed */
2484 if (cargotypes == 0xFFFFFFFF) break;
2485
2486 for (uint j = 0; j < 3; j++) {
2487 /* Get the cargo number from the 'list' */
2488 uint8 cargo_part = GB(cargotypes, 8 * j, 8);
2489 CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2490
2491 if (cargo == CT_INVALID) {
2492 /* Disable acceptance of invalid cargo type */
2493 housespec->cargo_acceptance[j] = 0;
2494 } else {
2495 housespec->accepts_cargo[j] = cargo;
2496 }
2497 }
2498 break;
2499 }
2500
2501 case 0x1F: // Minimum life span
2502 housespec->minimum_life = buf->ReadByte();
2503 break;
2504
2505 case 0x20: { // Cargo acceptance watch list
2506 byte count = buf->ReadByte();
2507 for (byte j = 0; j < count; j++) {
2508 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2509 if (cargo != CT_INVALID) SetBit(housespec->watched_cargoes, cargo);
2510 }
2511 break;
2512 }
2513
2514 case 0x21: // long introduction year
2515 housespec->min_year = buf->ReadWord();
2516 break;
2517
2518 case 0x22: // long maximum year
2519 housespec->max_year = buf->ReadWord();
2520 break;
2521
2522 case 0x23: { // variable length cargo types accepted
2523 uint count = buf->ReadByte();
2524 if (count > lengthof(housespec->accepts_cargo)) {
2525 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2526 error->param_value[1] = prop;
2527 return CIR_DISABLED;
2528 }
2529 /* Always write the full accepts_cargo array, and check each index for being inside the
2530 * provided data. This ensures all values are properly initialized, and also avoids
2531 * any risks of array overrun. */
2532 for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2533 if (i < count) {
2534 housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2535 housespec->cargo_acceptance[i] = buf->ReadByte();
2536 } else {
2537 housespec->accepts_cargo[i] = CT_INVALID;
2538 housespec->cargo_acceptance[i] = 0;
2539 }
2540 }
2541 break;
2542 }
2543
2544 default:
2545 ret = CIR_UNKNOWN;
2546 break;
2547 }
2548 }
2549
2550 return ret;
2551 }
2552
2559 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32 grfid, uint8 language_id)
2560 {
2561 /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2562 const GRFFile *grffile = GetFileByGRFID(grfid);
2563 return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
2564 }
2565
2575 template <typename T>
2576 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
2577 {
2578 if (gvid != 0) {
2579 grfmsg(1, "LoadTranslationTable: %s translation table must start at zero", name);
2580 return CIR_INVALID_ID;
2581 }
2582
2583 translation_table.clear();
2584 for (int i = 0; i < numinfo; i++) {
2585 uint32 item = buf->ReadDWord();
2586 translation_table.push_back(BSWAP32(item));
2587 }
2588
2589 return CIR_SUCCESS;
2590 }
2591
2598 static std::string ReadDWordAsString(ByteReader *reader)
2599 {
2600 char output[5];
2601 for (int i = 0; i < 4; i++) output[i] = reader->ReadByte();
2602 output[4] = '\0';
2603 StrMakeValidInPlace(output, lastof(output));
2604
2605 return std::string(output);
2606 }
2607
2616 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2617 {
2618 /* Properties which are handled as a whole */
2619 switch (prop) {
2620 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2621 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2622
2623 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2624 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2625
2626 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2627 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2628
2629 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2630 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2631
2632 default:
2633 break;
2634 }
2635
2636 /* Properties which are handled per item */
2637 ChangeInfoResult ret = CIR_SUCCESS;
2638 for (int i = 0; i < numinfo; i++) {
2639 switch (prop) {
2640 case 0x08: { // Cost base factor
2641 int factor = buf->ReadByte();
2642 uint price = gvid + i;
2643
2644 if (price < PR_END) {
2645 _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2646 } else {
2647 grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
2648 }
2649 break;
2650 }
2651
2652 case 0x0A: { // Currency display names
2653 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2654 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2655
2656 if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2657 _currency_specs[curidx].name = newone;
2658 }
2659 break;
2660 }
2661
2662 case 0x0B: { // Currency multipliers
2663 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2664 uint32 rate = buf->ReadDWord();
2665
2666 if (curidx < CURRENCY_END) {
2667 /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2668 * which OTTD does not. For this reason, divide grf value by 1000,
2669 * to be compatible */
2670 _currency_specs[curidx].rate = rate / 1000;
2671 } else {
2672 grfmsg(1, "GlobalVarChangeInfo: Currency multipliers %d out of range, ignoring", curidx);
2673 }
2674 break;
2675 }
2676
2677 case 0x0C: { // Currency options
2678 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2679 uint16 options = buf->ReadWord();
2680
2681 if (curidx < CURRENCY_END) {
2682 _currency_specs[curidx].separator.clear();
2683 _currency_specs[curidx].separator.push_back(GB(options, 0, 8));
2684 /* By specifying only one bit, we prevent errors,
2685 * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2686 _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2687 } else {
2688 grfmsg(1, "GlobalVarChangeInfo: Currency option %d out of range, ignoring", curidx);
2689 }
2690 break;
2691 }
2692
2693 case 0x0D: { // Currency prefix symbol
2694 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2695 std::string prefix = ReadDWordAsString(buf);
2696
2697 if (curidx < CURRENCY_END) {
2698 _currency_specs[curidx].prefix = prefix;
2699 } else {
2700 grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2701 }
2702 break;
2703 }
2704
2705 case 0x0E: { // Currency suffix symbol
2706 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2707 std::string suffix = ReadDWordAsString(buf);
2708
2709 if (curidx < CURRENCY_END) {
2710 _currency_specs[curidx].suffix = suffix;
2711 } else {
2712 grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2713 }
2714 break;
2715 }
2716
2717 case 0x0F: { // Euro introduction dates
2718 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2719 Year year_euro = buf->ReadWord();
2720
2721 if (curidx < CURRENCY_END) {
2722 _currency_specs[curidx].to_euro = year_euro;
2723 } else {
2724 grfmsg(1, "GlobalVarChangeInfo: Euro intro date %d out of range, ignoring", curidx);
2725 }
2726 break;
2727 }
2728
2729 case 0x10: // Snow line height table
2730 if (numinfo > 1 || IsSnowLineSet()) {
2731 grfmsg(1, "GlobalVarChangeInfo: The snowline can only be set once (%d)", numinfo);
2732 } else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2733 grfmsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table (" PRINTF_SIZE ")", buf->Remaining());
2734 } else {
2735 byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2736
2737 for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2738 for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2739 table[i][j] = buf->ReadByte();
2740 if (_cur.grffile->grf_version >= 8) {
2741 if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2742 } else {
2743 if (table[i][j] >= 128) {
2744 /* no snow */
2745 table[i][j] = 0xFF;
2746 } else {
2747 table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2748 }
2749 }
2750 }
2751 }
2752 SetSnowLine(table);
2753 }
2754 break;
2755
2756 case 0x11: // GRF match for engine allocation
2757 /* This is loaded during the reservation stage, so just skip it here. */
2758 /* Each entry is 8 bytes. */
2759 buf->Skip(8);
2760 break;
2761
2762 case 0x13: // Gender translation table
2763 case 0x14: // Case translation table
2764 case 0x15: { // Plural form translation
2765 uint curidx = gvid + i; // The current index, i.e. language.
2766 const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2767 if (lang == nullptr) {
2768 grfmsg(1, "GlobalVarChangeInfo: Language %d is not known, ignoring", curidx);
2769 /* Skip over the data. */
2770 if (prop == 0x15) {
2771 buf->ReadByte();
2772 } else {
2773 while (buf->ReadByte() != 0) {
2774 buf->ReadString();
2775 }
2776 }
2777 break;
2778 }
2779
2780 if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
2781
2782 if (prop == 0x15) {
2783 uint plural_form = buf->ReadByte();
2784 if (plural_form >= LANGUAGE_MAX_PLURAL) {
2785 grfmsg(1, "GlobalVarChanceInfo: Plural form %d is out of range, ignoring", plural_form);
2786 } else {
2787 _cur.grffile->language_map[curidx].plural_form = plural_form;
2788 }
2789 break;
2790 }
2791
2792 byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
2793 while (newgrf_id != 0) {
2794 const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
2795
2796 /* We'll just ignore the UTF8 identifier character. This is (fairly)
2797 * safe as OpenTTD's strings gender/cases are usually in ASCII which
2798 * is just a subset of UTF8, or they need the bigger UTF8 characters
2799 * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2800 WChar c;
2801 size_t len = Utf8Decode(&c, name);
2802 if (c == NFO_UTF8_IDENTIFIER) name += len;
2803
2804 LanguageMap::Mapping map;
2805 map.newgrf_id = newgrf_id;
2806 if (prop == 0x13) {
2807 map.openttd_id = lang->GetGenderIndex(name);
2808 if (map.openttd_id >= MAX_NUM_GENDERS) {
2809 grfmsg(1, "GlobalVarChangeInfo: Gender name %s is not known, ignoring", name);
2810 } else {
2811 _cur.grffile->language_map[curidx].gender_map.push_back(map);
2812 }
2813 } else {
2814 map.openttd_id = lang->GetCaseIndex(name);
2815 if (map.openttd_id >= MAX_NUM_CASES) {
2816 grfmsg(1, "GlobalVarChangeInfo: Case name %s is not known, ignoring", name);
2817 } else {
2818 _cur.grffile->language_map[curidx].case_map.push_back(map);
2819 }
2820 }
2821 newgrf_id = buf->ReadByte();
2822 }
2823 break;
2824 }
2825
2826 default:
2827 ret = CIR_UNKNOWN;
2828 break;
2829 }
2830 }
2831
2832 return ret;
2833 }
2834
2835 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2836 {
2837 /* Properties which are handled as a whole */
2838 switch (prop) {
2839 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2840 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2841
2842 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2843 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2844
2845 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2846 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2847
2848 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2849 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2850
2851 default:
2852 break;
2853 }
2854
2855 /* Properties which are handled per item */
2856 ChangeInfoResult ret = CIR_SUCCESS;
2857 for (int i = 0; i < numinfo; i++) {
2858 switch (prop) {
2859 case 0x08: // Cost base factor
2860 case 0x15: // Plural form translation
2861 buf->ReadByte();
2862 break;
2863
2864 case 0x0A: // Currency display names
2865 case 0x0C: // Currency options
2866 case 0x0F: // Euro introduction dates
2867 buf->ReadWord();
2868 break;
2869
2870 case 0x0B: // Currency multipliers
2871 case 0x0D: // Currency prefix symbol
2872 case 0x0E: // Currency suffix symbol
2873 buf->ReadDWord();
2874 break;
2875
2876 case 0x10: // Snow line height table
2877 buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2878 break;
2879
2880 case 0x11: { // GRF match for engine allocation
2881 uint32 s = buf->ReadDWord();
2882 uint32 t = buf->ReadDWord();
2883 SetNewGRFOverride(s, t);
2884 break;
2885 }
2886
2887 case 0x13: // Gender translation table
2888 case 0x14: // Case translation table
2889 while (buf->ReadByte() != 0) {
2890 buf->ReadString();
2891 }
2892 break;
2893
2894 default:
2895 ret = CIR_UNKNOWN;
2896 break;
2897 }
2898 }
2899
2900 return ret;
2901 }
2902
2903
2912 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
2913 {
2914 ChangeInfoResult ret = CIR_SUCCESS;
2915
2916 if (cid + numinfo > NUM_CARGO) {
2917 grfmsg(2, "CargoChangeInfo: Cargo type %d out of range (max %d)", cid + numinfo, NUM_CARGO - 1);
2918 return CIR_INVALID_ID;
2919 }
2920
2921 for (int i = 0; i < numinfo; i++) {
2922 CargoSpec *cs = CargoSpec::Get(cid + i);
2923
2924 switch (prop) {
2925 case 0x08: // Bit number of cargo
2926 cs->bitnum = buf->ReadByte();
2927 if (cs->IsValid()) {
2928 cs->grffile = _cur.grffile;
2929 SetBit(_cargo_mask, cid + i);
2930 } else {
2931 ClrBit(_cargo_mask, cid + i);
2932 }
2933 break;
2934
2935 case 0x09: // String ID for cargo type name
2936 AddStringForMapping(buf->ReadWord(), &cs->name);
2937 break;
2938
2939 case 0x0A: // String for 1 unit of cargo
2940 AddStringForMapping(buf->ReadWord(), &cs->name_single);
2941 break;
2942
2943 case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
2944 case 0x1B: // String for cargo units
2945 /* String for units of cargo. This is different in OpenTTD
2946 * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
2947 * Property 1B is used to set OpenTTD's behaviour. */
2948 AddStringForMapping(buf->ReadWord(), &cs->units_volume);
2949 break;
2950
2951 case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
2952 case 0x1C: // String for any amount of cargo
2953 /* Strings for an amount of cargo. This is different in OpenTTD
2954 * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
2955 * Property 1C is used to set OpenTTD's behaviour. */
2956 AddStringForMapping(buf->ReadWord(), &cs->quantifier);
2957 break;
2958
2959 case 0x0D: // String for two letter cargo abbreviation
2960 AddStringForMapping(buf->ReadWord(), &cs->abbrev);
2961 break;
2962
2963 case 0x0E: // Sprite ID for cargo icon
2964 cs->sprite = buf->ReadWord();
2965 break;
2966
2967 case 0x0F: // Weight of one unit of cargo
2968 cs->weight = buf->ReadByte();
2969 break;
2970
2971 case 0x10: // Used for payment calculation
2972 cs->transit_days[0] = buf->ReadByte();
2973 break;
2974
2975 case 0x11: // Used for payment calculation
2976 cs->transit_days[1] = buf->ReadByte();
2977 break;
2978
2979 case 0x12: // Base cargo price
2980 cs->initial_payment = buf->ReadDWord();
2981 break;
2982
2983 case 0x13: // Colour for station rating bars
2984 cs->rating_colour = buf->ReadByte();
2985 break;
2986
2987 case 0x14: // Colour for cargo graph
2988 cs->legend_colour = buf->ReadByte();
2989 break;
2990
2991 case 0x15: // Freight status
2992 cs->is_freight = (buf->ReadByte() != 0);
2993 break;
2994
2995 case 0x16: // Cargo classes
2996 cs->classes = buf->ReadWord();
2997 break;
2998
2999 case 0x17: // Cargo label
3000 cs->label = buf->ReadDWord();
3001 cs->label = BSWAP32(cs->label);
3002 break;
3003
3004 case 0x18: { // Town growth substitute type
3005 uint8 substitute_type = buf->ReadByte();
3006
3007 switch (substitute_type) {
3008 case 0x00: cs->town_effect = TE_PASSENGERS; break;
3009 case 0x02: cs->town_effect = TE_MAIL; break;
3010 case 0x05: cs->town_effect = TE_GOODS; break;
3011 case 0x09: cs->town_effect = TE_WATER; break;
3012 case 0x0B: cs->town_effect = TE_FOOD; break;
3013 default:
3014 grfmsg(1, "CargoChangeInfo: Unknown town growth substitute value %d, setting to none.", substitute_type);
3015 FALLTHROUGH;
3016 case 0xFF: cs->town_effect = TE_NONE; break;
3017 }
3018 break;
3019 }
3020
3021 case 0x19: // Town growth coefficient
3022 cs->multipliertowngrowth = buf->ReadWord();
3023 break;
3024
3025 case 0x1A: // Bitmask of callbacks to use
3026 cs->callback_mask = buf->ReadByte();
3027 break;
3028
3029 case 0x1D: // Vehicle capacity muliplier
3030 cs->multiplier = std::max<uint16>(1u, buf->ReadWord());
3031 break;
3032
3033 default:
3034 ret = CIR_UNKNOWN;
3035 break;
3036 }
3037 }
3038
3039 return ret;
3040 }
3041
3042
3051 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
3052 {
3053 ChangeInfoResult ret = CIR_SUCCESS;
3054
3055 if (_cur.grffile->sound_offset == 0) {
3056 grfmsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3057 return CIR_INVALID_ID;
3058 }
3059
3060 if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3061 grfmsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect (%u), max (%u). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3062 return CIR_INVALID_ID;
3063 }
3064
3065 for (int i = 0; i < numinfo; i++) {
3066 SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3067
3068 switch (prop) {
3069 case 0x08: // Relative volume
3070 sound->volume = buf->ReadByte();
3071 break;
3072
3073 case 0x09: // Priority
3074 sound->priority = buf->ReadByte();
3075 break;
3076
3077 case 0x0A: { // Override old sound
3078 SoundID orig_sound = buf->ReadByte();
3079
3080 if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3081 grfmsg(1, "SoundEffectChangeInfo: Original sound %d not defined (max %d)", orig_sound, ORIGINAL_SAMPLE_COUNT);
3082 } else {
3083 SoundEntry *old_sound = GetSound(orig_sound);
3084
3085 /* Literally copy the data of the new sound over the original */
3086 *old_sound = *sound;
3087 }
3088 break;
3089 }
3090
3091 default:
3092 ret = CIR_UNKNOWN;
3093 break;
3094 }
3095 }
3096
3097 return ret;
3098 }
3099
3106 static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
3107 {
3108 ChangeInfoResult ret = CIR_SUCCESS;
3109
3110 switch (prop) {
3111 case 0x09:
3112 case 0x0D:
3113 case 0x0E:
3114 case 0x10:
3115 case 0x11:
3116 case 0x12:
3117 buf->ReadByte();
3118 break;
3119
3120 case 0x0A:
3121 case 0x0B:
3122 case 0x0C:
3123 case 0x0F:
3124 buf->ReadWord();
3125 break;
3126
3127 case 0x13:
3128 buf->Skip(buf->ReadByte() * 2);
3129 break;
3130
3131 default:
3132 ret = CIR_UNKNOWN;
3133 break;
3134 }
3135 return ret;
3136 }
3137
3146 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
3147 {
3148 ChangeInfoResult ret = CIR_SUCCESS;
3149
3150 if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3151 grfmsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded (%u), max (%u). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3152 return CIR_INVALID_ID;
3153 }
3154
3155 /* Allocate industry tile specs if they haven't been allocated already. */
3156 if (_cur.grffile->indtspec == nullptr) {
3157 _cur.grffile->indtspec = CallocT<IndustryTileSpec*>(NUM_INDUSTRYTILES_PER_GRF);
3158 }
3159
3160 for (int i = 0; i < numinfo; i++) {
3161 IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i];
3162
3163 if (prop != 0x08 && tsp == nullptr) {
3164 ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf);
3165 if (cir > ret) ret = cir;
3166 continue;
3167 }
3168
3169 switch (prop) {
3170 case 0x08: { // Substitute industry tile type
3171 IndustryTileSpec **tilespec = &_cur.grffile->indtspec[indtid + i];
3172 byte subs_id = buf->ReadByte();
3173
3174 if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3175 /* The substitute id must be one of the original industry tile. */
3176 grfmsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile %u as substitute industry tile for %u. Ignoring.", subs_id, indtid + i);
3177 continue;
3178 }
3179
3180 /* Allocate space for this industry. */
3181 if (*tilespec == nullptr) {
3182 *tilespec = CallocT<IndustryTileSpec>(1);
3183 tsp = *tilespec;
3184
3185 memcpy(tsp, &_industry_tile_specs[subs_id], sizeof(_industry_tile_specs[subs_id]));
3186 tsp->enabled = true;
3187
3188 /* A copied tile should not have the animation infos copied too.
3189 * The anim_state should be left untouched, though
3190 * It is up to the author to animate them */
3191 tsp->anim_production = INDUSTRYTILE_NOANIM;
3192 tsp->anim_next = INDUSTRYTILE_NOANIM;
3193
3194 tsp->grf_prop.local_id = indtid + i;
3195 tsp->grf_prop.subst_id = subs_id;
3196 tsp->grf_prop.grffile = _cur.grffile;
3197 _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3198 }
3199 break;
3200 }
3201
3202 case 0x09: { // Industry tile override
3203 byte ovrid = buf->ReadByte();
3204
3205 /* The industry being overridden must be an original industry. */
3206 if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3207 grfmsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile %u with industry tile id %u. Ignoring.", ovrid, indtid + i);
3208 continue;
3209 }
3210
3211 _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3212 break;
3213 }
3214
3215 case 0x0A: // Tile acceptance
3216 case 0x0B:
3217 case 0x0C: {
3218 uint16 acctp = buf->ReadWord();
3219 tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3220 tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3221 break;
3222 }
3223
3224 case 0x0D: // Land shape flags
3225 tsp->slopes_refused = (Slope)buf->ReadByte();
3226 break;
3227
3228 case 0x0E: // Callback mask
3229 tsp->callback_mask = buf->ReadByte();
3230 break;
3231
3232 case 0x0F: // Animation information
3233 tsp->animation.frames = buf->ReadByte();
3234 tsp->animation.status = buf->ReadByte();
3235 break;
3236
3237 case 0x10: // Animation speed
3238 tsp->animation.speed = buf->ReadByte();
3239 break;
3240
3241 case 0x11: // Triggers for callback 25
3242 tsp->animation.triggers = buf->ReadByte();
3243 break;
3244
3245 case 0x12: // Special flags
3246 tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
3247 break;
3248
3249 case 0x13: { // variable length cargo acceptance
3250 byte num_cargoes = buf->ReadByte();
3251 if (num_cargoes > lengthof(tsp->acceptance)) {
3252 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3253 error->param_value[1] = prop;
3254 return CIR_DISABLED;
3255 }
3256 for (uint i = 0; i < lengthof(tsp->acceptance); i++) {
3257 if (i < num_cargoes) {
3258 tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3259 /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3260 tsp->acceptance[i] = (int8)buf->ReadByte();
3261 } else {
3262 tsp->accepts_cargo[i] = CT_INVALID;
3263 tsp->acceptance[i] = 0;
3264 }
3265 }
3266 break;
3267 }
3268
3269 default:
3270 ret = CIR_UNKNOWN;
3271 break;
3272 }
3273 }
3274
3275 return ret;
3276 }
3277
3284 static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
3285 {
3286 ChangeInfoResult ret = CIR_SUCCESS;
3287
3288 switch (prop) {
3289 case 0x09:
3290 case 0x0B:
3291 case 0x0F:
3292 case 0x12:
3293 case 0x13:
3294 case 0x14:
3295 case 0x17:
3296 case 0x18:
3297 case 0x19:
3298 case 0x21:
3299 case 0x22:
3300 buf->ReadByte();
3301 break;
3302
3303 case 0x0C:
3304 case 0x0D:
3305 case 0x0E:
3306 case 0x10:
3307 case 0x1B:
3308 case 0x1F:
3309 case 0x24:
3310 buf->ReadWord();
3311 break;
3312
3313 case 0x11:
3314 case 0x1A:
3315 case 0x1C:
3316 case 0x1D:
3317 case 0x1E:
3318 case 0x20:
3319 case 0x23:
3320 buf->ReadDWord();
3321 break;
3322
3323 case 0x0A: {
3324 byte num_table = buf->ReadByte();
3325 for (byte j = 0; j < num_table; j++) {
3326 for (uint k = 0;; k++) {
3327 byte x = buf->ReadByte();
3328 if (x == 0xFE && k == 0) {
3329 buf->ReadByte();
3330 buf->ReadByte();
3331 break;
3332 }
3333
3334 byte y = buf->ReadByte();
3335 if (x == 0 && y == 0x80) break;
3336
3337 byte gfx = buf->ReadByte();
3338 if (gfx == 0xFE) buf->ReadWord();
3339 }
3340 }
3341 break;
3342 }
3343
3344 case 0x16:
3345 for (byte j = 0; j < 3; j++) buf->ReadByte();
3346 break;
3347
3348 case 0x15:
3349 case 0x25:
3350 case 0x26:
3351 case 0x27:
3352 buf->Skip(buf->ReadByte());
3353 break;
3354
3355 case 0x28: {
3356 int num_inputs = buf->ReadByte();
3357 int num_outputs = buf->ReadByte();
3358 buf->Skip(num_inputs * num_outputs * 2);
3359 break;
3360 }
3361
3362 default:
3363 ret = CIR_UNKNOWN;
3364 break;
3365 }
3366 return ret;
3367 }
3368
3374 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3375 {
3376 const size_t size = layout.size();
3377 for (size_t i = 0; i < size - 1; i++) {
3378 for (size_t j = i + 1; j < size; j++) {
3379 if (layout[i].ti.x == layout[j].ti.x &&
3380 layout[i].ti.y == layout[j].ti.y) {
3381 return false;
3382 }
3383 }
3384 }
3385 return true;
3386 }
3387
3396 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
3397 {
3398 ChangeInfoResult ret = CIR_SUCCESS;
3399
3400 if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3401 grfmsg(1, "IndustriesChangeInfo: Too many industries loaded (%u), max (%u). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3402 return CIR_INVALID_ID;
3403 }
3404
3405 /* Allocate industry specs if they haven't been allocated already. */
3406 if (_cur.grffile->industryspec == nullptr) {
3407 _cur.grffile->industryspec = CallocT<IndustrySpec*>(NUM_INDUSTRYTYPES_PER_GRF);
3408 }
3409
3410 for (int i = 0; i < numinfo; i++) {
3411 IndustrySpec *indsp = _cur.grffile->industryspec[indid + i];
3412
3413 if (prop != 0x08 && indsp == nullptr) {
3414 ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3415 if (cir > ret) ret = cir;
3416 continue;
3417 }
3418
3419 switch (prop) {
3420 case 0x08: { // Substitute industry type
3421 IndustrySpec **indspec = &_cur.grffile->industryspec[indid + i];
3422 byte subs_id = buf->ReadByte();
3423
3424 if (subs_id == 0xFF) {
3425 /* Instead of defining a new industry, a substitute industry id
3426 * of 0xFF disables the old industry with the current id. */
3427 _industry_specs[indid + i].enabled = false;
3428 continue;
3429 } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3430 /* The substitute id must be one of the original industry. */
3431 grfmsg(2, "_industry_specs: Attempt to use new industry %u as substitute industry for %u. Ignoring.", subs_id, indid + i);
3432 continue;
3433 }
3434
3435 /* Allocate space for this industry.
3436 * Only need to do it once. If ever it is called again, it should not
3437 * do anything */
3438 if (*indspec == nullptr) {
3439 *indspec = new IndustrySpec;
3440 indsp = *indspec;
3441
3442 *indsp = _origin_industry_specs[subs_id];
3443 indsp->enabled = true;
3444 indsp->grf_prop.local_id = indid + i;
3445 indsp->grf_prop.subst_id = subs_id;
3446 indsp->grf_prop.grffile = _cur.grffile;
3447 /* If the grf industry needs to check its surrounding upon creation, it should
3448 * rely on callbacks, not on the original placement functions */
3449 indsp->check_proc = CHECK_NOTHING;
3450 }
3451 break;
3452 }
3453
3454 case 0x09: { // Industry type override
3455 byte ovrid = buf->ReadByte();
3456
3457 /* The industry being overridden must be an original industry. */
3458 if (ovrid >= NEW_INDUSTRYOFFSET) {
3459 grfmsg(2, "IndustriesChangeInfo: Attempt to override new industry %u with industry id %u. Ignoring.", ovrid, indid + i);
3460 continue;
3461 }
3462 indsp->grf_prop.override = ovrid;
3463 _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3464 break;
3465 }
3466
3467 case 0x0A: { // Set industry layout(s)
3468 byte new_num_layouts = buf->ReadByte();
3469 uint32 definition_size = buf->ReadDWord();
3470 uint32 bytes_read = 0;
3471 std::vector<IndustryTileLayout> new_layouts;
3472 IndustryTileLayout layout;
3473
3474 for (byte j = 0; j < new_num_layouts; j++) {
3475 layout.clear();
3476
3477 for (uint k = 0;; k++) {
3478 if (bytes_read >= definition_size) {
3479 grfmsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry %u.", indid);
3480 /* Avoid warning twice */
3481 definition_size = UINT32_MAX;
3482 }
3483
3484 layout.push_back(IndustryTileLayoutTile{});
3485 IndustryTileLayoutTile &it = layout.back();
3486
3487 it.ti.x = buf->ReadByte(); // Offsets from northermost tile
3488 ++bytes_read;
3489
3490 if (it.ti.x == 0xFE && k == 0) {
3491 /* This means we have to borrow the layout from an old industry */
3492 IndustryType type = buf->ReadByte();
3493 byte laynbr = buf->ReadByte();
3494 bytes_read += 2;
3495
3496 if (type >= lengthof(_origin_industry_specs)) {
3497 grfmsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry %u", indid);
3498 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3499 return CIR_DISABLED;
3500 }
3501 if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3502 grfmsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry %u", indid);
3503 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3504 return CIR_DISABLED;
3505 }
3506 layout = _origin_industry_specs[type].layouts[laynbr];
3507 break;
3508 }
3509
3510 it.ti.y = buf->ReadByte(); // Or table definition finalisation
3511 ++bytes_read;
3512
3513 if (it.ti.x == 0 && it.ti.y == 0x80) {
3514 /* Terminator, remove and finish up */
3515 layout.pop_back();
3516 break;
3517 }
3518
3519 it.gfx = buf->ReadByte();
3520 ++bytes_read;
3521
3522 if (it.gfx == 0xFE) {
3523 /* Use a new tile from this GRF */
3524 int local_tile_id = buf->ReadWord();
3525 bytes_read += 2;
3526
3527 /* Read the ID from the _industile_mngr. */
3528 int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3529
3530 if (tempid == INVALID_INDUSTRYTILE) {
3531 grfmsg(2, "IndustriesChangeInfo: Attempt to use industry tile %u with industry id %u, not yet defined. Ignoring.", local_tile_id, indid);
3532 } else {
3533 /* Declared as been valid, can be used */
3534 it.gfx = tempid;
3535 }
3536 } else if (it.gfx == 0xFF) {
3537 it.ti.x = (int8)GB(it.ti.x, 0, 8);
3538 it.ti.y = (int8)GB(it.ti.y, 0, 8);
3539
3540 /* When there were only 256x256 maps, TileIndex was a uint16 and
3541 * it.ti was just a TileIndexDiff that was added to it.
3542 * As such negative "x" values were shifted into the "y" position.
3543 * x = -1, y = 1 -> x = 255, y = 0
3544 * Since GRF version 8 the position is interpreted as pair of independent int8.
3545 * For GRF version < 8 we need to emulate the old shifting behaviour.
3546 */
3547 if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3548 }
3549 }
3550
3551 if (!ValidateIndustryLayout(layout)) {
3552 /* The industry layout was not valid, so skip this one. */
3553 grfmsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id %u. Ignoring", indid);
3554 new_num_layouts--;
3555 j--;
3556 } else {
3557 new_layouts.push_back(layout);
3558 }
3559 }
3560
3561 /* Install final layout construction in the industry spec */
3562 indsp->layouts = new_layouts;
3563 break;
3564 }
3565
3566 case 0x0B: // Industry production flags
3567 indsp->life_type = (IndustryLifeType)buf->ReadByte();
3568 break;
3569
3570 case 0x0C: // Industry closure message
3571 AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
3572 break;
3573
3574 case 0x0D: // Production increase message
3575 AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
3576 break;
3577
3578 case 0x0E: // Production decrease message
3579 AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
3580 break;
3581
3582 case 0x0F: // Fund cost multiplier
3583 indsp->cost_multiplier = buf->ReadByte();
3584 break;
3585
3586 case 0x10: // Production cargo types
3587 for (byte j = 0; j < 2; j++) {
3588 indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3589 }
3590 break;
3591
3592 case 0x11: // Acceptance cargo types
3593 for (byte j = 0; j < 3; j++) {
3594 indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3595 }
3596 buf->ReadByte(); // Unnused, eat it up
3597 break;
3598
3599 case 0x12: // Production multipliers
3600 case 0x13:
3601 indsp->production_rate[prop - 0x12] = buf->ReadByte();
3602 break;
3603
3604 case 0x14: // Minimal amount of cargo distributed
3605 indsp->minimal_cargo = buf->ReadByte();
3606 break;
3607
3608 case 0x15: { // Random sound effects
3609 indsp->number_of_sounds = buf->ReadByte();
3610 uint8 *sounds = MallocT<uint8>(indsp->number_of_sounds);
3611
3612 try {
3613 for (uint8 j = 0; j < indsp->number_of_sounds; j++) {
3614 sounds[j] = buf->ReadByte();
3615 }
3616 } catch (...) {
3617 free(sounds);
3618 throw;
3619 }
3620
3621 if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3622 free(indsp->random_sounds);
3623 }
3624 indsp->random_sounds = sounds;
3625 SetBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS);
3626 break;
3627 }
3628
3629 case 0x16: // Conflicting industry types
3630 for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
3631 break;
3632
3633 case 0x17: // Probability in random game
3634 indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
3635 break;
3636
3637 case 0x18: // Probability during gameplay
3638 indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
3639 break;
3640
3641 case 0x19: // Map colour
3642 indsp->map_colour = buf->ReadByte();
3643 break;
3644
3645 case 0x1A: // Special industry flags to define special behavior
3646 indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
3647 break;
3648
3649 case 0x1B: // New industry text ID
3650 AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
3651 break;
3652
3653 case 0x1C: // Input cargo multipliers for the three input cargo types
3654 case 0x1D:
3655 case 0x1E: {
3656 uint32 multiples = buf->ReadDWord();
3657 indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3658 indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3659 break;
3660 }
3661
3662 case 0x1F: // Industry name
3663 AddStringForMapping(buf->ReadWord(), &indsp->name);
3664 break;
3665
3666 case 0x20: // Prospecting success chance
3667 indsp->prospecting_chance = buf->ReadDWord();
3668 break;
3669
3670 case 0x21: // Callback mask
3671 case 0x22: { // Callback additional mask
3672 byte aflag = buf->ReadByte();
3673 SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3674 break;
3675 }
3676
3677 case 0x23: // removal cost multiplier
3678 indsp->removal_cost_multiplier = buf->ReadDWord();
3679 break;
3680
3681 case 0x24: { // name for nearby station
3682 uint16 str = buf->ReadWord();
3683 if (str == 0) {
3684 indsp->station_name = STR_NULL;
3685 } else {
3686 AddStringForMapping(str, &indsp->station_name);
3687 }
3688 break;
3689 }
3690
3691 case 0x25: { // variable length produced cargoes
3692 byte num_cargoes = buf->ReadByte();
3693 if (num_cargoes > lengthof(indsp->produced_cargo)) {
3694 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3695 error->param_value[1] = prop;
3696 return CIR_DISABLED;
3697 }
3698 for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
3699 if (i < num_cargoes) {
3700 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3701 indsp->produced_cargo[i] = cargo;
3702 } else {
3703 indsp->produced_cargo[i] = CT_INVALID;
3704 }
3705 }
3706 break;
3707 }
3708
3709 case 0x26: { // variable length accepted cargoes
3710 byte num_cargoes = buf->ReadByte();
3711 if (num_cargoes > lengthof(indsp->accepts_cargo)) {
3712 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3713 error->param_value[1] = prop;
3714 return CIR_DISABLED;
3715 }
3716 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3717 if (i < num_cargoes) {
3718 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3719 indsp->accepts_cargo[i] = cargo;
3720 } else {
3721 indsp->accepts_cargo[i] = CT_INVALID;
3722 }
3723 }
3724 break;
3725 }
3726
3727 case 0x27: { // variable length production rates
3728 byte num_cargoes = buf->ReadByte();
3729 if (num_cargoes > lengthof(indsp->production_rate)) {
3730 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3731 error->param_value[1] = prop;
3732 return CIR_DISABLED;
3733 }
3734 for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3735 if (i < num_cargoes) {
3736 indsp->production_rate[i] = buf->ReadByte();
3737 } else {
3738 indsp->production_rate[i] = 0;
3739 }
3740 }
3741 break;
3742 }
3743
3744 case 0x28: { // variable size input/output production multiplier table
3745 byte num_inputs = buf->ReadByte();
3746 byte num_outputs = buf->ReadByte();
3747 if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
3748 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3749 error->param_value[1] = prop;
3750 return CIR_DISABLED;
3751 }
3752 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3753 for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
3754 uint16 mult = 0;
3755 if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
3756 indsp->input_cargo_multiplier[i][j] = mult;
3757 }
3758 }
3759 break;
3760 }
3761
3762 default:
3763 ret = CIR_UNKNOWN;
3764 break;
3765 }
3766 }
3767
3768 return ret;
3769 }
3770
3776 static void DuplicateTileTable(AirportSpec *as)
3777 {
3778 AirportTileTable **table_list = MallocT<AirportTileTable*>(as->num_table);
3779 for (int i = 0; i < as->num_table; i++) {
3780 uint num_tiles = 1;
3781 const AirportTileTable *it = as->table[0];
3782 do {
3783 num_tiles++;
3784 } while ((++it)->ti.x != -0x80);
3785 table_list[i] = MallocT<AirportTileTable>(num_tiles);
3786 MemCpyT(table_list[i], as->table[i], num_tiles);
3787 }
3788 as->table = table_list;
3789 HangarTileTable *depot_table = MallocT<HangarTileTable>(as->nof_depots);
3790 MemCpyT(depot_table, as->depot_table, as->nof_depots);
3791 as->depot_table = depot_table;
3792 Direction *rotation = MallocT<Direction>(as->num_table);
3793 MemCpyT(rotation, as->rotation, as->num_table);
3794 as->rotation = rotation;
3795 }
3796
3805 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
3806 {
3807 ChangeInfoResult ret = CIR_SUCCESS;
3808
3809 if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3810 grfmsg(1, "AirportChangeInfo: Too many airports, trying id (%u), max (%u). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3811 return CIR_INVALID_ID;
3812 }
3813
3814 /* Allocate industry specs if they haven't been allocated already. */
3815 if (_cur.grffile->airportspec == nullptr) {
3816 _cur.grffile->airportspec = CallocT<AirportSpec*>(NUM_AIRPORTS_PER_GRF);
3817 }
3818
3819 for (int i = 0; i < numinfo; i++) {
3820 AirportSpec *as = _cur.grffile->airportspec[airport + i];
3821
3822 if (as == nullptr && prop != 0x08 && prop != 0x09) {
3823 grfmsg(2, "AirportChangeInfo: Attempt to modify undefined airport %u, ignoring", airport + i);
3824 return CIR_INVALID_ID;
3825 }
3826
3827 switch (prop) {
3828 case 0x08: { // Modify original airport
3829 byte subs_id = buf->ReadByte();
3830
3831 if (subs_id == 0xFF) {
3832 /* Instead of defining a new airport, an airport id
3833 * of 0xFF disables the old airport with the current id. */
3834 AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3835 continue;
3836 } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3837 /* The substitute id must be one of the original airports. */
3838 grfmsg(2, "AirportChangeInfo: Attempt to use new airport %u as substitute airport for %u. Ignoring.", subs_id, airport + i);
3839 continue;
3840 }
3841
3842 AirportSpec **spec = &_cur.grffile->airportspec[airport + i];
3843 /* Allocate space for this airport.
3844 * Only need to do it once. If ever it is called again, it should not
3845 * do anything */
3846 if (*spec == nullptr) {
3847 *spec = MallocT<AirportSpec>(1);
3848 as = *spec;
3849
3850 memcpy(as, AirportSpec::GetWithoutOverride(subs_id), sizeof(*as));
3851 as->enabled = true;
3852 as->grf_prop.local_id = airport + i;
3853 as->grf_prop.subst_id = subs_id;
3854 as->grf_prop.grffile = _cur.grffile;
3855 /* override the default airport */
3856 _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3857 /* Create a copy of the original tiletable so it can be freed later. */
3858 DuplicateTileTable(as);
3859 }
3860 break;
3861 }
3862
3863 case 0x0A: { // Set airport layout
3864 byte old_num_table = as->num_table;
3865 free(as->rotation);
3866 as->num_table = buf->ReadByte(); // Number of layaouts
3867 as->rotation = MallocT<Direction>(as->num_table);
3868 uint32 defsize = buf->ReadDWord(); // Total size of the definition
3869 AirportTileTable **tile_table = CallocT<AirportTileTable*>(as->num_table); // Table with tiles to compose the airport
3870 AirportTileTable *att = CallocT<AirportTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
3871 int size;
3872 const AirportTileTable *copy_from;
3873 try {
3874 for (byte j = 0; j < as->num_table; j++) {
3875 const_cast<Direction&>(as->rotation[j]) = (Direction)buf->ReadByte();
3876 for (int k = 0;; k++) {
3877 att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3878 att[k].ti.y = buf->ReadByte();
3879
3880 if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
3881 /* Not the same terminator. The one we are using is rather
3882 * x = -80, y = 0 . So, adjust it. */
3883 att[k].ti.x = -0x80;
3884 att[k].ti.y = 0;
3885 att[k].gfx = 0;
3886
3887 size = k + 1;
3888 copy_from = att;
3889 break;
3890 }
3891
3892 att[k].gfx = buf->ReadByte();
3893
3894 if (att[k].gfx == 0xFE) {
3895 /* Use a new tile from this GRF */
3896 int local_tile_id = buf->ReadWord();
3897
3898 /* Read the ID from the _airporttile_mngr. */
3899 uint16 tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3900
3901 if (tempid == INVALID_AIRPORTTILE) {
3902 grfmsg(2, "AirportChangeInfo: Attempt to use airport tile %u with airport id %u, not yet defined. Ignoring.", local_tile_id, airport + i);
3903 } else {
3904 /* Declared as been valid, can be used */
3905 att[k].gfx = tempid;
3906 }
3907 } else if (att[k].gfx == 0xFF) {
3908 att[k].ti.x = (int8)GB(att[k].ti.x, 0, 8);
3909 att[k].ti.y = (int8)GB(att[k].ti.y, 0, 8);
3910 }
3911
3912 if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
3913 as->size_x = std::max<byte>(as->size_x, att[k].ti.y + 1);
3914 as->size_y = std::max<byte>(as->size_y, att[k].ti.x + 1);
3915 } else {
3916 as->size_x = std::max<byte>(as->size_x, att[k].ti.x + 1);
3917 as->size_y = std::max<byte>(as->size_y, att[k].ti.y + 1);
3918 }
3919 }
3920 tile_table[j] = CallocT<AirportTileTable>(size);
3921 memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
3922 }
3923 /* Free old layouts in the airport spec */
3924 for (int j = 0; j < old_num_table; j++) {
3925 /* remove the individual layouts */
3926 free(as->table[j]);
3927 }
3928 free(as->table);
3929 /* Install final layout construction in the airport spec */
3930 as->table = tile_table;
3931 free(att);
3932 } catch (...) {
3933 for (int i = 0; i < as->num_table; i++) {
3934 free(tile_table[i]);
3935 }
3936 free(tile_table);
3937 free(att);
3938 throw;
3939 }
3940 break;
3941 }
3942
3943 case 0x0C:
3944 as->min_year = buf->ReadWord();
3945 as->max_year = buf->ReadWord();
3946 if (as->max_year == 0xFFFF) as->max_year = MAX_YEAR;
3947 break;
3948
3949 case 0x0D:
3950 as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
3951 break;
3952
3953 case 0x0E:
3954 as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
3955 break;
3956
3957 case 0x0F:
3958 as->noise_level = buf->ReadByte();
3959 break;
3960
3961 case 0x10:
3962 AddStringForMapping(buf->ReadWord(), &as->name);
3963 break;
3964
3965 case 0x11: // Maintenance cost factor
3966 as->maintenance_cost = buf->ReadWord();
3967 break;
3968
3969 default:
3970 ret = CIR_UNKNOWN;
3971 break;
3972 }
3973 }
3974
3975 return ret;
3976 }
3977
3984 static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
3985 {
3986 ChangeInfoResult ret = CIR_SUCCESS;
3987
3988 switch (prop) {
3989 case 0x0B:
3990 case 0x0C:
3991 case 0x0D:
3992 case 0x12:
3993 case 0x14:
3994 case 0x16:
3995 case 0x17:
3996 buf->ReadByte();
3997 break;
3998
3999 case 0x09:
4000 case 0x0A:
4001 case 0x10:
4002 case 0x11:
4003 case 0x13:
4004 case 0x15:
4005 buf->ReadWord();
4006 break;
4007
4008 case 0x08:
4009 case 0x0E:
4010 case 0x0F:
4011 buf->ReadDWord();
4012 break;
4013
4014 default:
4015 ret = CIR_UNKNOWN;
4016 break;
4017 }
4018
4019 return ret;
4020 }
4021
4030 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4031 {
4032 ChangeInfoResult ret = CIR_SUCCESS;
4033
4034 if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4035 grfmsg(1, "ObjectChangeInfo: Too many objects loaded (%u), max (%u). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4036 return CIR_INVALID_ID;
4037 }
4038
4039 /* Allocate object specs if they haven't been allocated already. */
4040 if (_cur.grffile->objectspec == nullptr) {
4041 _cur.grffile->objectspec = CallocT<ObjectSpec*>(NUM_OBJECTS_PER_GRF);
4042 }
4043
4044 for (int i = 0; i < numinfo; i++) {
4045 ObjectSpec *spec = _cur.grffile->objectspec[id + i];
4046
4047 if (prop != 0x08 && spec == nullptr) {
4048 /* If the object property 08 is not yet set, ignore this property */
4049 ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4050 if (cir > ret) ret = cir;
4051 continue;
4052 }
4053
4054 switch (prop) {
4055 case 0x08: { // Class ID
4056 ObjectSpec **ospec = &_cur.grffile->objectspec[id + i];
4057
4058 /* Allocate space for this object. */
4059 if (*ospec == nullptr) {
4060 *ospec = CallocT<ObjectSpec>(1);
4061 (*ospec)->views = 1; // Default for NewGRFs that don't set it.
4062 (*ospec)->size = 0x11; // Default for NewGRFs that manage to not set it (1x1)
4063 }
4064
4065 /* Swap classid because we read it in BE. */
4066 uint32 classid = buf->ReadDWord();
4067 (*ospec)->cls_id = ObjectClass::Allocate(BSWAP32(classid));
4068 (*ospec)->enabled = true;
4069 break;
4070 }
4071
4072 case 0x09: { // Class name
4073 ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
4074 AddStringForMapping(buf->ReadWord(), &objclass->name);
4075 break;
4076 }
4077
4078 case 0x0A: // Object name
4079 AddStringForMapping(buf->ReadWord(), &spec->name);
4080 break;
4081
4082 case 0x0B: // Climate mask
4083 spec->climate = buf->ReadByte();
4084 break;
4085
4086 case 0x0C: // Size
4087 spec->size = buf->ReadByte();
4088 if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4089 grfmsg(0, "ObjectChangeInfo: Invalid object size requested (0x%x) for object id %u. Ignoring.", spec->size, id + i);
4090 spec->size = 0x11; // 1x1
4091 }
4092 break;
4093
4094 case 0x0D: // Build cost multipler
4095 spec->build_cost_multiplier = buf->ReadByte();
4096 spec->clear_cost_multiplier = spec->build_cost_multiplier;
4097 break;
4098
4099 case 0x0E: // Introduction date
4100 spec->introduction_date = buf->ReadDWord();
4101 break;
4102
4103 case 0x0F: // End of life
4104 spec->end_of_life_date = buf->ReadDWord();
4105 break;
4106
4107 case 0x10: // Flags
4108 spec->flags = (ObjectFlags)buf->ReadWord();
4109 _loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
4110 break;
4111
4112 case 0x11: // Animation info
4113 spec->animation.frames = buf->ReadByte();
4114 spec->animation.status = buf->ReadByte();
4115 break;
4116
4117 case 0x12: // Animation speed
4118 spec->animation.speed = buf->ReadByte();
4119 break;
4120
4121 case 0x13: // Animation triggers
4122 spec->animation.triggers = buf->ReadWord();
4123 break;
4124
4125 case 0x14: // Removal cost multiplier
4126 spec->clear_cost_multiplier = buf->ReadByte();
4127 break;
4128
4129 case 0x15: // Callback mask
4130 spec->callback_mask = buf->ReadWord();
4131 break;
4132
4133 case 0x16: // Building height
4134 spec->height = buf->ReadByte();
4135 break;
4136
4137 case 0x17: // Views
4138 spec->views = buf->ReadByte();
4139 if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4140 grfmsg(2, "ObjectChangeInfo: Invalid number of views (%u) for object id %u. Ignoring.", spec->views, id + i);
4141 spec->views = 1;
4142 }
4143 break;
4144
4145 case 0x18: // Amount placed on 256^2 map on map creation
4146 spec->generate_amount = buf->ReadByte();
4147 break;
4148
4149 default:
4150 ret = CIR_UNKNOWN;
4151 break;
4152 }
4153 }
4154
4155 return ret;
4156 }
4157
4166 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4167 {
4168 ChangeInfoResult ret = CIR_SUCCESS;
4169
4170 extern RailtypeInfo _railtypes[RAILTYPE_END];
4171
4172 if (id + numinfo > RAILTYPE_END) {
4173 grfmsg(1, "RailTypeChangeInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4174 return CIR_INVALID_ID;
4175 }
4176
4177 for (int i = 0; i < numinfo; i++) {
4178 RailType rt = _cur.grffile->railtype_map[id + i];
4179 if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4180
4181 RailtypeInfo *rti = &_railtypes[rt];
4182
4183 switch (prop) {
4184 case 0x08: // Label of rail type
4185 /* Skipped here as this is loaded during reservation stage. */
4186 buf->ReadDWord();
4187 break;
4188
4189 case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4190 uint16 str = buf->ReadWord();
4191 AddStringForMapping(str, &rti->strings.toolbar_caption);
4192 if (_cur.grffile->grf_version < 8) {
4193 AddStringForMapping(str, &rti->strings.name);
4194 }
4195 break;
4196 }
4197
4198 case 0x0A: // Menu text of railtype
4199 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4200 break;
4201
4202 case 0x0B: // Build window caption
4203 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4204 break;
4205
4206 case 0x0C: // Autoreplace text
4207 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4208 break;
4209
4210 case 0x0D: // New locomotive text
4211 AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
4212 break;
4213
4214 case 0x0E: // Compatible railtype list
4215 case 0x0F: // Powered railtype list
4216 case 0x18: // Railtype list required for date introduction
4217 case 0x19: // Introduced railtype list
4218 {
4219 /* Rail type compatibility bits are added to the existing bits
4220 * to allow multiple GRFs to modify compatibility with the
4221 * default rail types. */
4222 int n = buf->ReadByte();
4223 for (int j = 0; j != n; j++) {
4224 RailTypeLabel label = buf->ReadDWord();
4225 RailType rt = GetRailTypeByLabel(BSWAP32(label), false);
4226 if (rt != INVALID_RAILTYPE) {
4227 switch (prop) {
4228 case 0x0F: SetBit(rti->powered_railtypes, rt); FALLTHROUGH; // Powered implies compatible.
4229 case 0x0E: SetBit(rti->compatible_railtypes, rt); break;
4230 case 0x18: SetBit(rti->introduction_required_railtypes, rt); break;
4231 case 0x19: SetBit(rti->introduces_railtypes, rt); break;
4232 }
4233 }
4234 }
4235 break;
4236 }
4237
4238 case 0x10: // Rail Type flags
4239 rti->flags = (RailTypeFlags)buf->ReadByte();
4240 break;
4241
4242 case 0x11: // Curve speed advantage
4243 rti->curve_speed = buf->ReadByte();
4244 break;
4245
4246 case 0x12: // Station graphic
4247 rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
4248 break;
4249
4250 case 0x13: // Construction cost factor
4251 rti->cost_multiplier = buf->ReadWord();
4252 break;
4253
4254 case 0x14: // Speed limit
4255 rti->max_speed = buf->ReadWord();
4256 break;
4257
4258 case 0x15: // Acceleration model
4259 rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
4260 break;
4261
4262 case 0x16: // Map colour
4263 rti->map_colour = buf->ReadByte();
4264 break;
4265
4266 case 0x17: // Introduction date
4267 rti->introduction_date = buf->ReadDWord();
4268 break;
4269
4270 case 0x1A: // Sort order
4271 rti->sorting_order = buf->ReadByte();
4272 break;
4273
4274 case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4275 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4276 break;
4277
4278 case 0x1C: // Maintenance cost factor
4279 rti->maintenance_multiplier = buf->ReadWord();
4280 break;
4281
4282 case 0x1D: // Alternate rail type label list
4283 /* Skipped here as this is loaded during reservation stage. */
4284 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4285 break;
4286
4287 default:
4288 ret = CIR_UNKNOWN;
4289 break;
4290 }
4291 }
4292
4293 return ret;
4294 }
4295
4296 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4297 {
4298 ChangeInfoResult ret = CIR_SUCCESS;
4299
4300 extern RailtypeInfo _railtypes[RAILTYPE_END];
4301
4302 if (id + numinfo > RAILTYPE_END) {
4303 grfmsg(1, "RailTypeReserveInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4304 return CIR_INVALID_ID;
4305 }
4306
4307 for (int i = 0; i < numinfo; i++) {
4308 switch (prop) {
4309 case 0x08: // Label of rail type
4310 {
4311 RailTypeLabel rtl = buf->ReadDWord();
4312 rtl = BSWAP32(rtl);
4313
4314 RailType rt = GetRailTypeByLabel(rtl, false);
4315 if (rt == INVALID_RAILTYPE) {
4316 /* Set up new rail type */
4317 rt = AllocateRailType(rtl);
4318 }
4319
4320 _cur.grffile->railtype_map[id + i] = rt;
4321 break;
4322 }
4323
4324 case 0x09: // Toolbar caption of railtype
4325 case 0x0A: // Menu text
4326 case 0x0B: // Build window caption
4327 case 0x0C: // Autoreplace text
4328 case 0x0D: // New loco
4329 case 0x13: // Construction cost
4330 case 0x14: // Speed limit
4331 case 0x1B: // Name of railtype
4332 case 0x1C: // Maintenance cost factor
4333 buf->ReadWord();
4334 break;
4335
4336 case 0x1D: // Alternate rail type label list
4337 if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4338 int n = buf->ReadByte();
4339 for (int j = 0; j != n; j++) {
4340 _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4341 }
4342 break;
4343 }
4344 grfmsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type %u because no label was set", id + i);
4345 FALLTHROUGH;
4346
4347 case 0x0E: // Compatible railtype list
4348 case 0x0F: // Powered railtype list
4349 case 0x18: // Railtype list required for date introduction
4350 case 0x19: // Introduced railtype list
4351 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4352 break;
4353
4354 case 0x10: // Rail Type flags
4355 case 0x11: // Curve speed advantage
4356 case 0x12: // Station graphic
4357 case 0x15: // Acceleration model
4358 case 0x16: // Map colour
4359 case 0x1A: // Sort order
4360 buf->ReadByte();
4361 break;
4362
4363 case 0x17: // Introduction date
4364 buf->ReadDWord();
4365 break;
4366
4367 default:
4368 ret = CIR_UNKNOWN;
4369 break;
4370 }
4371 }
4372
4373 return ret;
4374 }
4375
4384 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4385 {
4386 ChangeInfoResult ret = CIR_SUCCESS;
4387
4388 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4389 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4390
4391 if (id + numinfo > ROADTYPE_END) {
4392 grfmsg(1, "RoadTypeChangeInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4393 return CIR_INVALID_ID;
4394 }
4395
4396 for (int i = 0; i < numinfo; i++) {
4397 RoadType rt = type_map[id + i];
4398 if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4399
4400 RoadTypeInfo *rti = &_roadtypes[rt];
4401
4402 switch (prop) {
4403 case 0x08: // Label of road type
4404 /* Skipped here as this is loaded during reservation stage. */
4405 buf->ReadDWord();
4406 break;
4407
4408 case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4409 uint16 str = buf->ReadWord();
4410 AddStringForMapping(str, &rti->strings.toolbar_caption);
4411 break;
4412 }
4413
4414 case 0x0A: // Menu text of roadtype
4415 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4416 break;
4417
4418 case 0x0B: // Build window caption
4419 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4420 break;
4421
4422 case 0x0C: // Autoreplace text
4423 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4424 break;
4425
4426 case 0x0D: // New engine text
4427 AddStringForMapping(buf->ReadWord(), &rti->strings.new_engine);
4428 break;
4429
4430 case 0x0F: // Powered roadtype list
4431 case 0x18: // Roadtype list required for date introduction
4432 case 0x19: { // Introduced roadtype list
4433 /* Road type compatibility bits are added to the existing bits
4434 * to allow multiple GRFs to modify compatibility with the
4435 * default road types. */
4436 int n = buf->ReadByte();
4437 for (int j = 0; j != n; j++) {
4438 RoadTypeLabel label = buf->ReadDWord();
4439 RoadType rt = GetRoadTypeByLabel(BSWAP32(label), false);
4440 if (rt != INVALID_ROADTYPE) {
4441 switch (prop) {
4442 case 0x0F: SetBit(rti->powered_roadtypes, rt); break;
4443 case 0x18: SetBit(rti->introduction_required_roadtypes, rt); break;
4444 case 0x19: SetBit(rti->introduces_roadtypes, rt); break;
4445 }
4446 }
4447 }
4448 break;
4449 }
4450
4451 case 0x10: // Road Type flags
4452 rti->flags = (RoadTypeFlags)buf->ReadByte();
4453 break;
4454
4455 case 0x13: // Construction cost factor
4456 rti->cost_multiplier = buf->ReadWord();
4457 break;
4458
4459 case 0x14: // Speed limit
4460 rti->max_speed = buf->ReadWord();
4461 break;
4462
4463 case 0x16: // Map colour
4464 rti->map_colour = buf->ReadByte();
4465 break;
4466
4467 case 0x17: // Introduction date
4468 rti->introduction_date = buf->ReadDWord();
4469 break;
4470
4471 case 0x1A: // Sort order
4472 rti->sorting_order = buf->ReadByte();
4473 break;
4474
4475 case 0x1B: // Name of roadtype
4476 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4477 break;
4478
4479 case 0x1C: // Maintenance cost factor
4480 rti->maintenance_multiplier = buf->ReadWord();
4481 break;
4482
4483 case 0x1D: // Alternate road type label list
4484 /* Skipped here as this is loaded during reservation stage. */
4485 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4486 break;
4487
4488 default:
4489 ret = CIR_UNKNOWN;
4490 break;
4491 }
4492 }
4493
4494 return ret;
4495 }
4496
4497 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4498 {
4499 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4500 }
4501
4502 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4503 {
4504 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4505 }
4506
4507
4508 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4509 {
4510 ChangeInfoResult ret = CIR_SUCCESS;
4511
4512 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4513 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4514
4515 if (id + numinfo > ROADTYPE_END) {
4516 grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4517 return CIR_INVALID_ID;
4518 }
4519
4520 for (int i = 0; i < numinfo; i++) {
4521 switch (prop) {
4522 case 0x08: { // Label of road type
4523 RoadTypeLabel rtl = buf->ReadDWord();
4524 rtl = BSWAP32(rtl);
4525
4526 RoadType rt = GetRoadTypeByLabel(rtl, false);
4527 if (rt == INVALID_ROADTYPE) {
4528 /* Set up new road type */
4529 rt = AllocateRoadType(rtl, rtt);
4530 } else if (GetRoadTramType(rt) != rtt) {
4531 grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid type (road/tram), ignoring", id + numinfo);
4532 return CIR_INVALID_ID;
4533 }
4534
4535 type_map[id + i] = rt;
4536 break;
4537 }
4538 case 0x09: // Toolbar caption of roadtype
4539 case 0x0A: // Menu text
4540 case 0x0B: // Build window caption
4541 case 0x0C: // Autoreplace text
4542 case 0x0D: // New loco
4543 case 0x13: // Construction cost
4544 case 0x14: // Speed limit
4545 case 0x1B: // Name of roadtype
4546 case 0x1C: // Maintenance cost factor
4547 buf->ReadWord();
4548 break;
4549
4550 case 0x1D: // Alternate road type label list
4551 if (type_map[id + i] != INVALID_ROADTYPE) {
4552 int n = buf->ReadByte();
4553 for (int j = 0; j != n; j++) {
4554 _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4555 }
4556 break;
4557 }
4558 grfmsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type %u because no label was set", id + i);
4559 /* FALL THROUGH */
4560
4561 case 0x0F: // Powered roadtype list
4562 case 0x18: // Roadtype list required for date introduction
4563 case 0x19: // Introduced roadtype list
4564 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4565 break;
4566
4567 case 0x10: // Road Type flags
4568 case 0x16: // Map colour
4569 case 0x1A: // Sort order
4570 buf->ReadByte();
4571 break;
4572
4573 case 0x17: // Introduction date
4574 buf->ReadDWord();
4575 break;
4576
4577 default:
4578 ret = CIR_UNKNOWN;
4579 break;
4580 }
4581 }
4582
4583 return ret;
4584 }
4585
4586 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4587 {
4588 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4589 }
4590
4591 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4592 {
4593 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4594 }
4595
4596 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader *buf)
4597 {
4598 ChangeInfoResult ret = CIR_SUCCESS;
4599
4600 if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4601 grfmsg(1, "AirportTileChangeInfo: Too many airport tiles loaded (%u), max (%u). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4602 return CIR_INVALID_ID;
4603 }
4604
4605 /* Allocate airport tile specs if they haven't been allocated already. */
4606 if (_cur.grffile->airtspec == nullptr) {
4607 _cur.grffile->airtspec = CallocT<AirportTileSpec*>(NUM_AIRPORTTILES_PER_GRF);
4608 }
4609
4610 for (int i = 0; i < numinfo; i++) {
4611 AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i];
4612
4613 if (prop != 0x08 && tsp == nullptr) {
4614 grfmsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile %u. Ignoring.", airtid + i);
4615 return CIR_INVALID_ID;
4616 }
4617
4618 switch (prop) {
4619 case 0x08: { // Substitute airport tile type
4620 AirportTileSpec **tilespec = &_cur.grffile->airtspec[airtid + i];
4621 byte subs_id = buf->ReadByte();
4622
4623 if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4624 /* The substitute id must be one of the original airport tiles. */
4625 grfmsg(2, "AirportTileChangeInfo: Attempt to use new airport tile %u as substitute airport tile for %u. Ignoring.", subs_id, airtid + i);
4626 continue;
4627 }
4628
4629 /* Allocate space for this airport tile. */
4630 if (*tilespec == nullptr) {
4631 *tilespec = CallocT<AirportTileSpec>(1);
4632 tsp = *tilespec;
4633
4634 memcpy(tsp, AirportTileSpec::Get(subs_id), sizeof(AirportTileSpec));
4635 tsp->enabled = true;
4636
4637 tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
4638
4639 tsp->grf_prop.local_id = airtid + i;
4640 tsp->grf_prop.subst_id = subs_id;
4641 tsp->grf_prop.grffile = _cur.grffile;
4642 _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4643 }
4644 break;
4645 }
4646
4647 case 0x09: { // Airport tile override
4648 byte override = buf->ReadByte();
4649
4650 /* The airport tile being overridden must be an original airport tile. */
4651 if (override >= NEW_AIRPORTTILE_OFFSET) {
4652 grfmsg(2, "AirportTileChangeInfo: Attempt to override new airport tile %u with airport tile id %u. Ignoring.", override, airtid + i);
4653 continue;
4654 }
4655
4656 _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4657 break;
4658 }
4659
4660 case 0x0E: // Callback mask
4661 tsp->callback_mask = buf->ReadByte();
4662 break;
4663
4664 case 0x0F: // Animation information
4665 tsp->animation.frames = buf->ReadByte();
4666 tsp->animation.status = buf->ReadByte();
4667 break;
4668
4669 case 0x10: // Animation speed
4670 tsp->animation.speed = buf->ReadByte();
4671 break;
4672
4673 case 0x11: // Animation triggers
4674 tsp->animation.triggers = buf->ReadByte();
4675 break;
4676
4677 default:
4678 ret = CIR_UNKNOWN;
4679 break;
4680 }
4681 }
4682
4683 return ret;
4684 }
4685
4686 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8 feature, uint8 property)
4687 {
4688 switch (cir) {
4689 default: NOT_REACHED();
4690
4691 case CIR_DISABLED:
4692 /* Error has already been printed; just stop parsing */
4693 return true;
4694
4695 case CIR_SUCCESS:
4696 return false;
4697
4698 case CIR_UNHANDLED:
4699 grfmsg(1, "%s: Ignoring property 0x%02X of feature 0x%02X (not implemented)", caller, property, feature);
4700 return false;
4701
4702 case CIR_UNKNOWN:
4703 grfmsg(0, "%s: Unknown property 0x%02X of feature 0x%02X, disabling", caller, property, feature);
4704 FALLTHROUGH;
4705
4706 case CIR_INVALID_ID: {
4707 /* No debug message for an invalid ID, as it has already been output */
4708 GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4709 if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4710 return true;
4711 }
4712 }
4713 }
4714
4715 /* Action 0x00 */
4716 static void FeatureChangeInfo(ByteReader *buf)
4717 {
4718 /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4719 *
4720 * B feature
4721 * B num-props how many properties to change per vehicle/station
4722 * B num-info how many vehicles/stations to change
4723 * E id ID of first vehicle/station to change, if num-info is
4724 * greater than one, this one and the following
4725 * vehicles/stations will be changed
4726 * B property what property to change, depends on the feature
4727 * V new-info new bytes of info (variable size; depends on properties) */
4728
4729 static const VCI_Handler handler[] = {
4730 /* GSF_TRAINS */ RailVehicleChangeInfo,
4731 /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4732 /* GSF_SHIPS */ ShipVehicleChangeInfo,
4733 /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4734 /* GSF_STATIONS */ StationChangeInfo,
4735 /* GSF_CANALS */ CanalChangeInfo,
4736 /* GSF_BRIDGES */ BridgeChangeInfo,
4737 /* GSF_HOUSES */ TownHouseChangeInfo,
4738 /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4739 /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4740 /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4741 /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4742 /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4743 /* GSF_AIRPORTS */ AirportChangeInfo,
4744 /* GSF_SIGNALS */ nullptr,
4745 /* GSF_OBJECTS */ ObjectChangeInfo,
4746 /* GSF_RAILTYPES */ RailTypeChangeInfo,
4747 /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4748 /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4749 /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4750 };
4751 static_assert(GSF_END == lengthof(handler));
4752
4753 uint8 feature = buf->ReadByte();
4754 uint8 numprops = buf->ReadByte();
4755 uint numinfo = buf->ReadByte();
4756 uint engine = buf->ReadExtendedByte();
4757
4758 if (feature >= GSF_END) {
4759 grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4760 return;
4761 }
4762
4763 grfmsg(6, "FeatureChangeInfo: Feature 0x%02X, %d properties, to apply to %d+%d",
4764 feature, numprops, engine, numinfo);
4765
4766 if (handler[feature] == nullptr) {
4767 if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4768 return;
4769 }
4770
4771 /* Mark the feature as used by the grf */
4772 SetBit(_cur.grffile->grf_features, feature);
4773
4774 while (numprops-- && buf->HasData()) {
4775 uint8 prop = buf->ReadByte();
4776
4777 ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4778 if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4779 }
4780 }
4781
4782 /* Action 0x00 (GLS_SAFETYSCAN) */
4783 static void SafeChangeInfo(ByteReader *buf)
4784 {
4785 uint8 feature = buf->ReadByte();
4786 uint8 numprops = buf->ReadByte();
4787 uint numinfo = buf->ReadByte();
4788 buf->ReadExtendedByte(); // id
4789
4790 if (feature == GSF_BRIDGES && numprops == 1) {
4791 uint8 prop = buf->ReadByte();
4792 /* Bridge property 0x0D is redefinition of sprite layout tables, which
4793 * is considered safe. */
4794 if (prop == 0x0D) return;
4795 } else if (feature == GSF_GLOBALVAR && numprops == 1) {
4796 uint8 prop = buf->ReadByte();
4797 /* Engine ID Mappings are safe, if the source is static */
4798 if (prop == 0x11) {
4799 bool is_safe = true;
4800 for (uint i = 0; i < numinfo; i++) {
4801 uint32 s = buf->ReadDWord();
4802 buf->ReadDWord(); // dest
4803 const GRFConfig *grfconfig = GetGRFConfig(s);
4804 if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
4805 is_safe = false;
4806 break;
4807 }
4808 }
4809 if (is_safe) return;
4810 }
4811 }
4812
4813 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
4814
4815 /* Skip remainder of GRF */
4816 _cur.skip_sprites = -1;
4817 }
4818
4819 /* Action 0x00 (GLS_RESERVE) */
4820 static void ReserveChangeInfo(ByteReader *buf)
4821 {
4822 uint8 feature = buf->ReadByte();
4823
4824 if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
4825
4826 uint8 numprops = buf->ReadByte();
4827 uint8 numinfo = buf->ReadByte();
4828 uint8 index = buf->ReadExtendedByte();
4829
4830 while (numprops-- && buf->HasData()) {
4831 uint8 prop = buf->ReadByte();
4832 ChangeInfoResult cir = CIR_SUCCESS;
4833
4834 switch (feature) {
4835 default: NOT_REACHED();
4836 case GSF_CARGOES:
4837 cir = CargoChangeInfo(index, numinfo, prop, buf);
4838 break;
4839
4840 case GSF_GLOBALVAR:
4841 cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
4842 break;
4843
4844 case GSF_RAILTYPES:
4845 cir = RailTypeReserveInfo(index, numinfo, prop, buf);
4846 break;
4847
4848 case GSF_ROADTYPES:
4849 cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
4850 break;
4851
4852 case GSF_TRAMTYPES:
4853 cir = TramTypeReserveInfo(index, numinfo, prop, buf);
4854 break;
4855 }
4856
4857 if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
4858 }
4859 }
4860
4861 /* Action 0x01 */
4862 static void NewSpriteSet(ByteReader *buf)
4863 {
4864 /* Basic format: <01> <feature> <num-sets> <num-ent>
4865 * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
4866 *
4867 * B feature feature to define sprites for
4868 * 0, 1, 2, 3: veh-type, 4: train stations
4869 * E first-set first sprite set to define
4870 * B num-sets number of sprite sets (extended byte in extended format)
4871 * E num-ent how many entries per sprite set
4872 * For vehicles, this is the number of different
4873 * vehicle directions in each sprite set
4874 * Set num-dirs=8, unless your sprites are symmetric.
4875 * In that case, use num-dirs=4.
4876 */
4877
4878 uint8 feature = buf->ReadByte();
4879 uint16 num_sets = buf->ReadByte();
4880 uint16 first_set = 0;
4881
4882 if (num_sets == 0 && buf->HasData(3)) {
4883 /* Extended Action1 format.
4884 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4885 first_set = buf->ReadExtendedByte();
4886 num_sets = buf->ReadExtendedByte();
4887 }
4888 uint16 num_ents = buf->ReadExtendedByte();
4889
4890 if (feature >= GSF_END) {
4891 _cur.skip_sprites = num_sets * num_ents;
4892 grfmsg(1, "NewSpriteSet: Unsupported feature 0x%02X, skipping %d sprites", feature, _cur.skip_sprites);
4893 return;
4894 }
4895
4896 _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
4897
4898 grfmsg(7, "New sprite set at %d of feature 0x%02X, consisting of %d sets with %d views each (total %d)",
4899 _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
4900 );
4901
4902 for (int i = 0; i < num_sets * num_ents; i++) {
4903 _cur.nfo_line++;
4904 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
4905 }
4906 }
4907
4908 /* Action 0x01 (SKIP) */
4909 static void SkipAct1(ByteReader *buf)
4910 {
4911 buf->ReadByte();
4912 uint16 num_sets = buf->ReadByte();
4913
4914 if (num_sets == 0 && buf->HasData(3)) {
4915 /* Extended Action1 format.
4916 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4917 buf->ReadExtendedByte(); // first_set
4918 num_sets = buf->ReadExtendedByte();
4919 }
4920 uint16 num_ents = buf->ReadExtendedByte();
4921
4922 _cur.skip_sprites = num_sets * num_ents;
4923
4924 grfmsg(3, "SkipAct1: Skipping %d sprites", _cur.skip_sprites);
4925 }
4926
4927 /* Helper function to either create a callback or link to a previously
4928 * defined spritegroup. */
4929 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 groupid)
4930 {
4931 if (HasBit(groupid, 15)) {
4932 assert(CallbackResultSpriteGroup::CanAllocateItem());
4933 return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
4934 }
4935
4936 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
4937 grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
4938 return nullptr;
4939 }
4940
4941 return _cur.spritegroups[groupid];
4942 }
4943
4952 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
4953 {
4954 if (HasBit(spriteid, 15)) {
4955 assert(CallbackResultSpriteGroup::CanAllocateItem());
4956 return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
4957 }
4958
4959 if (!_cur.IsValidSpriteSet(feature, spriteid)) {
4960 grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
4961 return nullptr;
4962 }
4963
4964 SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
4965 uint num_sprites = _cur.GetNumEnts(feature, spriteid);
4966
4967 /* Ensure that the sprites are loeded */
4968 assert(spriteset_start + num_sprites <= _cur.spriteid);
4969
4970 assert(ResultSpriteGroup::CanAllocateItem());
4971 return new ResultSpriteGroup(spriteset_start, num_sprites);
4972 }
4973
4974 /* Action 0x02 */
4975 static void NewSpriteGroup(ByteReader *buf)
4976 {
4977 /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
4978 *
4979 * B feature see action 1
4980 * B set-id ID of this particular definition
4981 * B type/num-entries
4982 * if 80 or greater, this is a randomized or variational
4983 * list definition, see below
4984 * otherwise it specifies a number of entries, the exact
4985 * meaning depends on the feature
4986 * V feature-specific-data (huge mess, don't even look it up --pasky) */
4987 const SpriteGroup *act_group = nullptr;
4988
4989 uint8 feature = buf->ReadByte();
4990 if (feature >= GSF_END) {
4991 grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
4992 return;
4993 }
4994
4995 uint8 setid = buf->ReadByte();
4996 uint8 type = buf->ReadByte();
4997
4998 /* Sprite Groups are created here but they are allocated from a pool, so
4999 * we do not need to delete anything if there is an exception from the
5000 * ByteReader. */
5001
5002 switch (type) {
5003 /* Deterministic Sprite Group */
5004 case 0x81: // Self scope, byte
5005 case 0x82: // Parent scope, byte
5006 case 0x85: // Self scope, word
5007 case 0x86: // Parent scope, word
5008 case 0x89: // Self scope, dword
5009 case 0x8A: // Parent scope, dword
5010 {
5011 byte varadjust;
5012 byte varsize;
5013
5014 assert(DeterministicSpriteGroup::CanAllocateItem());
5015 DeterministicSpriteGroup *group = new DeterministicSpriteGroup();
5016 group->nfo_line = _cur.nfo_line;
5017 act_group = group;
5018 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5019
5020 switch (GB(type, 2, 2)) {
5021 default: NOT_REACHED();
5022 case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5023 case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5024 case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5025 }
5026
5027 /* Loop through the var adjusts. Unfortunately we don't know how many we have
5028 * from the outset, so we shall have to keep reallocing. */
5029 do {
5030 DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5031
5032 /* The first var adjust doesn't have an operation specified, so we set it to add. */
5033 adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
5034 adjust.variable = buf->ReadByte();
5035 if (adjust.variable == 0x7E) {
5036 /* Link subroutine group */
5037 adjust.subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
5038 } else {
5039 adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf->ReadByte() : 0;
5040 }
5041
5042 varadjust = buf->ReadByte();
5043 adjust.shift_num = GB(varadjust, 0, 5);
5044 adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5045 adjust.and_mask = buf->ReadVarSize(varsize);
5046
5047 if (adjust.type != DSGA_TYPE_NONE) {
5048 adjust.add_val = buf->ReadVarSize(varsize);
5049 adjust.divmod_val = buf->ReadVarSize(varsize);
5050 } else {
5051 adjust.add_val = 0;
5052 adjust.divmod_val = 0;
5053 }
5054
5055 /* Continue reading var adjusts while bit 5 is set. */
5056 } while (HasBit(varadjust, 5));
5057
5058 std::vector<DeterministicSpriteGroupRange> ranges;
5059 ranges.resize(buf->ReadByte());
5060 for (uint i = 0; i < ranges.size(); i++) {
5061 ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5062 ranges[i].low = buf->ReadVarSize(varsize);
5063 ranges[i].high = buf->ReadVarSize(varsize);
5064 }
5065
5066 group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5067 group->error_group = ranges.size() > 0 ? ranges[0].group : group->default_group;
5068 /* nvar == 0 is a special case -- we turn our value into a callback result */
5069 group->calculated_result = ranges.size() == 0;
5070
5071 /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5072 std::vector<uint32> bounds;
5073 for (uint i = 0; i < ranges.size(); i++) {
5074 bounds.push_back(ranges[i].low);
5075 if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
5076 }
5077 std::sort(bounds.begin(), bounds.end());
5078 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5079
5080 std::vector<const SpriteGroup *> target;
5081 for (uint j = 0; j < bounds.size(); ++j) {
5082 uint32 v = bounds[j];
5083 const SpriteGroup *t = group->default_group;
5084 for (uint i = 0; i < ranges.size(); i++) {
5085 if (ranges[i].low <= v && v <= ranges[i].high) {
5086 t = ranges[i].group;
5087 break;
5088 }
5089 }
5090 target.push_back(t);
5091 }
5092 assert(target.size() == bounds.size());
5093
5094 for (uint j = 0; j < bounds.size(); ) {
5095 if (target[j] != group->default_group) {
5096 DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5097 r.group = target[j];
5098 r.low = bounds[j];
5099 while (j < bounds.size() && target[j] == r.group) {
5100 j++;
5101 }
5102 r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5103 } else {
5104 j++;
5105 }
5106 }
5107
5108 break;
5109 }
5110
5111 /* Randomized Sprite Group */
5112 case 0x80: // Self scope
5113 case 0x83: // Parent scope
5114 case 0x84: // Relative scope
5115 {
5116 assert(RandomizedSpriteGroup::CanAllocateItem());
5117 RandomizedSpriteGroup *group = new RandomizedSpriteGroup();
5118 group->nfo_line = _cur.nfo_line;
5119 act_group = group;
5120 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5121
5122 if (HasBit(type, 2)) {
5123 if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5124 group->count = buf->ReadByte();
5125 }
5126
5127 uint8 triggers = buf->ReadByte();
5128 group->triggers = GB(triggers, 0, 7);
5129 group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5130 group->lowest_randbit = buf->ReadByte();
5131
5132 byte num_groups = buf->ReadByte();
5133 if (!HasExactlyOneBit(num_groups)) {
5134 grfmsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5135 }
5136
5137 for (uint i = 0; i < num_groups; i++) {
5138 group->groups.push_back(GetGroupFromGroupID(setid, type, buf->ReadWord()));
5139 }
5140
5141 break;
5142 }
5143
5144 /* Neither a variable or randomized sprite group... must be a real group */
5145 default:
5146 {
5147 switch (feature) {
5148 case GSF_TRAINS:
5149 case GSF_ROADVEHICLES:
5150 case GSF_SHIPS:
5151 case GSF_AIRCRAFT:
5152 case GSF_STATIONS:
5153 case GSF_CANALS:
5154 case GSF_CARGOES:
5155 case GSF_AIRPORTS:
5156 case GSF_RAILTYPES:
5157 case GSF_ROADTYPES:
5158 case GSF_TRAMTYPES:
5159 {
5160 byte num_loaded = type;
5161 byte num_loading = buf->ReadByte();
5162
5163 if (!_cur.HasValidSpriteSets(feature)) {
5164 grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5165 return;
5166 }
5167
5168 grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u loaded, %u loading",
5169 setid, num_loaded, num_loading);
5170
5171 if (num_loaded + num_loading == 0) {
5172 grfmsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5173 break;
5174 }
5175
5176 if (num_loaded + num_loading == 1) {
5177 /* Avoid creating 'Real' sprite group if only one option. */
5178 uint16 spriteid = buf->ReadWord();
5179 act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5180 grfmsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset %u", spriteid);
5181 break;
5182 }
5183
5184 std::vector<uint16> loaded;
5185 std::vector<uint16> loading;
5186
5187 for (uint i = 0; i < num_loaded; i++) {
5188 loaded.push_back(buf->ReadWord());
5189 grfmsg(8, "NewSpriteGroup: + rg->loaded[%i] = subset %u", i, loaded[i]);
5190 }
5191
5192 for (uint i = 0; i < num_loading; i++) {
5193 loading.push_back(buf->ReadWord());
5194 grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, loading[i]);
5195 }
5196
5197 if (std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end() &&
5198 std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end() &&
5199 loaded[0] == loading[0])
5200 {
5201 /* Both lists only contain the same value, so don't create 'Real' sprite group */
5202 act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5203 grfmsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset %u", loaded[0]);
5204 break;
5205 }
5206
5207 assert(RealSpriteGroup::CanAllocateItem());
5208 RealSpriteGroup *group = new RealSpriteGroup();
5209 group->nfo_line = _cur.nfo_line;
5210 act_group = group;
5211
5212 for (uint16 spriteid : loaded) {
5213 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5214 group->loaded.push_back(t);
5215 }
5216
5217 for (uint16 spriteid : loading) {
5218 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5219 group->loading.push_back(t);
5220 }
5221
5222 break;
5223 }
5224
5225 case GSF_HOUSES:
5226 case GSF_AIRPORTTILES:
5227 case GSF_OBJECTS:
5228 case GSF_INDUSTRYTILES: {
5229 byte num_building_sprites = std::max((uint8)1, type);
5230
5231 assert(TileLayoutSpriteGroup::CanAllocateItem());
5232 TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup();
5233 group->nfo_line = _cur.nfo_line;
5234 act_group = group;
5235
5236 /* On error, bail out immediately. Temporary GRF data was already freed */
5237 if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5238 break;
5239 }
5240
5241 case GSF_INDUSTRIES: {
5242 if (type > 2) {
5243 grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
5244 break;
5245 }
5246
5247 assert(IndustryProductionSpriteGroup::CanAllocateItem());
5248 IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup();
5249 group->nfo_line = _cur.nfo_line;
5250 act_group = group;
5251 group->version = type;
5252 if (type == 0) {
5253 group->num_input = 3;
5254 for (uint i = 0; i < 3; i++) {
5255 group->subtract_input[i] = (int16)buf->ReadWord(); // signed
5256 }
5257 group->num_output = 2;
5258 for (uint i = 0; i < 2; i++) {
5259 group->add_output[i] = buf->ReadWord(); // unsigned
5260 }
5261 group->again = buf->ReadByte();
5262 } else if (type == 1) {
5263 group->num_input = 3;
5264 for (uint i = 0; i < 3; i++) {
5265 group->subtract_input[i] = buf->ReadByte();
5266 }
5267 group->num_output = 2;
5268 for (uint i = 0; i < 2; i++) {
5269 group->add_output[i] = buf->ReadByte();
5270 }
5271 group->again = buf->ReadByte();
5272 } else if (type == 2) {
5273 group->num_input = buf->ReadByte();
5274 if (group->num_input > lengthof(group->subtract_input)) {
5275 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5276 error->data = "too many inputs (max 16)";
5277 return;
5278 }
5279 for (uint i = 0; i < group->num_input; i++) {
5280 byte rawcargo = buf->ReadByte();
5281 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5282 if (cargo == CT_INVALID) {
5283 /* The mapped cargo is invalid. This is permitted at this point,
5284 * as long as the result is not used. Mark it invalid so this
5285 * can be tested later. */
5286 group->version = 0xFF;
5287 } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5288 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5289 error->data = "duplicate input cargo";
5290 return;
5291 }
5292 group->cargo_input[i] = cargo;
5293 group->subtract_input[i] = buf->ReadByte();
5294 }
5295 group->num_output = buf->ReadByte();
5296 if (group->num_output > lengthof(group->add_output)) {
5297 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5298 error->data = "too many outputs (max 16)";
5299 return;
5300 }
5301 for (uint i = 0; i < group->num_output; i++) {
5302 byte rawcargo = buf->ReadByte();
5303 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5304 if (cargo == CT_INVALID) {
5305 /* Mark this result as invalid to use */
5306 group->version = 0xFF;
5307 } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5308 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5309 error->data = "duplicate output cargo";
5310 return;
5311 }
5312 group->cargo_output[i] = cargo;
5313 group->add_output[i] = buf->ReadByte();
5314 }
5315 group->again = buf->ReadByte();
5316 } else {
5317 NOT_REACHED();
5318 }
5319 break;
5320 }
5321
5322 /* Loading of Tile Layout and Production Callback groups would happen here */
5323 default: grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5324 }
5325 }
5326 }
5327
5328 _cur.spritegroups[setid] = act_group;
5329 }
5330
5331 static CargoID TranslateCargo(uint8 feature, uint8 ctype)
5332 {
5333 if (feature == GSF_OBJECTS) {
5334 switch (ctype) {
5335 case 0: return 0;
5336 case 0xFF: return CT_PURCHASE_OBJECT;
5337 default:
5338 grfmsg(1, "TranslateCargo: Invalid cargo bitnum %d for objects, skipping.", ctype);
5339 return CT_INVALID;
5340 }
5341 }
5342 /* Special cargo types for purchase list and stations */
5343 if (feature == GSF_STATIONS && ctype == 0xFE) return CT_DEFAULT_NA;
5344 if (ctype == 0xFF) return CT_PURCHASE;
5345
5346 if (_cur.grffile->cargo_list.size() == 0) {
5347 /* No cargo table, so use bitnum values */
5348 if (ctype >= 32) {
5349 grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
5350 return CT_INVALID;
5351 }
5352
5353 for (const CargoSpec *cs : CargoSpec::Iterate()) {
5354 if (cs->bitnum == ctype) {
5355 grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, cs->Index());
5356 return cs->Index();
5357 }
5358 }
5359
5360 grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
5361 return CT_INVALID;
5362 }
5363
5364 /* Check if the cargo type is out of bounds of the cargo translation table */
5365 if (ctype >= _cur.grffile->cargo_list.size()) {
5366 grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5367 return CT_INVALID;
5368 }
5369
5370 /* Look up the cargo label from the translation table */
5371 CargoLabel cl = _cur.grffile->cargo_list[ctype];
5372 if (cl == 0) {
5373 grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
5374 return CT_INVALID;
5375 }
5376
5377 ctype = GetCargoIDByLabel(cl);
5378 if (ctype == CT_INVALID) {
5379 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));
5380 return CT_INVALID;
5381 }
5382
5383 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);
5384 return ctype;
5385 }
5386
5387
5388 static bool IsValidGroupID(uint16 groupid, const char *function)
5389 {
5390 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5391 grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
5392 return false;
5393 }
5394
5395 return true;
5396 }
5397
5398 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
5399 {
5400 static EngineID *last_engines;
5401 static uint last_engines_count;
5402 bool wagover = false;
5403
5404 /* Test for 'wagon override' flag */
5405 if (HasBit(idcount, 7)) {
5406 wagover = true;
5407 /* Strip off the flag */
5408 idcount = GB(idcount, 0, 7);
5409
5410 if (last_engines_count == 0) {
5411 grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5412 return;
5413 }
5414
5415 grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
5416 last_engines_count, idcount);
5417 } else {
5418 if (last_engines_count != idcount) {
5419 last_engines = ReallocT(last_engines, idcount);
5420 last_engines_count = idcount;
5421 }
5422 }
5423
5424 EngineID *engines = AllocaM(EngineID, idcount);
5425 for (uint i = 0; i < idcount; i++) {
5426 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5427 if (e == nullptr) {
5428 /* No engine could be allocated?!? Deal with it. Okay,
5429 * this might look bad. Also make sure this NewGRF
5430 * gets disabled, as a half loaded one is bad. */
5431 HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5432 return;
5433 }
5434
5435 engines[i] = e->index;
5436 if (!wagover) last_engines[i] = engines[i];
5437 }
5438
5439 uint8 cidcount = buf->ReadByte();
5440 for (uint c = 0; c < cidcount; c++) {
5441 uint8 ctype = buf->ReadByte();
5442 uint16 groupid = buf->ReadWord();
5443 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5444
5445 grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
5446
5447 ctype = TranslateCargo(feature, ctype);
5448 if (ctype == CT_INVALID) continue;
5449
5450 for (uint i = 0; i < idcount; i++) {
5451 EngineID engine = engines[i];
5452
5453 grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
5454
5455 if (wagover) {
5456 SetWagonOverrideSprites(engine, ctype, _cur.spritegroups[groupid], last_engines, last_engines_count);
5457 } else {
5458 SetCustomEngineSprites(engine, ctype, _cur.spritegroups[groupid]);
5459 }
5460 }
5461 }
5462
5463 uint16 groupid = buf->ReadWord();
5464 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5465
5466 grfmsg(8, "-- Default group id 0x%04X", groupid);
5467
5468 for (uint i = 0; i < idcount; i++) {
5469 EngineID engine = engines[i];
5470
5471 if (wagover) {
5472 SetWagonOverrideSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5473 } else {
5474 SetCustomEngineSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid]);
5475 SetEngineGRF(engine, _cur.grffile);
5476 }
5477 }
5478 }
5479
5480
5481 static void CanalMapSpriteGroup(ByteReader *buf, uint8 idcount)
5482 {
5483 CanalFeature *cfs = AllocaM(CanalFeature, idcount);
5484 for (uint i = 0; i < idcount; i++) {
5485 cfs[i] = (CanalFeature)buf->ReadByte();
5486 }
5487
5488 uint8 cidcount = buf->ReadByte();
5489 buf->Skip(cidcount * 3);
5490
5491 uint16 groupid = buf->ReadWord();
5492 if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5493
5494 for (uint i = 0; i < idcount; i++) {
5495 CanalFeature cf = cfs[i];
5496
5497 if (cf >= CF_END) {
5498 grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
5499 continue;
5500 }
5501
5502 _water_feature[cf].grffile = _cur.grffile;
5503 _water_feature[cf].group = _cur.spritegroups[groupid];
5504 }
5505 }
5506
5507
5508 static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
5509 {
5510 uint8 *stations = AllocaM(uint8, idcount);
5511 for (uint i = 0; i < idcount; i++) {
5512 stations[i] = buf->ReadByte();
5513 }
5514
5515 uint8 cidcount = buf->ReadByte();
5516 for (uint c = 0; c < cidcount; c++) {
5517 uint8 ctype = buf->ReadByte();
5518 uint16 groupid = buf->ReadWord();
5519 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5520
5521 ctype = TranslateCargo(GSF_STATIONS, ctype);
5522 if (ctype == CT_INVALID) continue;
5523
5524 for (uint i = 0; i < idcount; i++) {
5525 StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
5526
5527 if (statspec == nullptr) {
5528 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5529 continue;
5530 }
5531
5532 statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5533 }
5534 }
5535
5536 uint16 groupid = buf->ReadWord();
5537 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5538
5539 for (uint i = 0; i < idcount; i++) {
5540 StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
5541
5542 if (statspec == nullptr) {
5543 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5544 continue;
5545 }
5546
5547 if (statspec->grf_prop.grffile != nullptr) {
5548 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X mapped multiple times, skipping", stations[i]);
5549 continue;
5550 }
5551
5552 statspec->grf_prop.spritegroup[CT_DEFAULT] = _cur.spritegroups[groupid];
5553 statspec->grf_prop.grffile = _cur.grffile;
5554 statspec->grf_prop.local_id = stations[i];
5555 StationClass::Assign(statspec);
5556 }
5557 }
5558
5559
5560 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
5561 {
5562 uint8 *houses = AllocaM(uint8, idcount);
5563 for (uint i = 0; i < idcount; i++) {
5564 houses[i] = buf->ReadByte();
5565 }
5566
5567 /* Skip the cargo type section, we only care about the default group */
5568 uint8 cidcount = buf->ReadByte();
5569 buf->Skip(cidcount * 3);
5570
5571 uint16 groupid = buf->ReadWord();
5572 if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5573
5574 if (_cur.grffile->housespec == nullptr) {
5575 grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5576 return;
5577 }
5578
5579 for (uint i = 0; i < idcount; i++) {
5580 HouseSpec *hs = _cur.grffile->housespec[houses[i]];
5581
5582 if (hs == nullptr) {
5583 grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
5584 continue;
5585 }
5586
5587 hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5588 }
5589 }
5590
5591 static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
5592 {
5593 uint8 *industries = AllocaM(uint8, idcount);
5594 for (uint i = 0; i < idcount; i++) {
5595 industries[i] = buf->ReadByte();
5596 }
5597
5598 /* Skip the cargo type section, we only care about the default group */
5599 uint8 cidcount = buf->ReadByte();
5600 buf->Skip(cidcount * 3);
5601
5602 uint16 groupid = buf->ReadWord();
5603 if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5604
5605 if (_cur.grffile->industryspec == nullptr) {
5606 grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5607 return;
5608 }
5609
5610 for (uint i = 0; i < idcount; i++) {
5611 IndustrySpec *indsp = _cur.grffile->industryspec[industries[i]];
5612
5613 if (indsp == nullptr) {
5614 grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
5615 continue;
5616 }
5617
5618 indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5619 }
5620 }
5621
5622 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5623 {
5624 uint8 *indtiles = AllocaM(uint8, idcount);
5625 for (uint i = 0; i < idcount; i++) {
5626 indtiles[i] = buf->ReadByte();
5627 }
5628
5629 /* Skip the cargo type section, we only care about the default group */
5630 uint8 cidcount = buf->ReadByte();
5631 buf->Skip(cidcount * 3);
5632
5633 uint16 groupid = buf->ReadWord();
5634 if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5635
5636 if (_cur.grffile->indtspec == nullptr) {
5637 grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5638 return;
5639 }
5640
5641 for (uint i = 0; i < idcount; i++) {
5642 IndustryTileSpec *indtsp = _cur.grffile->indtspec[indtiles[i]];
5643
5644 if (indtsp == nullptr) {
5645 grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
5646 continue;
5647 }
5648
5649 indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5650 }
5651 }
5652
5653 static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
5654 {
5655 CargoID *cargoes = AllocaM(CargoID, idcount);
5656 for (uint i = 0; i < idcount; i++) {
5657 cargoes[i] = buf->ReadByte();
5658 }
5659
5660 /* Skip the cargo type section, we only care about the default group */
5661 uint8 cidcount = buf->ReadByte();
5662 buf->Skip(cidcount * 3);
5663
5664 uint16 groupid = buf->ReadWord();
5665 if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5666
5667 for (uint i = 0; i < idcount; i++) {
5668 CargoID cid = cargoes[i];
5669
5670 if (cid >= NUM_CARGO) {
5671 grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
5672 continue;
5673 }
5674
5675 CargoSpec *cs = CargoSpec::Get(cid);
5676 cs->grffile = _cur.grffile;
5677 cs->group = _cur.spritegroups[groupid];
5678 }
5679 }
5680
5681 static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
5682 {
5683 if (_cur.grffile->objectspec == nullptr) {
5684 grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5685 return;
5686 }
5687
5688 uint8 *objects = AllocaM(uint8, idcount);
5689 for (uint i = 0; i < idcount; i++) {
5690 objects[i] = buf->ReadByte();
5691 }
5692
5693 uint8 cidcount = buf->ReadByte();
5694 for (uint c = 0; c < cidcount; c++) {
5695 uint8 ctype = buf->ReadByte();
5696 uint16 groupid = buf->ReadWord();
5697 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5698
5699 ctype = TranslateCargo(GSF_OBJECTS, ctype);
5700 if (ctype == CT_INVALID) continue;
5701
5702 for (uint i = 0; i < idcount; i++) {
5703 ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5704
5705 if (spec == nullptr) {
5706 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5707 continue;
5708 }
5709
5710 spec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5711 }
5712 }
5713
5714 uint16 groupid = buf->ReadWord();
5715 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5716
5717 for (uint i = 0; i < idcount; i++) {
5718 ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5719
5720 if (spec == nullptr) {
5721 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5722 continue;
5723 }
5724
5725 if (spec->grf_prop.grffile != nullptr) {
5726 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X mapped multiple times, skipping", objects[i]);
5727 continue;
5728 }
5729
5730 spec->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5731 spec->grf_prop.grffile = _cur.grffile;
5732 spec->grf_prop.local_id = objects[i];
5733 }
5734 }
5735
5736 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8 idcount)
5737 {
5738 uint8 *railtypes = AllocaM(uint8, idcount);
5739 for (uint i = 0; i < idcount; i++) {
5740 uint8 id = buf->ReadByte();
5741 railtypes[i] = id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE;
5742 }
5743
5744 uint8 cidcount = buf->ReadByte();
5745 for (uint c = 0; c < cidcount; c++) {
5746 uint8 ctype = buf->ReadByte();
5747 uint16 groupid = buf->ReadWord();
5748 if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5749
5750 if (ctype >= RTSG_END) continue;
5751
5752 extern RailtypeInfo _railtypes[RAILTYPE_END];
5753 for (uint i = 0; i < idcount; i++) {
5754 if (railtypes[i] != INVALID_RAILTYPE) {
5755 RailtypeInfo *rti = &_railtypes[railtypes[i]];
5756
5757 rti->grffile[ctype] = _cur.grffile;
5758 rti->group[ctype] = _cur.spritegroups[groupid];
5759 }
5760 }
5761 }
5762
5763 /* Railtypes do not use the default group. */
5764 buf->ReadWord();
5765 }
5766
5767 static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8 idcount, RoadTramType rtt)
5768 {
5769 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5770
5771 uint8 *roadtypes = AllocaM(uint8, idcount);
5772 for (uint i = 0; i < idcount; i++) {
5773 uint8 id = buf->ReadByte();
5774 roadtypes[i] = id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE;
5775 }
5776
5777 uint8 cidcount = buf->ReadByte();
5778 for (uint c = 0; c < cidcount; c++) {
5779 uint8 ctype = buf->ReadByte();
5780 uint16 groupid = buf->ReadWord();
5781 if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
5782
5783 if (ctype >= ROTSG_END) continue;
5784
5785 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
5786 for (uint i = 0; i < idcount; i++) {
5787 if (roadtypes[i] != INVALID_ROADTYPE) {
5788 RoadTypeInfo *rti = &_roadtypes[roadtypes[i]];
5789
5790 rti->grffile[ctype] = _cur.grffile;
5791 rti->group[ctype] = _cur.spritegroups[groupid];
5792 }
5793 }
5794 }
5795
5796 /* Roadtypes do not use the default group. */
5797 buf->ReadWord();
5798 }
5799
5800 static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
5801 {
5802 uint8 *airports = AllocaM(uint8, idcount);
5803 for (uint i = 0; i < idcount; i++) {
5804 airports[i] = buf->ReadByte();
5805 }
5806
5807 /* Skip the cargo type section, we only care about the default group */
5808 uint8 cidcount = buf->ReadByte();
5809 buf->Skip(cidcount * 3);
5810
5811 uint16 groupid = buf->ReadWord();
5812 if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
5813
5814 if (_cur.grffile->airportspec == nullptr) {
5815 grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
5816 return;
5817 }
5818
5819 for (uint i = 0; i < idcount; i++) {
5820 AirportSpec *as = _cur.grffile->airportspec[airports[i]];
5821
5822 if (as == nullptr) {
5823 grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
5824 continue;
5825 }
5826
5827 as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5828 }
5829 }
5830
5831 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5832 {
5833 uint8 *airptiles = AllocaM(uint8, idcount);
5834 for (uint i = 0; i < idcount; i++) {
5835 airptiles[i] = buf->ReadByte();
5836 }
5837
5838 /* Skip the cargo type section, we only care about the default group */
5839 uint8 cidcount = buf->ReadByte();
5840 buf->Skip(cidcount * 3);
5841
5842 uint16 groupid = buf->ReadWord();
5843 if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
5844
5845 if (_cur.grffile->airtspec == nullptr) {
5846 grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
5847 return;
5848 }
5849
5850 for (uint i = 0; i < idcount; i++) {
5851 AirportTileSpec *airtsp = _cur.grffile->airtspec[airptiles[i]];
5852
5853 if (airtsp == nullptr) {
5854 grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
5855 continue;
5856 }
5857
5858 airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5859 }
5860 }
5861
5862
5863 /* Action 0x03 */
5864 static void FeatureMapSpriteGroup(ByteReader *buf)
5865 {
5866 /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
5867 * id-list := [<id>] [id-list]
5868 * cargo-list := <cargo-type> <cid> [cargo-list]
5869 *
5870 * B feature see action 0
5871 * B n-id bits 0-6: how many IDs this definition applies to
5872 * bit 7: if set, this is a wagon override definition (see below)
5873 * B ids the IDs for which this definition applies
5874 * B num-cid number of cargo IDs (sprite group IDs) in this definition
5875 * can be zero, in that case the def-cid is used always
5876 * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
5877 * W cid cargo ID (sprite group ID) for this type of cargo
5878 * W def-cid default cargo ID (sprite group ID) */
5879
5880 uint8 feature = buf->ReadByte();
5881 uint8 idcount = buf->ReadByte();
5882
5883 if (feature >= GSF_END) {
5884 grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5885 return;
5886 }
5887
5888 /* If idcount is zero, this is a feature callback */
5889 if (idcount == 0) {
5890 /* Skip number of cargo ids? */
5891 buf->ReadByte();
5892 uint16 groupid = buf->ReadWord();
5893 if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
5894
5895 grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x%02X", feature);
5896
5897 AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
5898 return;
5899 }
5900
5901 /* Mark the feature as used by the grf (generic callbacks do not count) */
5902 SetBit(_cur.grffile->grf_features, feature);
5903
5904 grfmsg(6, "FeatureMapSpriteGroup: Feature 0x%02X, %d ids", feature, idcount);
5905
5906 switch (feature) {
5907 case GSF_TRAINS:
5908 case GSF_ROADVEHICLES:
5909 case GSF_SHIPS:
5910 case GSF_AIRCRAFT:
5911 VehicleMapSpriteGroup(buf, feature, idcount);
5912 return;
5913
5914 case GSF_CANALS:
5915 CanalMapSpriteGroup(buf, idcount);
5916 return;
5917
5918 case GSF_STATIONS:
5919 StationMapSpriteGroup(buf, idcount);
5920 return;
5921
5922 case GSF_HOUSES:
5923 TownHouseMapSpriteGroup(buf, idcount);
5924 return;
5925
5926 case GSF_INDUSTRIES:
5927 IndustryMapSpriteGroup(buf, idcount);
5928 return;
5929
5930 case GSF_INDUSTRYTILES:
5931 IndustrytileMapSpriteGroup(buf, idcount);
5932 return;
5933
5934 case GSF_CARGOES:
5935 CargoMapSpriteGroup(buf, idcount);
5936 return;
5937
5938 case GSF_AIRPORTS:
5939 AirportMapSpriteGroup(buf, idcount);
5940 return;
5941
5942 case GSF_OBJECTS:
5943 ObjectMapSpriteGroup(buf, idcount);
5944 break;
5945
5946 case GSF_RAILTYPES:
5947 RailTypeMapSpriteGroup(buf, idcount);
5948 break;
5949
5950 case GSF_ROADTYPES:
5951 RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
5952 break;
5953
5954 case GSF_TRAMTYPES:
5955 RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
5956 break;
5957
5958 case GSF_AIRPORTTILES:
5959 AirportTileMapSpriteGroup(buf, idcount);
5960 return;
5961
5962 default:
5963 grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5964 return;
5965 }
5966 }
5967
5968 /* Action 0x04 */
5969 static void FeatureNewName(ByteReader *buf)
5970 {
5971 /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
5972 *
5973 * B veh-type see action 0 (as 00..07, + 0A
5974 * But IF veh-type = 48, then generic text
5975 * B language-id If bit 6 is set, This is the extended language scheme,
5976 * with up to 64 language.
5977 * Otherwise, it is a mapping where set bits have meaning
5978 * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
5979 * Bit 7 set means this is a generic text, not a vehicle one (or else)
5980 * B num-veh number of vehicles which are getting a new name
5981 * B/W offset number of the first vehicle that gets a new name
5982 * Byte : ID of vehicle to change
5983 * Word : ID of string to change/add
5984 * S data new texts, each of them zero-terminated, after
5985 * which the next name begins. */
5986
5987 bool new_scheme = _cur.grffile->grf_version >= 7;
5988
5989 uint8 feature = buf->ReadByte();
5990 if (feature >= GSF_END && feature != 0x48) {
5991 grfmsg(1, "FeatureNewName: Unsupported feature 0x%02X, skipping", feature);
5992 return;
5993 }
5994
5995 uint8 lang = buf->ReadByte();
5996 uint8 num = buf->ReadByte();
5997 bool generic = HasBit(lang, 7);
5998 uint16 id;
5999 if (generic) {
6000 id = buf->ReadWord();
6001 } else if (feature <= GSF_AIRCRAFT) {
6002 id = buf->ReadExtendedByte();
6003 } else {
6004 id = buf->ReadByte();
6005 }
6006
6007 ClrBit(lang, 7);
6008
6009 uint16 endid = id + num;
6010
6011 grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature 0x%02X) in language 0x%02X",
6012 id, endid, feature, lang);
6013
6014 for (; id < endid && buf->HasData(); id++) {
6015 const char *name = buf->ReadString();
6016 grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
6017
6018 switch (feature) {
6019 case GSF_TRAINS:
6020 case GSF_ROADVEHICLES:
6021 case GSF_SHIPS:
6022 case GSF_AIRCRAFT:
6023 if (!generic) {
6024 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6025 if (e == nullptr) break;
6026 StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6027 e->info.string_id = string;
6028 } else {
6029 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6030 }
6031 break;
6032
6033 default:
6034 if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0xE000)) {
6035 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6036 break;
6037 }
6038
6039 switch (GB(id, 8, 8)) {
6040 case 0xC4: // Station class name
6041 if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6042 grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6043 } else {
6044 StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
6045 StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6046 }
6047 break;
6048
6049 case 0xC5: // Station name
6050 if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6051 grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6052 } else {
6053 _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6054 }
6055 break;
6056
6057 case 0xC7: // Airporttile name
6058 if (_cur.grffile->airtspec == nullptr || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6059 grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
6060 } else {
6061 _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6062 }
6063 break;
6064
6065 case 0xC9: // House name
6066 if (_cur.grffile->housespec == nullptr || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6067 grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
6068 } else {
6069 _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6070 }
6071 break;
6072
6073 default:
6074 grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
6075 break;
6076 }
6077 break;
6078 }
6079 }
6080 }
6081
6090 static uint16 SanitizeSpriteOffset(uint16& num, uint16 offset, int max_sprites, const char *name)
6091 {
6092
6093 if (offset >= max_sprites) {
6094 grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
6095 uint orig_num = num;
6096 num = 0;
6097 return orig_num;
6098 }
6099
6100 if (offset + num > max_sprites) {
6101 grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
6102 uint orig_num = num;
6103 num = std::max(max_sprites - offset, 0);
6104 return orig_num - num;
6105 }
6106
6107 return 0;
6108 }
6109
6110
6112 enum Action5BlockType {
6113 A5BLOCK_FIXED,
6114 A5BLOCK_ALLOW_OFFSET,
6115 A5BLOCK_INVALID,
6116 };
6118 struct Action5Type {
6119 Action5BlockType block_type;
6120 SpriteID sprite_base;
6121 uint16 min_sprites;
6122 uint16 max_sprites;
6123 const char *name;
6124 };
6125
6127 static const Action5Type _action5_types[] = {
6128 /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6129 /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6130 /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6131 /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6132 /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6133 /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6134 /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6135 /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6136 /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6137 /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6138 /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6139 /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6140 /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6141 /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6142 /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6143 /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6144 /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6145 /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6146 /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6147 /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6148 /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6149 /* 0x14 */ { A5BLOCK_ALLOW_OFFSET, SPR_FLAGS_BASE, 1, FLAGS_SPRITE_COUNT, "Flag graphics" },
6150 /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6151 /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6152 /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6153 /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6154 };
6155
6156 /* Action 0x05 */
6157 static void GraphicsNew(ByteReader *buf)
6158 {
6159 /* <05> <graphics-type> <num-sprites> <other data...>
6160 *
6161 * B graphics-type What set of graphics the sprites define.
6162 * E num-sprites How many sprites are in this set?
6163 * V other data Graphics type specific data. Currently unused. */
6164
6165 uint8 type = buf->ReadByte();
6166 uint16 num = buf->ReadExtendedByte();
6167 uint16 offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
6168 ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6169
6170 if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6171 /* Special not-TTDP-compatible case used in openttd.grf
6172 * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6173 grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6174 LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6175 LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6176 LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6177 LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6178 LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6179 LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6180 LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6181 LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6182 LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6183 LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6184 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
6185 return;
6186 }
6187
6188 /* Supported type? */
6189 if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6190 grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
6191 _cur.skip_sprites = num;
6192 return;
6193 }
6194
6195 const Action5Type *action5_type = &_action5_types[type];
6196
6197 /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6198 * except for the long version of the shore type:
6199 * Ignore offset if not allowed */
6200 if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6201 grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6202 offset = 0;
6203 }
6204
6205 /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6206 * This does not make sense, if <offset> is allowed */
6207 if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6208 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);
6209 _cur.skip_sprites = num;
6210 return;
6211 }
6212
6213 /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6214 uint16 skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6215 SpriteID replace = action5_type->sprite_base + offset;
6216
6217 /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6218 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);
6219
6220 if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
6221
6222 if (type == 0x0B) {
6223 static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6224 static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6225 if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6226 if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6227 }
6228
6229 for (; num > 0; num--) {
6230 _cur.nfo_line++;
6231 LoadNextSprite(replace == 0 ? _cur.spriteid++ : replace++, *_cur.file, _cur.nfo_line);
6232 }
6233
6234 _cur.skip_sprites = skip_num;
6235 }
6236
6237 /* Action 0x05 (SKIP) */
6238 static void SkipAct5(ByteReader *buf)
6239 {
6240 /* Ignore type byte */
6241 buf->ReadByte();
6242
6243 /* Skip the sprites of this action */
6244 _cur.skip_sprites = buf->ReadExtendedByte();
6245
6246 grfmsg(3, "SkipAct5: Skipping %d sprites", _cur.skip_sprites);
6247 }
6248
6260 bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
6261 {
6262 switch (param) {
6263 case 0x00: // current date
6264 *value = std::max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
6265 return true;
6266
6267 case 0x01: // current year
6268 *value = Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
6269 return true;
6270
6271 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)
6272 YearMonthDay ymd;
6273 ConvertDateToYMD(_date, &ymd);
6274 Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1);
6275 *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16;
6276 return true;
6277 }
6278
6279 case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6280 *value = _settings_game.game_creation.landscape;
6281 return true;
6282
6283 case 0x06: // road traffic side, bit 4 clear=left, set=right
6284 *value = _settings_game.vehicle.road_side << 4;
6285 return true;
6286
6287 case 0x09: // date fraction
6288 *value = _date_fract * 885;
6289 return true;
6290
6291 case 0x0A: // animation counter
6292 *value = _tick_counter;
6293 return true;
6294
6295 case 0x0B: { // TTDPatch version
6296 uint major = 2;
6297 uint minor = 6;
6298 uint revision = 1; // special case: 2.0.1 is 2.0.10
6299 uint build = 1382;
6300 *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6301 return true;
6302 }
6303
6304 case 0x0D: // TTD Version, 00=DOS, 01=Windows
6305 *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6306 return true;
6307
6308 case 0x0E: // Y-offset for train sprites
6309 *value = _cur.grffile->traininfo_vehicle_pitch;
6310 return true;
6311
6312 case 0x0F: // Rail track type cost factors
6313 *value = 0;
6314 SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6315 if (_settings_game.vehicle.disable_elrails) {
6316 /* skip elrail multiplier - disabled */
6317 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6318 } else {
6319 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6320 /* Skip monorail multiplier - no space in result */
6321 }
6322 SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6323 return true;
6324
6325 case 0x11: // current rail tool type
6326 *value = 0; // constant fake value to avoid desync
6327 return true;
6328
6329 case 0x12: // Game mode
6330 *value = _game_mode;
6331 return true;
6332
6333 /* case 0x13: // Tile refresh offset to left not implemented */
6334 /* case 0x14: // Tile refresh offset to right not implemented */
6335 /* case 0x15: // Tile refresh offset upwards not implemented */
6336 /* case 0x16: // Tile refresh offset downwards not implemented */
6337 /* case 0x17: // temperate snow line not implemented */
6338
6339 case 0x1A: // Always -1
6340 *value = UINT_MAX;
6341 return true;
6342
6343 case 0x1B: // Display options
6344 *value = 0x3F; // constant fake value to avoid desync
6345 return true;
6346
6347 case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6348 *value = 1;
6349 return true;
6350
6351 case 0x1E: // Miscellaneous GRF features
6352 *value = _misc_grf_features;
6353
6354 /* Add the local flags */
6355 assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6356 if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6357 return true;
6358
6359 /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6360
6361 case 0x20: { // snow line height
6362 byte snowline = GetSnowLine();
6363 if (_settings_game.game_creation.landscape == LT_ARCTIC && snowline <= _settings_game.construction.map_height_limit) {
6364 *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6365 } else {
6366 /* No snow */
6367 *value = 0xFF;
6368 }
6369 return true;
6370 }
6371
6372 case 0x21: // OpenTTD version
6373 *value = _openttd_newgrf_version;
6374 return true;
6375
6376 case 0x22: // difficulty level
6377 *value = SP_CUSTOM;
6378 return true;
6379
6380 case 0x23: // long format date
6381 *value = _date;
6382 return true;
6383
6384 case 0x24: // long format year
6385 *value = _cur_year;
6386 return true;
6387
6388 default: return false;
6389 }
6390 }
6391
6392 static uint32 GetParamVal(byte param, uint32 *cond_val)
6393 {
6394 /* First handle variable common with VarAction2 */
6395 uint32 value;
6396 if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6397
6398 /* Non-common variable */
6399 switch (param) {
6400 case 0x84: { // GRF loading stage
6401 uint32 res = 0;
6402
6403 if (_cur.stage > GLS_INIT) SetBit(res, 0);
6404 if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6405 if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6406 return res;
6407 }
6408
6409 case 0x85: // TTDPatch flags, only for bit tests
6410 if (cond_val == nullptr) {
6411 /* Supported in Action 0x07 and 0x09, not 0x0D */
6412 return 0;
6413 } else {
6414 uint32 index = *cond_val / 0x20;
6415 uint32 param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6416 *cond_val %= 0x20;
6417 return param_val;
6418 }
6419
6420 case 0x88: // GRF ID check
6421 return 0;
6422
6423 /* case 0x99: Global ID offset not implemented */
6424
6425 default:
6426 /* GRF Parameter */
6427 if (param < 0x80) return _cur.grffile->GetParam(param);
6428
6429 /* In-game variable. */
6430 grfmsg(1, "Unsupported in-game variable 0x%02X", param);
6431 return UINT_MAX;
6432 }
6433 }
6434
6435 /* Action 0x06 */
6436 static void CfgApply(ByteReader *buf)
6437 {
6438 /* <06> <param-num> <param-size> <offset> ... <FF>
6439 *
6440 * B param-num Number of parameter to substitute (First = "zero")
6441 * Ignored if that parameter was not specified in newgrf.cfg
6442 * B param-size How many bytes to replace. If larger than 4, the
6443 * bytes of the following parameter are used. In that
6444 * case, nothing is applied unless *all* parameters
6445 * were specified.
6446 * B offset Offset into data from beginning of next sprite
6447 * to place where parameter is to be stored. */
6448
6449 /* Preload the next sprite */
6450 SpriteFile &file = *_cur.file;
6451 size_t pos = file.GetPos();
6452 uint32 num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6453 uint8 type = file.ReadByte();
6454 byte *preload_sprite = nullptr;
6455
6456 /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6457 if (type == 0xFF) {
6458 preload_sprite = MallocT<byte>(num);
6459 file.ReadBlock(preload_sprite, num);
6460 }
6461
6462 /* Reset the file position to the start of the next sprite */
6463 file.SeekTo(pos, SEEK_SET);
6464
6465 if (type != 0xFF) {
6466 grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6467 free(preload_sprite);
6468 return;
6469 }
6470
6471 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6472 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
6473 if (it != _grf_line_to_action6_sprite_override.end()) {
6474 free(preload_sprite);
6475 preload_sprite = _grf_line_to_action6_sprite_override[location];
6476 } else {
6477 _grf_line_to_action6_sprite_override[location] = preload_sprite;
6478 }
6479
6480 /* Now perform the Action 0x06 on our data. */
6481
6482 for (;;) {
6483 uint i;
6484 uint param_num;
6485 uint param_size;
6486 uint offset;
6487 bool add_value;
6488
6489 /* Read the parameter to apply. 0xFF indicates no more data to change. */
6490 param_num = buf->ReadByte();
6491 if (param_num == 0xFF) break;
6492
6493 /* Get the size of the parameter to use. If the size covers multiple
6494 * double words, sequential parameter values are used. */
6495 param_size = buf->ReadByte();
6496
6497 /* Bit 7 of param_size indicates we should add to the original value
6498 * instead of replacing it. */
6499 add_value = HasBit(param_size, 7);
6500 param_size = GB(param_size, 0, 7);
6501
6502 /* Where to apply the data to within the pseudo sprite data. */
6503 offset = buf->ReadExtendedByte();
6504
6505 /* If the parameter is a GRF parameter (not an internal variable) check
6506 * if it (and all further sequential parameters) has been defined. */
6507 if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6508 grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
6509 break;
6510 }
6511
6512 grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
6513
6514 bool carry = false;
6515 for (i = 0; i < param_size && offset + i < num; i++) {
6516 uint32 value = GetParamVal(param_num + i / 4, nullptr);
6517 /* Reset carry flag for each iteration of the variable (only really
6518 * matters if param_size is greater than 4) */
6519 if (i % 4 == 0) carry = false;
6520
6521 if (add_value) {
6522 uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6523 preload_sprite[offset + i] = GB(new_value, 0, 8);
6524 /* Check if the addition overflowed */
6525 carry = new_value >= 256;
6526 } else {
6527 preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6528 }
6529 }
6530 }
6531 }
6532
6542 static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
6543 {
6544 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6545 error->data = _cur.grfconfig->GetName();
6546 }
6547
6548 /* Action 0x07
6549 * Action 0x09 */
6550 static void SkipIf(ByteReader *buf)
6551 {
6552 /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6553 *
6554 * B param-num
6555 * B param-size
6556 * B condition-type
6557 * V value
6558 * B num-sprites */
6559 uint32 cond_val = 0;
6560 uint32 mask = 0;
6561 bool result;
6562
6563 uint8 param = buf->ReadByte();
6564 uint8 paramsize = buf->ReadByte();
6565 uint8 condtype = buf->ReadByte();
6566
6567 if (condtype < 2) {
6568 /* Always 1 for bit tests, the given value should be ignored. */
6569 paramsize = 1;
6570 }
6571
6572 switch (paramsize) {
6573 case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6574 case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6575 case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6576 case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6577 default: break;
6578 }
6579
6580 if (param < 0x80 && _cur.grffile->param_end <= param) {
6581 grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
6582 return;
6583 }
6584
6585 grfmsg(7, "SkipIf: Test condtype %d, param 0x%02X, condval 0x%08X", condtype, param, cond_val);
6586
6587 /* condtypes that do not use 'param' are always valid.
6588 * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6589 */
6590 if (condtype >= 0x0B) {
6591 /* Tests that ignore 'param' */
6592 switch (condtype) {
6593 case 0x0B: result = GetCargoIDByLabel(BSWAP32(cond_val)) == CT_INVALID;
6594 break;
6595 case 0x0C: result = GetCargoIDByLabel(BSWAP32(cond_val)) != CT_INVALID;
6596 break;
6597 case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6598 break;
6599 case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6600 break;
6601 case 0x0F: {
6602 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6603 result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6604 break;
6605 }
6606 case 0x10: {
6607 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6608 result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6609 break;
6610 }
6611 case 0x11: {
6612 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6613 result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6614 break;
6615 }
6616 case 0x12: {
6617 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6618 result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6619 break;
6620 }
6621 default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6622 }
6623 } else if (param == 0x88) {
6624 /* GRF ID checks */
6625
6626 GRFConfig *c = GetGRFConfig(cond_val, mask);
6627
6628 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6629 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
6630 c = nullptr;
6631 }
6632
6633 if (condtype != 10 && c == nullptr) {
6634 grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
6635 return;
6636 }
6637
6638 switch (condtype) {
6639 /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6640 case 0x06: // Is GRFID active?
6641 result = c->status == GCS_ACTIVATED;
6642 break;
6643
6644 case 0x07: // Is GRFID non-active?
6645 result = c->status != GCS_ACTIVATED;
6646 break;
6647
6648 case 0x08: // GRFID is not but will be active?
6649 result = c->status == GCS_INITIALISED;
6650 break;
6651
6652 case 0x09: // GRFID is or will be active?
6653 result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6654 break;
6655
6656 case 0x0A: // GRFID is not nor will be active
6657 /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6658 result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6659 break;
6660
6661 default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
6662 }
6663 } else {
6664 /* Tests that use 'param' and are not GRF ID checks. */
6665 uint32 param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6666 switch (condtype) {
6667 case 0x00: result = !!(param_val & (1 << cond_val));
6668 break;
6669 case 0x01: result = !(param_val & (1 << cond_val));
6670 break;
6671 case 0x02: result = (param_val & mask) == cond_val;
6672 break;
6673 case 0x03: result = (param_val & mask) != cond_val;
6674 break;
6675 case 0x04: result = (param_val & mask) < cond_val;
6676 break;
6677 case 0x05: result = (param_val & mask) > cond_val;
6678 break;
6679 default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6680 }
6681 }
6682
6683 if (!result) {
6684 grfmsg(2, "SkipIf: Not skipping sprites, test was false");
6685 return;
6686 }
6687
6688 uint8 numsprites = buf->ReadByte();
6689
6690 /* numsprites can be a GOTO label if it has been defined in the GRF
6691 * file. The jump will always be the first matching label that follows
6692 * the current nfo_line. If no matching label is found, the first matching
6693 * label in the file is used. */
6694 GRFLabel *choice = nullptr;
6695 for (GRFLabel *label = _cur.grffile->label; label != nullptr; label = label->next) {
6696 if (label->label != numsprites) continue;
6697
6698 /* Remember a goto before the current line */
6699 if (choice == nullptr) choice = label;
6700 /* If we find a label here, this is definitely good */
6701 if (label->nfo_line > _cur.nfo_line) {
6702 choice = label;
6703 break;
6704 }
6705 }
6706
6707 if (choice != nullptr) {
6708 grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
6709 _cur.file->SeekTo(choice->pos, SEEK_SET);
6710 _cur.nfo_line = choice->nfo_line;
6711 return;
6712 }
6713
6714 grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
6715 _cur.skip_sprites = numsprites;
6716 if (_cur.skip_sprites == 0) {
6717 /* Zero means there are no sprites to skip, so
6718 * we use -1 to indicate that all further
6719 * sprites should be skipped. */
6720 _cur.skip_sprites = -1;
6721
6722 /* If an action 8 hasn't been encountered yet, disable the grf. */
6723 if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6724 DisableGrf();
6725 }
6726 }
6727 }
6728
6729
6730 /* Action 0x08 (GLS_FILESCAN) */
6731 static void ScanInfo(ByteReader *buf)
6732 {
6733 uint8 grf_version = buf->ReadByte();
6734 uint32 grfid = buf->ReadDWord();
6735 const char *name = buf->ReadString();
6736
6737 _cur.grfconfig->ident.grfid = grfid;
6738
6739 if (grf_version < 2 || grf_version > 8) {
6740 SetBit(_cur.grfconfig->flags, GCF_INVALID);
6741 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);
6742 }
6743
6744 /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
6745 if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
6746
6747 AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
6748
6749 if (buf->HasData()) {
6750 const char *info = buf->ReadString();
6751 AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
6752 }
6753
6754 /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
6755 _cur.skip_sprites = -1;
6756 }
6757
6758 /* Action 0x08 */
6759 static void GRFInfo(ByteReader *buf)
6760 {
6761 /* <08> <version> <grf-id> <name> <info>
6762 *
6763 * B version newgrf version, currently 06
6764 * 4*B grf-id globally unique ID of this .grf file
6765 * S name name of this .grf set
6766 * S info string describing the set, and e.g. author and copyright */
6767
6768 uint8 version = buf->ReadByte();
6769 uint32 grfid = buf->ReadDWord();
6770 const char *name = buf->ReadString();
6771
6772 if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
6773 DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
6774 return;
6775 }
6776
6777 if (_cur.grffile->grfid != grfid) {
6778 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));
6779 _cur.grffile->grfid = grfid;
6780 }
6781
6782 _cur.grffile->grf_version = version;
6783 _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
6784
6785 /* Do swap the GRFID for displaying purposes since people expect that */
6786 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);
6787 }
6788
6789 /* Action 0x0A */
6790 static void SpriteReplace(ByteReader *buf)
6791 {
6792 /* <0A> <num-sets> <set1> [<set2> ...]
6793 * <set>: <num-sprites> <first-sprite>
6794 *
6795 * B num-sets How many sets of sprites to replace.
6796 * Each set:
6797 * B num-sprites How many sprites are in this set
6798 * W first-sprite First sprite number to replace */
6799
6800 uint8 num_sets = buf->ReadByte();
6801
6802 for (uint i = 0; i < num_sets; i++) {
6803 uint8 num_sprites = buf->ReadByte();
6804 uint16 first_sprite = buf->ReadWord();
6805
6806 grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
6807 i, num_sprites, first_sprite
6808 );
6809
6810 for (uint j = 0; j < num_sprites; j++) {
6811 int load_index = first_sprite + j;
6812 _cur.nfo_line++;
6813 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
6814
6815 /* Shore sprites now located at different addresses.
6816 * So detect when the old ones get replaced. */
6817 if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
6818 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
6819 }
6820 }
6821 }
6822 }
6823
6824 /* Action 0x0A (SKIP) */
6825 static void SkipActA(ByteReader *buf)
6826 {
6827 uint8 num_sets = buf->ReadByte();
6828
6829 for (uint i = 0; i < num_sets; i++) {
6830 /* Skip the sprites this replaces */
6831 _cur.skip_sprites += buf->ReadByte();
6832 /* But ignore where they go */
6833 buf->ReadWord();
6834 }
6835
6836 grfmsg(3, "SkipActA: Skipping %d sprites", _cur.skip_sprites);
6837 }
6838
6839 /* Action 0x0B */
6840 static void GRFLoadError(ByteReader *buf)
6841 {
6842 /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
6843 *
6844 * B severity 00: notice, continue loading grf file
6845 * 01: warning, continue loading grf file
6846 * 02: error, but continue loading grf file, and attempt
6847 * loading grf again when loading or starting next game
6848 * 03: error, abort loading and prevent loading again in
6849 * the future (only when restarting the patch)
6850 * B language-id see action 4, use 1F for built-in error messages
6851 * B message-id message to show, see below
6852 * S message for custom messages (message-id FF), text of the message
6853 * not present for built-in messages.
6854 * V data additional data for built-in (or custom) messages
6855 * B parnum parameter numbers to be shown in the message (maximum of 2) */
6856
6857 static const StringID msgstr[] = {
6858 STR_NEWGRF_ERROR_VERSION_NUMBER,
6859 STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
6860 STR_NEWGRF_ERROR_UNSET_SWITCH,
6861 STR_NEWGRF_ERROR_INVALID_PARAMETER,
6862 STR_NEWGRF_ERROR_LOAD_BEFORE,
6863 STR_NEWGRF_ERROR_LOAD_AFTER,
6864 STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
6865 };
6866
6867 static const StringID sevstr[] = {
6868 STR_NEWGRF_ERROR_MSG_INFO,
6869 STR_NEWGRF_ERROR_MSG_WARNING,
6870 STR_NEWGRF_ERROR_MSG_ERROR,
6871 STR_NEWGRF_ERROR_MSG_FATAL
6872 };
6873
6874 byte severity = buf->ReadByte();
6875 byte lang = buf->ReadByte();
6876 byte message_id = buf->ReadByte();
6877
6878 /* Skip the error if it isn't valid for the current language. */
6879 if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
6880
6881 /* Skip the error until the activation stage unless bit 7 of the severity
6882 * is set. */
6883 if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
6884 grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur.stage);
6885 return;
6886 }
6887 ClrBit(severity, 7);
6888
6889 if (severity >= lengthof(sevstr)) {
6890 grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
6891 severity = 2;
6892 } else if (severity == 3) {
6893 /* This is a fatal error, so make sure the GRF is deactivated and no
6894 * more of it gets loaded. */
6895 DisableGrf();
6896
6897 /* Make sure we show fatal errors, instead of silly infos from before */
6898 delete _cur.grfconfig->error;
6899 _cur.grfconfig->error = nullptr;
6900 }
6901
6902 if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
6903 grfmsg(7, "GRFLoadError: Invalid message id.");
6904 return;
6905 }
6906
6907 if (buf->Remaining() <= 1) {
6908 grfmsg(7, "GRFLoadError: No message data supplied.");
6909 return;
6910 }
6911
6912 /* For now we can only show one message per newgrf file. */
6913 if (_cur.grfconfig->error != nullptr) return;
6914
6915 GRFError *error = new GRFError(sevstr[severity]);
6916
6917 if (message_id == 0xFF) {
6918 /* This is a custom error message. */
6919 if (buf->HasData()) {
6920 const char *message = buf->ReadString();
6921
6922 error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
6923 } else {
6924 grfmsg(7, "GRFLoadError: No custom message supplied.");
6925 error->custom_message.clear();
6926 }
6927 } else {
6928 error->message = msgstr[message_id];
6929 }
6930
6931 if (buf->HasData()) {
6932 const char *data = buf->ReadString();
6933
6934 error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
6935 } else {
6936 grfmsg(7, "GRFLoadError: No message data supplied.");
6937 error->data.clear();
6938 }
6939
6940 /* Only two parameter numbers can be used in the string. */
6941 for (uint i = 0; i < lengthof(error->param_value) && buf->HasData(); i++) {
6942 uint param_number = buf->ReadByte();
6943 error->param_value[i] = _cur.grffile->GetParam(param_number);
6944 }
6945
6946 _cur.grfconfig->error = error;
6947 }
6948
6949 /* Action 0x0C */
6950 static void GRFComment(ByteReader *buf)
6951 {
6952 /* <0C> [<ignored...>]
6953 *
6954 * V ignored Anything following the 0C is ignored */
6955
6956 if (!buf->HasData()) return;
6957
6958 const char *text = buf->ReadString();
6959 grfmsg(2, "GRFComment: %s", text);
6960 }
6961
6962 /* Action 0x0D (GLS_SAFETYSCAN) */
6963 static void SafeParamSet(ByteReader *buf)
6964 {
6965 uint8 target = buf->ReadByte();
6966
6967 /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
6968 if (target < 0x80 || target == 0x9E) return;
6969
6970 /* GRM could be unsafe, but as here it can only happen after other GRFs
6971 * are loaded, it should be okay. If the GRF tried to use the slots it
6972 * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
6973 * sprites is considered safe. */
6974
6975 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
6976
6977 /* Skip remainder of GRF */
6978 _cur.skip_sprites = -1;
6979 }
6980
6981
6982 static uint32 GetPatchVariable(uint8 param)
6983 {
6984 switch (param) {
6985 /* start year - 1920 */
6986 case 0x0B: return std::max(_settings_game.game_creation.starting_year, ORIGINAL_BASE_YEAR) - ORIGINAL_BASE_YEAR;
6987
6988 /* freight trains weight factor */
6989 case 0x0E: return _settings_game.vehicle.freight_trains;
6990
6991 /* empty wagon speed increase */
6992 case 0x0F: return 0;
6993
6994 /* plane speed factor; our patch option is reversed from TTDPatch's,
6995 * the following is good for 1x, 2x and 4x (most common?) and...
6996 * well not really for 3x. */
6997 case 0x10:
6998 switch (_settings_game.vehicle.plane_speed) {
6999 default:
7000 case 4: return 1;
7001 case 3: return 2;
7002 case 2: return 2;
7003 case 1: return 4;
7004 }
7005
7006
7007 /* 2CC colourmap base sprite */
7008 case 0x11: return SPR_2CCMAP_BASE;
7009
7010 /* map size: format = -MABXYSS
7011 * M : the type of map
7012 * bit 0 : set : squared map. Bit 1 is now not relevant
7013 * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7014 * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7015 * clear : X is the bigger edge.
7016 * A : minimum edge(log2) of the map
7017 * B : maximum edge(log2) of the map
7018 * XY : edges(log2) of each side of the map.
7019 * SS : combination of both X and Y, thus giving the size(log2) of the map
7020 */
7021 case 0x13: {
7022 byte map_bits = 0;
7023 byte log_X = MapLogX() - 6; // subtraction is required to make the minimal size (64) zero based
7024 byte log_Y = MapLogY() - 6;
7025 byte max_edge = std::max(log_X, log_Y);
7026
7027 if (log_X == log_Y) { // we have a squared map, since both edges are identical
7028 SetBit(map_bits, 0);
7029 } else {
7030 if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7031 }
7032
7033 return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7034 (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7035 }
7036
7037 /* The maximum height of the map. */
7038 case 0x14:
7039 return _settings_game.construction.map_height_limit;
7040
7041 /* Extra foundations base sprite */
7042 case 0x15:
7043 return SPR_SLOPES_BASE;
7044
7045 /* Shore base sprite */
7046 case 0x16:
7047 return SPR_SHORE_BASE;
7048
7049 default:
7050 grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
7051 return 0;
7052 }
7053 }
7054
7055
7056 static uint32 PerformGRM(uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
7057 {
7058 uint start = 0;
7059 uint size = 0;
7060
7061 if (op == 6) {
7062 /* Return GRFID of set that reserved ID */
7063 return grm[_cur.grffile->GetParam(target)];
7064 }
7065
7066 /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7067 if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7068
7069 for (uint i = start; i < num_ids; i++) {
7070 if (grm[i] == 0) {
7071 size++;
7072 } else {
7073 if (op == 2 || op == 3) break;
7074 start = i + 1;
7075 size = 0;
7076 }
7077
7078 if (size == count) break;
7079 }
7080
7081 if (size == count) {
7082 /* Got the slot... */
7083 if (op == 0 || op == 3) {
7084 grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
7085 for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7086 }
7087 return start;
7088 }
7089
7090 /* Unable to allocate */
7091 if (op != 4 && op != 5) {
7092 /* Deactivate GRF */
7093 grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
7094 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7095 return UINT_MAX;
7096 }
7097
7098 grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
7099 return UINT_MAX;
7100 }
7101
7102
7104 static void ParamSet(ByteReader *buf)
7105 {
7106 /* <0D> <target> <operation> <source1> <source2> [<data>]
7107 *
7108 * B target parameter number where result is stored
7109 * B operation operation to perform, see below
7110 * B source1 first source operand
7111 * B source2 second source operand
7112 * D data data to use in the calculation, not necessary
7113 * if both source1 and source2 refer to actual parameters
7114 *
7115 * Operations
7116 * 00 Set parameter equal to source1
7117 * 01 Addition, source1 + source2
7118 * 02 Subtraction, source1 - source2
7119 * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7120 * 04 Signed multiplication, source1 * source2 (both signed)
7121 * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7122 * signed quantity; left shift if positive and right shift if
7123 * negative, source1 is unsigned)
7124 * 06 Signed bit shift, source1 by source2
7125 * (source2 like in 05, and source1 as well)
7126 */
7127
7128 uint8 target = buf->ReadByte();
7129 uint8 oper = buf->ReadByte();
7130 uint32 src1 = buf->ReadByte();
7131 uint32 src2 = buf->ReadByte();
7132
7133 uint32 data = 0;
7134 if (buf->Remaining() >= 4) data = buf->ReadDWord();
7135
7136 /* You can add 80 to the operation to make it apply only if the target
7137 * is not defined yet. In this respect, a parameter is taken to be
7138 * defined if any of the following applies:
7139 * - it has been set to any value in the newgrf(w).cfg parameter list
7140 * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7141 * an earlier action D */
7142 if (HasBit(oper, 7)) {
7143 if (target < 0x80 && target < _cur.grffile->param_end) {
7144 grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
7145 return;
7146 }
7147
7148 oper = GB(oper, 0, 7);
7149 }
7150
7151 if (src2 == 0xFE) {
7152 if (GB(data, 0, 8) == 0xFF) {
7153 if (data == 0x0000FFFF) {
7154 /* Patch variables */
7155 src1 = GetPatchVariable(src1);
7156 } else {
7157 /* GRF Resource Management */
7158 uint8 op = src1;
7159 uint8 feature = GB(data, 8, 8);
7160 uint16 count = GB(data, 16, 16);
7161
7162 if (_cur.stage == GLS_RESERVE) {
7163 if (feature == 0x08) {
7164 /* General sprites */
7165 if (op == 0) {
7166 /* Check if the allocated sprites will fit below the original sprite limit */
7167 if (_cur.spriteid + count >= 16384) {
7168 grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
7169 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7170 return;
7171 }
7172
7173 /* Reserve space at the current sprite ID */
7174 grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur.spriteid);
7175 _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
7176 _cur.spriteid += count;
7177 }
7178 }
7179 /* Ignore GRM result during reservation */
7180 src1 = 0;
7181 } else if (_cur.stage == GLS_ACTIVATION) {
7182 switch (feature) {
7183 case 0x00: // Trains
7184 case 0x01: // Road Vehicles
7185 case 0x02: // Ships
7186 case 0x03: // Aircraft
7187 if (!_settings_game.vehicle.dynamic_engines) {
7188 src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7189 if (_cur.skip_sprites == -1) return;
7190 } else {
7191 /* GRM does not apply for dynamic engine allocation. */
7192 switch (op) {
7193 case 2:
7194 case 3:
7195 src1 = _cur.grffile->GetParam(target);
7196 break;
7197
7198 default:
7199 src1 = 0;
7200 break;
7201 }
7202 }
7203 break;
7204
7205 case 0x08: // General sprites
7206 switch (op) {
7207 case 0:
7208 /* Return space reserved during reservation stage */
7209 src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
7210 grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
7211 break;
7212
7213 case 1:
7214 src1 = _cur.spriteid;
7215 break;
7216
7217 default:
7218 grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
7219 return;
7220 }
7221 break;
7222
7223 case 0x0B: // Cargo
7224 /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7225 src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7226 if (_cur.skip_sprites == -1) return;
7227 break;
7228
7229 default: grfmsg(1, "ParamSet: GRM: Unsupported feature 0x%X", feature); return;
7230 }
7231 } else {
7232 /* Ignore GRM during initialization */
7233 src1 = 0;
7234 }
7235 }
7236 } else {
7237 /* Read another GRF File's parameter */
7238 const GRFFile *file = GetFileByGRFID(data);
7239 GRFConfig *c = GetGRFConfig(data);
7240 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7241 /* Disable the read GRF if it is a static NewGRF. */
7242 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
7243 src1 = 0;
7244 } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7245 src1 = 0;
7246 } else if (src1 == 0xFE) {
7247 src1 = c->version;
7248 } else {
7249 src1 = file->GetParam(src1);
7250 }
7251 }
7252 } else {
7253 /* The source1 and source2 operands refer to the grf parameter number
7254 * like in action 6 and 7. In addition, they can refer to the special
7255 * variables available in action 7, or they can be FF to use the value
7256 * of <data>. If referring to parameters that are undefined, a value
7257 * of 0 is used instead. */
7258 src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7259 src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7260 }
7261
7262 uint32 res;
7263 switch (oper) {
7264 case 0x00:
7265 res = src1;
7266 break;
7267
7268 case 0x01:
7269 res = src1 + src2;
7270 break;
7271
7272 case 0x02:
7273 res = src1 - src2;
7274 break;
7275
7276 case 0x03:
7277 res = src1 * src2;
7278 break;
7279
7280 case 0x04:
7281 res = (int32)src1 * (int32)src2;
7282 break;
7283
7284 case 0x05:
7285 if ((int32)src2 < 0) {
7286 res = src1 >> -(int32)src2;
7287 } else {
7288 res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7289 }
7290 break;
7291
7292 case 0x06:
7293 if ((int32)src2 < 0) {
7294 res = (int32)src1 >> -(int32)src2;
7295 } else {
7296 res = (int32)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7297 }
7298 break;
7299
7300 case 0x07: // Bitwise AND
7301 res = src1 & src2;
7302 break;
7303
7304 case 0x08: // Bitwise OR
7305 res = src1 | src2;
7306 break;
7307
7308 case 0x09: // Unsigned division
7309 if (src2 == 0) {
7310 res = src1;
7311 } else {
7312 res = src1 / src2;
7313 }
7314 break;
7315
7316 case 0x0A: // Signed division
7317 if (src2 == 0) {
7318 res = src1;
7319 } else {
7320 res = (int32)src1 / (int32)src2;
7321 }
7322 break;
7323
7324 case 0x0B: // Unsigned modulo
7325 if (src2 == 0) {
7326 res = src1;
7327 } else {
7328 res = src1 % src2;
7329 }
7330 break;
7331
7332 case 0x0C: // Signed modulo
7333 if (src2 == 0) {
7334 res = src1;
7335 } else {
7336 res = (int32)src1 % (int32)src2;
7337 }
7338 break;
7339
7340 default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
7341 }
7342
7343 switch (target) {
7344 case 0x8E: // Y-Offset for train sprites
7345 _cur.grffile->traininfo_vehicle_pitch = res;
7346 break;
7347
7348 case 0x8F: { // Rail track type cost factors
7349 extern RailtypeInfo _railtypes[RAILTYPE_END];
7350 _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7351 if (_settings_game.vehicle.disable_elrails) {
7352 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7353 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7354 } else {
7355 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7356 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7357 }
7358 _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7359 break;
7360 }
7361
7362 /* not implemented */
7363 case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7364 case 0x94: // Tile refresh offset to right
7365 case 0x95: // Tile refresh offset upwards
7366 case 0x96: // Tile refresh offset downwards
7367 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
7368 case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7369 grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7370 break;
7371
7372 case 0x9E: // Miscellaneous GRF features
7373 /* Set train list engine width */
7374 _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7375 /* Remove the local flags from the global flags */
7376 ClrBit(res, GMB_TRAIN_WIDTH_32_PIXELS);
7377
7378 /* Only copy safe bits for static grfs */
7379 if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7380 uint32 safe_bits = 0;
7381 SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7382
7383 _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7384 } else {
7385 _misc_grf_features = res;
7386 }
7387 break;
7388
7389 case 0x9F: // locale-dependent settings
7390 grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7391 break;
7392
7393 default:
7394 if (target < 0x80) {
7395 _cur.grffile->param[target] = res;
7396 /* param is zeroed by default */
7397 if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7398 } else {
7399 grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
7400 }
7401 break;
7402 }
7403 }
7404
7405 /* Action 0x0E (GLS_SAFETYSCAN) */
7406 static void SafeGRFInhibit(ByteReader *buf)
7407 {
7408 /* <0E> <num> <grfids...>
7409 *
7410 * B num Number of GRFIDs that follow
7411 * D grfids GRFIDs of the files to deactivate */
7412
7413 uint8 num = buf->ReadByte();
7414
7415 for (uint i = 0; i < num; i++) {
7416 uint32 grfid = buf->ReadDWord();
7417
7418 /* GRF is unsafe it if tries to deactivate other GRFs */
7419 if (grfid != _cur.grfconfig->ident.grfid) {
7420 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7421
7422 /* Skip remainder of GRF */
7423 _cur.skip_sprites = -1;
7424
7425 return;
7426 }
7427 }
7428 }
7429
7430 /* Action 0x0E */
7431 static void GRFInhibit(ByteReader *buf)
7432 {
7433 /* <0E> <num> <grfids...>
7434 *
7435 * B num Number of GRFIDs that follow
7436 * D grfids GRFIDs of the files to deactivate */
7437
7438 uint8 num = buf->ReadByte();
7439
7440 for (uint i = 0; i < num; i++) {
7441 uint32 grfid = buf->ReadDWord();
7442 GRFConfig *file = GetGRFConfig(grfid);
7443
7444 /* Unset activation flag */
7445 if (file != nullptr && file != _cur.grfconfig) {
7446 grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
7447 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7448 error->data = _cur.grfconfig->GetName();
7449 }
7450 }
7451 }
7452
7454 static void FeatureTownName(ByteReader *buf)
7455 {
7456 /* <0F> <id> <style-name> <num-parts> <parts>
7457 *
7458 * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7459 * V style-name Name of the style (only for final definition)
7460 * B num-parts Number of parts in this definition
7461 * V parts The parts */
7462
7463 uint32 grfid = _cur.grffile->grfid;
7464
7465 GRFTownName *townname = AddGRFTownName(grfid);
7466
7467 byte id = buf->ReadByte();
7468 grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
7469
7470 if (HasBit(id, 7)) {
7471 /* Final definition */
7472 ClrBit(id, 7);
7473 bool new_scheme = _cur.grffile->grf_version >= 7;
7474
7475 byte lang = buf->ReadByte();
7476
7477 byte nb_gen = townname->nb_gen;
7478 do {
7479 ClrBit(lang, 7);
7480
7481 const char *name = buf->ReadString();
7482
7483 std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7484 grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name.c_str());
7485
7486 townname->name[nb_gen] = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7487
7488 lang = buf->ReadByte();
7489 } while (lang != 0);
7490 townname->id[nb_gen] = id;
7491 townname->nb_gen++;
7492 }
7493
7494 byte nb = buf->ReadByte();
7495 grfmsg(6, "FeatureTownName: %u parts", nb);
7496
7497 townname->nbparts[id] = nb;
7498 townname->partlist[id] = CallocT<NamePartList>(nb);
7499
7500 for (int i = 0; i < nb; i++) {
7501 byte nbtext = buf->ReadByte();
7502 townname->partlist[id][i].bitstart = buf->ReadByte();
7503 townname->partlist[id][i].bitcount = buf->ReadByte();
7504 townname->partlist[id][i].maxprob = 0;
7505 townname->partlist[id][i].partcount = nbtext;
7506 townname->partlist[id][i].parts = CallocT<NamePart>(nbtext);
7507 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);
7508
7509 for (int j = 0; j < nbtext; j++) {
7510 byte prob = buf->ReadByte();
7511
7512 if (HasBit(prob, 7)) {
7513 byte ref_id = buf->ReadByte();
7514
7515 if (townname->nbparts[ref_id] == 0) {
7516 grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
7517 DelGRFTownName(grfid);
7518 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7519 return;
7520 }
7521
7522 grfmsg(6, "FeatureTownName: part %d, text %d, uses intermediate definition 0x%02X (with probability %d)", i, j, ref_id, prob & 0x7F);
7523 townname->partlist[id][i].parts[j].data.id = ref_id;
7524 } else {
7525 const char *text = buf->ReadString();
7526 townname->partlist[id][i].parts[j].data.text = stredup(TranslateTTDPatchCodes(grfid, 0, false, text).c_str());
7527 grfmsg(6, "FeatureTownName: part %d, text %d, '%s' (with probability %d)", i, j, townname->partlist[id][i].parts[j].data.text, prob);
7528 }
7529 townname->partlist[id][i].parts[j].prob = prob;
7530 townname->partlist[id][i].maxprob += GB(prob, 0, 7);
7531 }
7532 grfmsg(6, "FeatureTownName: part %d, total probability %d", i, townname->partlist[id][i].maxprob);
7533 }
7534 }
7535
7537 static void DefineGotoLabel(ByteReader *buf)
7538 {
7539 /* <10> <label> [<comment>]
7540 *
7541 * B label The label to define
7542 * V comment Optional comment - ignored */
7543
7544 byte nfo_label = buf->ReadByte();
7545
7546 GRFLabel *label = MallocT<GRFLabel>(1);
7547 label->label = nfo_label;
7548 label->nfo_line = _cur.nfo_line;
7549 label->pos = _cur.file->GetPos();
7550 label->next = nullptr;
7551
7552 /* Set up a linked list of goto targets which we will search in an Action 0x7/0x9 */
7553 if (_cur.grffile->label == nullptr) {
7554 _cur.grffile->label = label;
7555 } else {
7556 /* Attach the label to the end of the list */
7557 GRFLabel *l;
7558 for (l = _cur.grffile->label; l->next != nullptr; l = l->next) {}
7559 l->next = label;
7560 }
7561
7562 grfmsg(2, "DefineGotoLabel: GOTO target with label 0x%02X", label->label);
7563 }
7564
7569 static void ImportGRFSound(SoundEntry *sound)
7570 {
7571 const GRFFile *file;
7572 uint32 grfid = _cur.file->ReadDword();
7573 SoundID sound_id = _cur.file->ReadWord();
7574
7575 file = GetFileByGRFID(grfid);
7576 if (file == nullptr || file->sound_offset == 0) {
7577 grfmsg(1, "ImportGRFSound: Source file not available");
7578 return;
7579 }
7580
7581 if (sound_id >= file->num_sounds) {
7582 grfmsg(1, "ImportGRFSound: Sound effect %d is invalid", sound_id);
7583 return;
7584 }
7585
7586 grfmsg(2, "ImportGRFSound: Copying sound %d (%d) from file %X", sound_id, file->sound_offset + sound_id, grfid);
7587
7588 *sound = *GetSound(file->sound_offset + sound_id);
7589
7590 /* Reset volume and priority, which TTDPatch doesn't copy */
7591 sound->volume = 128;
7592 sound->priority = 0;
7593 }
7594
7600 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7601 {
7602 /* Set default volume and priority */
7603 sound->volume = 0x80;
7604 sound->priority = 0;
7605
7606 if (offs != SIZE_MAX) {
7607 /* Sound is present in the NewGRF. */
7608 sound->file = _cur.file;
7609 sound->file_offset = offs;
7610 sound->grf_container_ver = _cur.file->GetContainerVersion();
7611 }
7612 }
7613
7614 /* Action 0x11 */
7615 static void GRFSound(ByteReader *buf)
7616 {
7617 /* <11> <num>
7618 *
7619 * W num Number of sound files that follow */
7620
7621 uint16 num = buf->ReadWord();
7622 if (num == 0) return;
7623
7624 SoundEntry *sound;
7625 if (_cur.grffile->sound_offset == 0) {
7626 _cur.grffile->sound_offset = GetNumSounds();
7627 _cur.grffile->num_sounds = num;
7628 sound = AllocateSound(num);
7629 } else {
7630 sound = GetSound(_cur.grffile->sound_offset);
7631 }
7632
7633 SpriteFile &file = *_cur.file;
7634 byte grf_container_version = file.GetContainerVersion();
7635 for (int i = 0; i < num; i++) {
7636 _cur.nfo_line++;
7637
7638 /* Check whether the index is in range. This might happen if multiple action 11 are present.
7639 * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7640 bool invalid = i >= _cur.grffile->num_sounds;
7641
7642 size_t offs = file.GetPos();
7643
7644 uint32 len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7645 byte type = file.ReadByte();
7646
7647 if (grf_container_version >= 2 && type == 0xFD) {
7648 /* Reference to sprite section. */
7649 if (invalid) {
7650 grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7651 file.SkipBytes(len);
7652 } else if (len != 4) {
7653 grfmsg(1, "GRFSound: Invalid sprite section import");
7654 file.SkipBytes(len);
7655 } else {
7656 uint32 id = file.ReadDword();
7657 if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7658 }
7659 continue;
7660 }
7661
7662 if (type != 0xFF) {
7663 grfmsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7664 file.SkipBytes(7);
7665 SkipSpriteData(*_cur.file, type, len - 8);
7666 continue;
7667 }
7668
7669 if (invalid) {
7670 grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7671 file.SkipBytes(len);
7672 }
7673
7674 byte action = file.ReadByte();
7675 switch (action) {
7676 case 0xFF:
7677 /* Allocate sound only in init stage. */
7678 if (_cur.stage == GLS_INIT) {
7679 if (grf_container_version >= 2) {
7680 grfmsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7681 } else {
7682 LoadGRFSound(offs, sound + i);
7683 }
7684 }
7685 file.SkipBytes(len - 1); // already read <action>
7686 break;
7687
7688 case 0xFE:
7689 if (_cur.stage == GLS_ACTIVATION) {
7690 /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7691 * importing sounds, so this is probably all wrong... */
7692 if (file.ReadByte() != 0) grfmsg(1, "GRFSound: Import type mismatch");
7693 ImportGRFSound(sound + i);
7694 } else {
7695 file.SkipBytes(len - 1); // already read <action>
7696 }
7697 break;
7698
7699 default:
7700 grfmsg(1, "GRFSound: Unexpected Action %x found, skipping", action);
7701 file.SkipBytes(len - 1); // already read <action>
7702 break;
7703 }
7704 }
7705 }
7706
7707 /* Action 0x11 (SKIP) */
7708 static void SkipAct11(ByteReader *buf)
7709 {
7710 /* <11> <num>
7711 *
7712 * W num Number of sound files that follow */
7713
7714 _cur.skip_sprites = buf->ReadWord();
7715
7716 grfmsg(3, "SkipAct11: Skipping %d sprites", _cur.skip_sprites);
7717 }
7718
7720 static void LoadFontGlyph(ByteReader *buf)
7721 {
7722 /* <12> <num_def> <font_size> <num_char> <base_char>
7723 *
7724 * B num_def Number of definitions
7725 * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7726 * B num_char Number of consecutive glyphs
7727 * W base_char First character index */
7728
7729 uint8 num_def = buf->ReadByte();
7730
7731 for (uint i = 0; i < num_def; i++) {
7732 FontSize size = (FontSize)buf->ReadByte();
7733 uint8 num_char = buf->ReadByte();
7734 uint16 base_char = buf->ReadWord();
7735
7736 if (size >= FS_END) {
7737 grfmsg(1, "LoadFontGlyph: Size %u is not supported, ignoring", size);
7738 }
7739
7740 grfmsg(7, "LoadFontGlyph: Loading %u glyph(s) at 0x%04X for size %u", num_char, base_char, size);
7741
7742 for (uint c = 0; c < num_char; c++) {
7743 if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
7744 _cur.nfo_line++;
7745 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
7746 }
7747 }
7748 }
7749
7751 static void SkipAct12(ByteReader *buf)
7752 {
7753 /* <12> <num_def> <font_size> <num_char> <base_char>
7754 *
7755 * B num_def Number of definitions
7756 * B font_size Size of font (0 = normal, 1 = small, 2 = large)
7757 * B num_char Number of consecutive glyphs
7758 * W base_char First character index */
7759
7760 uint8 num_def = buf->ReadByte();
7761
7762 for (uint i = 0; i < num_def; i++) {
7763 /* Ignore 'size' byte */
7764 buf->ReadByte();
7765
7766 /* Sum up number of characters */
7767 _cur.skip_sprites += buf->ReadByte();
7768
7769 /* Ignore 'base_char' word */
7770 buf->ReadWord();
7771 }
7772
7773 grfmsg(3, "SkipAct12: Skipping %d sprites", _cur.skip_sprites);
7774 }
7775
7777 static void TranslateGRFStrings(ByteReader *buf)
7778 {
7779 /* <13> <grfid> <num-ent> <offset> <text...>
7780 *
7781 * 4*B grfid The GRFID of the file whose texts are to be translated
7782 * B num-ent Number of strings
7783 * W offset First text ID
7784 * S text... Zero-terminated strings */
7785
7786 uint32 grfid = buf->ReadDWord();
7787 const GRFConfig *c = GetGRFConfig(grfid);
7788 if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
7789 grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
7790 return;
7791 }
7792
7793 if (c->status == GCS_INITIALISED) {
7794 /* If the file is not active but will be activated later, give an error
7795 * and disable this file. */
7796 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
7797
7798 error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
7799
7800 return;
7801 }
7802
7803 /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
7804 * to be added as a generic string, thus the language id of 0x7F. For this to work
7805 * new_scheme has to be true as well, which will also be implicitly the case for version 8
7806 * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
7807 * not change anything if a string has been provided specifically for this language. */
7808 byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
7809 byte num_strings = buf->ReadByte();
7810 uint16 first_id = buf->ReadWord();
7811
7812 if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
7813 grfmsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x%4X, number: 0x%2X)", first_id, num_strings);
7814 return;
7815 }
7816
7817 for (uint i = 0; i < num_strings && buf->HasData(); i++) {
7818 const char *string = buf->ReadString();
7819
7820 if (StrEmpty(string)) {
7821 grfmsg(7, "TranslateGRFString: Ignoring empty string.");
7822 continue;
7823 }
7824
7825 AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
7826 }
7827 }
7828
7830 static bool ChangeGRFName(byte langid, const char *str)
7831 {
7832 AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
7833 return true;
7834 }
7835
7837 static bool ChangeGRFDescription(byte langid, const char *str)
7838 {
7839 AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
7840 return true;
7841 }
7842
7844 static bool ChangeGRFURL(byte langid, const char *str)
7845 {
7846 AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
7847 return true;
7848 }
7849
7851 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
7852 {
7853 if (len != 1) {
7854 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
7855 buf->Skip(len);
7856 } else {
7857 _cur.grfconfig->num_valid_params = std::min<byte>(buf->ReadByte(), lengthof(_cur.grfconfig->param));
7858 }
7859 return true;
7860 }
7861
7863 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
7864 {
7865 if (len != 1) {
7866 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got " PRINTF_SIZE ", ignoring this field", len);
7867 buf->Skip(len);
7868 } else {
7869 char data = buf->ReadByte();
7870 GRFPalette pal = GRFP_GRF_UNSET;
7871 switch (data) {
7872 case '*':
7873 case 'A': pal = GRFP_GRF_ANY; break;
7874 case 'W': pal = GRFP_GRF_WINDOWS; break;
7875 case 'D': pal = GRFP_GRF_DOS; break;
7876 default:
7877 grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'PALS', ignoring this field", data);
7878 break;
7879 }
7880 if (pal != GRFP_GRF_UNSET) {
7881 _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
7882 _cur.grfconfig->palette |= pal;
7883 }
7884 }
7885 return true;
7886 }
7887
7889 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
7890 {
7891 if (len != 1) {
7892 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got " PRINTF_SIZE ", ignoring this field", len);
7893 buf->Skip(len);
7894 } else {
7895 char data = buf->ReadByte();
7896 GRFPalette pal = GRFP_BLT_UNSET;
7897 switch (data) {
7898 case '8': pal = GRFP_BLT_UNSET; break;
7899 case '3': pal = GRFP_BLT_32BPP; break;
7900 default:
7901 grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'BLTR', ignoring this field", data);
7902 return true;
7903 }
7904 _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
7905 _cur.grfconfig->palette |= pal;
7906 }
7907 return true;
7908 }
7909
7911 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
7912 {
7913 if (len != 4) {
7914 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got " PRINTF_SIZE ", ignoring this field", len);
7915 buf->Skip(len);
7916 } else {
7917 /* Set min_loadable_version as well (default to minimal compatibility) */
7918 _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7919 }
7920 return true;
7921 }
7922
7924 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
7925 {
7926 if (len != 4) {
7927 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got " PRINTF_SIZE ", ignoring this field", len);
7928 buf->Skip(len);
7929 } else {
7930 _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7931 if (_cur.grfconfig->version == 0) {
7932 grfmsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
7933 _cur.grfconfig->min_loadable_version = 0;
7934 }
7935 if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
7936 grfmsg(2, "StaticGRFInfo: 'MINV' defined as %d, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
7937 _cur.grfconfig->min_loadable_version = _cur.grfconfig->version;
7938 }
7939 }
7940 return true;
7941 }
7942
7943 static GRFParameterInfo *_cur_parameter;
7944
7946 static bool ChangeGRFParamName(byte langid, const char *str)
7947 {
7948 AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
7949 return true;
7950 }
7951
7953 static bool ChangeGRFParamDescription(byte langid, const char *str)
7954 {
7955 AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
7956 return true;
7957 }
7958
7960 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
7961 {
7962 if (len != 1) {
7963 grfmsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got " PRINTF_SIZE ", ignoring this field", len);
7964 buf->Skip(len);
7965 } else {
7966 GRFParameterType type = (GRFParameterType)buf->ReadByte();
7967 if (type < PTYPE_END) {
7968 _cur_parameter->type = type;
7969 } else {
7970 grfmsg(3, "StaticGRFInfo: unknown parameter type %d, ignoring this field", type);
7971 }
7972 }
7973 return true;
7974 }
7975
7977 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
7978 {
7979 if (_cur_parameter->type != PTYPE_UINT_ENUM) {
7980 grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
7981 buf->Skip(len);
7982 } else if (len != 8) {
7983 grfmsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got " PRINTF_SIZE ", ignoring this field", len);
7984 buf->Skip(len);
7985 } else {
7986 uint32 min_value = buf->ReadDWord();
7987 uint32 max_value = buf->ReadDWord();
7988 if (min_value <= max_value) {
7989 _cur_parameter->min_value = min_value;
7990 _cur_parameter->max_value = max_value;
7991 } else {
7992 grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
7993 }
7994 }
7995 return true;
7996 }
7997
7999 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
8000 {
8001 if (len < 1 || len > 3) {
8002 grfmsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got " PRINTF_SIZE ", ignoring this field", len);
8003 buf->Skip(len);
8004 } else {
8005 byte param_nr = buf->ReadByte();
8006 if (param_nr >= lengthof(_cur.grfconfig->param)) {
8007 grfmsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param %d, ignoring this field", param_nr);
8008 buf->Skip(len - 1);
8009 } else {
8010 _cur_parameter->param_nr = param_nr;
8011 if (len >= 2) _cur_parameter->first_bit = std::min<byte>(buf->ReadByte(), 31);
8012 if (len >= 3) _cur_parameter->num_bit = std::min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
8013 }
8014 }
8015
8016 return true;
8017 }
8018
8020 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
8021 {
8022 if (len != 4) {
8023 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got " PRINTF_SIZE ", ignoring this field", len);
8024 buf->Skip(len);
8025 } else {
8026 _cur_parameter->def_value = buf->ReadDWord();
8027 }
8028 _cur.grfconfig->has_param_defaults = true;
8029 return true;
8030 }
8031
8032 typedef bool (*DataHandler)(size_t, ByteReader *);
8033 typedef bool (*TextHandler)(byte, const char *str);
8034 typedef bool (*BranchHandler)(ByteReader *);
8035
8043 struct AllowedSubtags {
8045 AllowedSubtags() :
8046 id(0),
8047 type(0)
8048 {}
8049
8055 AllowedSubtags(uint32 id, DataHandler handler) :
8056 id(id),
8057 type('B')
8058 {
8059 this->handler.data = handler;
8060 }
8061
8067 AllowedSubtags(uint32 id, TextHandler handler) :
8068 id(id),
8069 type('T')
8070 {
8071 this->handler.text = handler;
8072 }
8073
8079 AllowedSubtags(uint32 id, BranchHandler handler) :
8080 id(id),
8081 type('C')
8082 {
8083 this->handler.call_handler = true;
8084 this->handler.u.branch = handler;
8085 }
8086
8092 AllowedSubtags(uint32 id, AllowedSubtags *subtags) :
8093 id(id),
8094 type('C')
8095 {
8096 this->handler.call_handler = false;
8097 this->handler.u.subtags = subtags;
8098 }
8099
8100 uint32 id;
8101 byte type;
8102 union {
8103 DataHandler data;
8104 TextHandler text;
8105 struct {
8106 union {
8107 BranchHandler branch;
8108 AllowedSubtags *subtags;
8109 } u;
8110 bool call_handler;
8111 };
8112 } handler;
8113 };
8114
8115 static bool SkipUnknownInfo(ByteReader *buf, byte type);
8116 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
8117
8124 static bool ChangeGRFParamValueNames(ByteReader *buf)
8125 {
8126 byte type = buf->ReadByte();
8127 while (type != 0) {
8128 uint32 id = buf->ReadDWord();
8129 if (type != 'T' || id > _cur_parameter->max_value) {
8130 grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8131 if (!SkipUnknownInfo(buf, type)) return false;
8132 type = buf->ReadByte();
8133 continue;
8134 }
8135
8136 byte langid = buf->ReadByte();
8137 const char *name_string = buf->ReadString();
8138
8139 std::pair<uint32, GRFTextList> *val_name = _cur_parameter->value_names.Find(id);
8140 if (val_name != _cur_parameter->value_names.End()) {
8141 AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8142 } else {
8143 GRFTextList list;
8144 AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8145 _cur_parameter->value_names.Insert(id, list);
8146 }
8147
8148 type = buf->ReadByte();
8149 }
8150 return true;
8151 }
8152
8154 AllowedSubtags _tags_parameters[] = {
8155 AllowedSubtags('NAME', ChangeGRFParamName),
8156 AllowedSubtags('DESC', ChangeGRFParamDescription),
8157 AllowedSubtags('TYPE', ChangeGRFParamType),
8158 AllowedSubtags('LIMI', ChangeGRFParamLimits),
8159 AllowedSubtags('MASK', ChangeGRFParamMask),
8160 AllowedSubtags('VALU', ChangeGRFParamValueNames),
8161 AllowedSubtags('DFLT', ChangeGRFParamDefault),
8162 AllowedSubtags()
8163 };
8164
8171 static bool HandleParameterInfo(ByteReader *buf)
8172 {
8173 byte type = buf->ReadByte();
8174 while (type != 0) {
8175 uint32 id = buf->ReadDWord();
8176 if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8177 grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8178 if (!SkipUnknownInfo(buf, type)) return false;
8179 type = buf->ReadByte();
8180 continue;
8181 }
8182
8183 if (id >= _cur.grfconfig->param_info.size()) {
8184 _cur.grfconfig->param_info.resize(id + 1);
8185 }
8186 if (_cur.grfconfig->param_info[id] == nullptr) {
8187 _cur.grfconfig->param_info[id] = new GRFParameterInfo(id);
8188 }
8189 _cur_parameter = _cur.grfconfig->param_info[id];
8190 /* Read all parameter-data and process each node. */
8191 if (!HandleNodes(buf, _tags_parameters)) return false;
8192 type = buf->ReadByte();
8193 }
8194 return true;
8195 }
8196
8198 AllowedSubtags _tags_info[] = {
8199 AllowedSubtags('NAME', ChangeGRFName),
8200 AllowedSubtags('DESC', ChangeGRFDescription),
8201 AllowedSubtags('URL_', ChangeGRFURL),
8202 AllowedSubtags('NPAR', ChangeGRFNumUsedParams),
8203 AllowedSubtags('PALS', ChangeGRFPalette),
8204 AllowedSubtags('BLTR', ChangeGRFBlitter),
8205 AllowedSubtags('VRSN', ChangeGRFVersion),
8206 AllowedSubtags('MINV', ChangeGRFMinVersion),
8207 AllowedSubtags('PARA', HandleParameterInfo),
8208 AllowedSubtags()
8209 };
8210
8212 AllowedSubtags _tags_root[] = {
8213 AllowedSubtags('INFO', _tags_info),
8214 AllowedSubtags()
8215 };
8216
8217
8224 static bool SkipUnknownInfo(ByteReader *buf, byte type)
8225 {
8226 /* type and id are already read */
8227 switch (type) {
8228 case 'C': {
8229 byte new_type = buf->ReadByte();
8230 while (new_type != 0) {
8231 buf->ReadDWord(); // skip the id
8232 if (!SkipUnknownInfo(buf, new_type)) return false;
8233 new_type = buf->ReadByte();
8234 }
8235 break;
8236 }
8237
8238 case 'T':
8239 buf->ReadByte(); // lang
8240 buf->ReadString(); // actual text
8241 break;
8242
8243 case 'B': {
8244 uint16 size = buf->ReadWord();
8245 buf->Skip(size);
8246 break;
8247 }
8248
8249 default:
8250 return false;
8251 }
8252
8253 return true;
8254 }
8255
8264 static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
8265 {
8266 uint i = 0;
8267 AllowedSubtags *tag;
8268 while ((tag = &subtags[i++])->type != 0) {
8269 if (tag->id != BSWAP32(id) || tag->type != type) continue;
8270 switch (type) {
8271 default: NOT_REACHED();
8272
8273 case 'T': {
8274 byte langid = buf->ReadByte();
8275 return tag->handler.text(langid, buf->ReadString());
8276 }
8277
8278 case 'B': {
8279 size_t len = buf->ReadWord();
8280 if (buf->Remaining() < len) return false;
8281 return tag->handler.data(len, buf);
8282 }
8283
8284 case 'C': {
8285 if (tag->handler.call_handler) {
8286 return tag->handler.u.branch(buf);
8287 }
8288 return HandleNodes(buf, tag->handler.u.subtags);
8289 }
8290 }
8291 }
8292 grfmsg(2, "StaticGRFInfo: unknown type/id combination found, type=%c, id=%x", type, id);
8293 return SkipUnknownInfo(buf, type);
8294 }
8295
8302 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
8303 {
8304 byte type = buf->ReadByte();
8305 while (type != 0) {
8306 uint32 id = buf->ReadDWord();
8307 if (!HandleNode(type, id, buf, subtags)) return false;
8308 type = buf->ReadByte();
8309 }
8310 return true;
8311 }
8312
8317 static void StaticGRFInfo(ByteReader *buf)
8318 {
8319 /* <14> <type> <id> <text/data...> */
8320 HandleNodes(buf, _tags_root);
8321 }
8322
8328 static void GRFUnsafe(ByteReader *buf)
8329 {
8330 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8331
8332 /* Skip remainder of GRF */
8333 _cur.skip_sprites = -1;
8334 }
8335
8336
8338 static void InitializeGRFSpecial()
8339 {
8340 _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1 : 0) << 0x0C) // keepsmallairport
8341 | (1 << 0x0D) // newairports
8342 | (1 << 0x0E) // largestations
8343 | ((_settings_game.construction.max_bridge_length > 16 ? 1 : 0) << 0x0F) // longbridges
8344 | (0 << 0x10) // loadtime
8345 | (1 << 0x12) // presignals
8346 | (1 << 0x13) // extpresignals
8347 | ((_settings_game.vehicle.never_expire_vehicles ? 1 : 0) << 0x16) // enginespersist
8348 | (1 << 0x1B) // multihead
8349 | (1 << 0x1D) // lowmemory
8350 | (1 << 0x1E); // generalfixes
8351
8352 _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1 : 0) << 0x07) // moreairports - based on units of noise
8353 | (1 << 0x08) // mammothtrains
8354 | (1 << 0x09) // trainrefit
8355 | (0 << 0x0B) // subsidiaries
8356 | ((_settings_game.order.gradual_loading ? 1 : 0) << 0x0C) // gradualloading
8357 | (1 << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8358 | (1 << 0x13) // unifiedmaglevmode - set bit 1 mode
8359 | (1 << 0x14) // bridgespeedlimits
8360 | (1 << 0x16) // eternalgame
8361 | (1 << 0x17) // newtrains
8362 | (1 << 0x18) // newrvs
8363 | (1 << 0x19) // newships
8364 | (1 << 0x1A) // newplanes
8365 | ((_settings_game.construction.train_signal_side == 1 ? 1 : 0) << 0x1B) // signalsontrafficside
8366 | ((_settings_game.vehicle.disable_elrails ? 0 : 1) << 0x1C); // electrifiedrailway
8367
8368 _ttdpatch_flags[2] = (1 << 0x01) // loadallgraphics - obsolote
8369 | (1 << 0x03) // semaphores
8370 | (1 << 0x0A) // newobjects
8371 | (0 << 0x0B) // enhancedgui
8372 | (0 << 0x0C) // newagerating
8373 | ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x0D) // buildonslopes
8374 | (1 << 0x0E) // fullloadany
8375 | (1 << 0x0F) // planespeed
8376 | (0 << 0x10) // moreindustriesperclimate - obsolete
8377 | (0 << 0x11) // moretoylandfeatures
8378 | (1 << 0x12) // newstations
8379 | (1 << 0x13) // tracktypecostdiff
8380 | (1 << 0x14) // manualconvert
8381 | ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x15) // buildoncoasts
8382 | (1 << 0x16) // canals
8383 | (1 << 0x17) // newstartyear
8384 | ((_settings_game.vehicle.freight_trains > 1 ? 1 : 0) << 0x18) // freighttrains
8385 | (1 << 0x19) // newhouses
8386 | (1 << 0x1A) // newbridges
8387 | (1 << 0x1B) // newtownnames
8388 | (1 << 0x1C) // moreanimation
8389 | ((_settings_game.vehicle.wagon_speed_limits ? 1 : 0) << 0x1D) // wagonspeedlimits
8390 | (1 << 0x1E) // newshistory
8391 | (0 << 0x1F); // custombridgeheads
8392
8393 _ttdpatch_flags[3] = (0 << 0x00) // newcargodistribution
8394 | (1 << 0x01) // windowsnap
8395 | ((_settings_game.economy.allow_town_roads || _generating_world ? 0 : 1) << 0x02) // townbuildnoroad
8396 | (1 << 0x03) // pathbasedsignalling
8397 | (0 << 0x04) // aichoosechance
8398 | (1 << 0x05) // resolutionwidth
8399 | (1 << 0x06) // resolutionheight
8400 | (1 << 0x07) // newindustries
8401 | ((_settings_game.order.improved_load ? 1 : 0) << 0x08) // fifoloading
8402 | (0 << 0x09) // townroadbranchprob
8403 | (0 << 0x0A) // tempsnowline
8404 | (1 << 0x0B) // newcargo
8405 | (1 << 0x0C) // enhancemultiplayer
8406 | (1 << 0x0D) // onewayroads
8407 | (1 << 0x0E) // irregularstations
8408 | (1 << 0x0F) // statistics
8409 | (1 << 0x10) // newsounds
8410 | (1 << 0x11) // autoreplace
8411 | (1 << 0x12) // autoslope
8412 | (0 << 0x13) // followvehicle
8413 | (1 << 0x14) // trams
8414 | (0 << 0x15) // enhancetunnels
8415 | (1 << 0x16) // shortrvs
8416 | (1 << 0x17) // articulatedrvs
8417 | ((_settings_game.vehicle.dynamic_engines ? 1 : 0) << 0x18) // dynamic engines
8418 | (1 << 0x1E) // variablerunningcosts
8419 | (1 << 0x1F); // any switch is on
8420
8421 _ttdpatch_flags[4] = (1 << 0x00) // larger persistent storage
8422 | ((_settings_game.economy.inflation ? 1 : 0) << 0x01); // inflation is on
8423 }
8424
8426 static void ResetCustomStations()
8427 {
8428 for (GRFFile * const file : _grf_files) {
8429 StationSpec **&stations = file->stations;
8430 if (stations == nullptr) continue;
8431 for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
8432 if (stations[i] == nullptr) continue;
8433 StationSpec *statspec = stations[i];
8434
8435 /* Release this station */
8436 delete statspec;
8437 }
8438
8439 /* Free and reset the station data */
8440 free(stations);
8441 stations = nullptr;
8442 }
8443 }
8444
8446 static void ResetCustomHouses()
8447 {
8448 for (GRFFile * const file : _grf_files) {
8449 HouseSpec **&housespec = file->housespec;
8450 if (housespec == nullptr) continue;
8451 for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8452 free(housespec[i]);
8453 }
8454
8455 free(housespec);
8456 housespec = nullptr;
8457 }
8458 }
8459
8461 static void ResetCustomAirports()
8462 {
8463 for (GRFFile * const file : _grf_files) {
8464 AirportSpec **aslist = file->airportspec;
8465 if (aslist != nullptr) {
8466 for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8467 AirportSpec *as = aslist[i];
8468
8469 if (as != nullptr) {
8470 /* We need to remove the tiles layouts */
8471 for (int j = 0; j < as->num_table; j++) {
8472 /* remove the individual layouts */
8473 free(as->table[j]);
8474 }
8475 free(as->table);
8476 free(as->depot_table);
8477 free(as->rotation);
8478
8479 free(as);
8480 }
8481 }
8482 free(aslist);
8483 file->airportspec = nullptr;
8484 }
8485
8486 AirportTileSpec **&airporttilespec = file->airtspec;
8487 if (airporttilespec != nullptr) {
8488 for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8489 free(airporttilespec[i]);
8490 }
8491 free(airporttilespec);
8492 airporttilespec = nullptr;
8493 }
8494 }
8495 }
8496
8498 static void ResetCustomIndustries()
8499 {
8500 for (GRFFile * const file : _grf_files) {
8501 IndustrySpec **&industryspec = file->industryspec;
8502 IndustryTileSpec **&indtspec = file->indtspec;
8503
8504 /* We are verifiying both tiles and industries specs loaded from the grf file
8505 * First, let's deal with industryspec */
8506 if (industryspec != nullptr) {
8507 for (uint i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8508 IndustrySpec *ind = industryspec[i];
8509 delete ind;
8510 }
8511
8512 free(industryspec);
8513 industryspec = nullptr;
8514 }
8515
8516 if (indtspec == nullptr) continue;
8517 for (uint i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8518 free(indtspec[i]);
8519 }
8520
8521 free(indtspec);
8522 indtspec = nullptr;
8523 }
8524 }
8525
8527 static void ResetCustomObjects()
8528 {
8529 for (GRFFile * const file : _grf_files) {
8530 ObjectSpec **&objectspec = file->objectspec;
8531 if (objectspec == nullptr) continue;
8532 for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8533 free(objectspec[i]);
8534 }
8535
8536 free(objectspec);
8537 objectspec = nullptr;
8538 }
8539 }
8540
8542 static void ResetNewGRF()
8543 {
8544 for (GRFFile * const file : _grf_files) {
8545 delete file;
8546 }
8547
8548 _grf_files.clear();
8549 _cur.grffile = nullptr;
8550 }
8551
8553 static void ResetNewGRFErrors()
8554 {
8555 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8556 if (!HasBit(c->flags, GCF_COPY) && c->error != nullptr) {
8557 delete c->error;
8558 c->error = nullptr;
8559 }
8560 }
8561 }
8562
8566 void ResetNewGRFData()
8567 {
8568 CleanUpStrings();
8569 CleanUpGRFTownNames();
8570
8571 /* Copy/reset original engine info data */
8572 SetupEngines();
8573
8574 /* Copy/reset original bridge info data */
8575 ResetBridges();
8576
8577 /* Reset rail type information */
8578 ResetRailTypes();
8579
8580 /* Copy/reset original road type info data */
8581 ResetRoadTypes();
8582
8583 /* Allocate temporary refit/cargo class data */
8584 _gted = CallocT<GRFTempEngineData>(Engine::GetPoolSize());
8585
8586 /* Fill rail type label temporary data for default trains */
8587 for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8588 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8589 }
8590
8591 /* Reset GRM reservations */
8592 memset(&_grm_engines, 0, sizeof(_grm_engines));
8593 memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8594
8595 /* Reset generic feature callback lists */
8596 ResetGenericCallbacks();
8597
8598 /* Reset price base data */
8599 ResetPriceBaseMultipliers();
8600
8601 /* Reset the curencies array */
8602 ResetCurrencies();
8603
8604 /* Reset the house array */
8605 ResetCustomHouses();
8606 ResetHouses();
8607
8608 /* Reset the industries structures*/
8609 ResetCustomIndustries();
8610 ResetIndustries();
8611
8612 /* Reset the objects. */
8613 ObjectClass::Reset();
8614 ResetCustomObjects();
8615 ResetObjects();
8616
8617 /* Reset station classes */
8618 StationClass::Reset();
8619 ResetCustomStations();
8620
8621 /* Reset airport-related structures */
8622 AirportClass::Reset();
8623 ResetCustomAirports();
8624 AirportSpec::ResetAirports();
8625 AirportTileSpec::ResetAirportTiles();
8626
8627 /* Reset canal sprite groups and flags */
8628 memset(_water_feature, 0, sizeof(_water_feature));
8629
8630 /* Reset the snowline table. */
8631 ClearSnowLine();
8632
8633 /* Reset NewGRF files */
8634 ResetNewGRF();
8635
8636 /* Reset NewGRF errors. */
8637 ResetNewGRFErrors();
8638
8639 /* Set up the default cargo types */
8640 SetupCargoForClimate(_settings_game.game_creation.landscape);
8641
8642 /* Reset misc GRF features and train list display variables */
8643 _misc_grf_features = 0;
8644
8645 _loaded_newgrf_features.has_2CC = false;
8646 _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8647 _loaded_newgrf_features.shore = SHORE_REPLACE_NONE;
8648 _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NONE;
8649
8650 /* Clear all GRF overrides */
8651 _grf_id_overrides.clear();
8652
8653 InitializeSoundPool();
8654 _spritegroup_pool.CleanPool();
8655 }
8656
8660 void ResetPersistentNewGRFData()
8661 {
8662 /* Reset override managers */
8663 _engine_mngr.ResetToDefaultMapping();
8664 _house_mngr.ResetMapping();
8665 _industry_mngr.ResetMapping();
8666 _industile_mngr.ResetMapping();
8667 _airport_mngr.ResetMapping();
8668 _airporttile_mngr.ResetMapping();
8669 }
8670
8675 static void BuildCargoTranslationMap()
8676 {
8677 memset(_cur.grffile->cargo_map, 0xFF, sizeof(_cur.grffile->cargo_map));
8678
8679 for (CargoID c = 0; c < NUM_CARGO; c++) {
8680 const CargoSpec *cs = CargoSpec::Get(c);
8681 if (!cs->IsValid()) continue;
8682
8683 if (_cur.grffile->cargo_list.size() == 0) {
8684 /* Default translation table, so just a straight mapping to bitnum */
8685 _cur.grffile->cargo_map[c] = cs->bitnum;
8686 } else {
8687 /* Check the translation table for this cargo's label */
8688 int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8689 if (idx >= 0) _cur.grffile->cargo_map[c] = idx;
8690 }
8691 }
8692 }
8693
8698 static void InitNewGRFFile(const GRFConfig *config)
8699 {
8700 GRFFile *newfile = GetFileByFilename(config->filename);
8701 if (newfile != nullptr) {
8702 /* We already loaded it once. */
8703 _cur.grffile = newfile;
8704 return;
8705 }
8706
8707 newfile = new GRFFile(config);
8708 _grf_files.push_back(_cur.grffile = newfile);
8709 }
8710
8715 GRFFile::GRFFile(const GRFConfig *config)
8716 {
8717 this->filename = stredup(config->filename);
8718 this->grfid = config->ident.grfid;
8719
8720 /* Initialise local settings to defaults */
8721 this->traininfo_vehicle_pitch = 0;
8722 this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8723
8724 /* Mark price_base_multipliers as 'not set' */
8725 for (Price i = PR_BEGIN; i < PR_END; i++) {
8726 this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8727 }
8728
8729 /* Initialise rail type map with default rail types */
8730 std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8731 this->railtype_map[0] = RAILTYPE_RAIL;
8732 this->railtype_map[1] = RAILTYPE_ELECTRIC;
8733 this->railtype_map[2] = RAILTYPE_MONO;
8734 this->railtype_map[3] = RAILTYPE_MAGLEV;
8735
8736 /* Initialise road type map with default road types */
8737 std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8738 this->roadtype_map[0] = ROADTYPE_ROAD;
8739
8740 /* Initialise tram type map with default tram types */
8741 std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8742 this->tramtype_map[0] = ROADTYPE_TRAM;
8743
8744 /* Copy the initial parameter list
8745 * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8746 static_assert(lengthof(this->param) == lengthof(config->param) && lengthof(this->param) == 0x80);
8747
8748 assert(config->num_params <= lengthof(config->param));
8749 this->param_end = config->num_params;
8750 if (this->param_end > 0) {
8751 MemCpyT(this->param, config->param, this->param_end);
8752 }
8753 }
8754
8755 GRFFile::~GRFFile()
8756 {
8757 free(this->filename);
8758 delete[] this->language_map;
8759 }
8760
8761
8765 static void CalculateRefitMasks()
8766 {
8767 CargoTypes original_known_cargoes = 0;
8768 for (int ct = 0; ct != NUM_ORIGINAL_CARGO; ++ct) {
8769 CargoID cid = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ct));
8770 if (cid != CT_INVALID) SetBit(original_known_cargoes, cid);
8771 }
8772
8773 for (Engine *e : Engine::Iterate()) {
8774 EngineID engine = e->index;
8775 EngineInfo *ei = &e->info;
8776 bool only_defaultcargo;
8777
8778 /* If the NewGRF did not set any cargo properties, we apply default values. */
8779 if (_gted[engine].defaultcargo_grf == nullptr) {
8780 /* If the vehicle has any capacity, apply the default refit masks */
8781 if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
8782 static constexpr byte T = 1 << LT_TEMPERATE;
8783 static constexpr byte A = 1 << LT_ARCTIC;
8784 static constexpr byte S = 1 << LT_TROPIC;
8785 static constexpr byte Y = 1 << LT_TOYLAND;
8786 static const struct DefaultRefitMasks {
8787 byte climate;
8788 CargoType cargo_type;
8789 CargoTypes cargo_allowed;
8790 CargoTypes cargo_disallowed;
8791 } _default_refit_masks[] = {
8792 {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
8793 {T | A | S , CT_MAIL, CC_MAIL, 0},
8794 {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
8795 { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
8796 {T | A , CT_COAL, CC_BULK, 0},
8797 { S , CT_COPPER_ORE, CC_BULK, 0},
8798 { Y, CT_SUGAR, CC_BULK, 0},
8799 {T | A | S , CT_OIL, CC_LIQUID, 0},
8800 { Y, CT_COLA, CC_LIQUID, 0},
8801 {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8802 { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
8803 { A | S , CT_FOOD, CC_REFRIGERATED, 0},
8804 { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8805 };
8806
8807 if (e->type == VEH_AIRCRAFT) {
8808 /* Aircraft default to "light" cargoes */
8809 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
8810 _gted[engine].cargo_disallowed = CC_LIQUID;
8811 } else if (e->type == VEH_SHIP) {
8812 switch (ei->cargo_type) {
8813 case CT_PASSENGERS:
8814 /* Ferries */
8815 _gted[engine].cargo_allowed = CC_PASSENGERS;
8816 _gted[engine].cargo_disallowed = 0;
8817 break;
8818 case CT_OIL:
8819 /* Tankers */
8820 _gted[engine].cargo_allowed = CC_LIQUID;
8821 _gted[engine].cargo_disallowed = 0;
8822 break;
8823 default:
8824 /* Cargo ships */
8825 if (_settings_game.game_creation.landscape == LT_TOYLAND) {
8826 /* No tanker in toyland :( */
8827 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8828 _gted[engine].cargo_disallowed = CC_PASSENGERS;
8829 } else {
8830 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
8831 _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
8832 }
8833 break;
8834 }
8835 e->u.ship.old_refittable = true;
8836 } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
8837 /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
8838 * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
8839 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8840 _gted[engine].cargo_disallowed = 0;
8841 } else {
8842 /* Train wagons and road vehicles are classified by their default cargo type */
8843 for (const auto &drm : _default_refit_masks) {
8844 if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
8845 if (drm.cargo_type != ei->cargo_type) continue;
8846
8847 _gted[engine].cargo_allowed = drm.cargo_allowed;
8848 _gted[engine].cargo_disallowed = drm.cargo_disallowed;
8849 break;
8850 }
8851
8852 /* All original cargoes have specialised vehicles, so exclude them */
8853 _gted[engine].ctt_exclude_mask = original_known_cargoes;
8854 }
8855 }
8856 _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
8857
8858 /* Translate cargo_type using the original climate-specific cargo table. */
8859 ei->cargo_type = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ei->cargo_type));
8860 if (ei->cargo_type != CT_INVALID) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
8861 }
8862
8863 /* Compute refittability */
8864 {
8865 CargoTypes mask = 0;
8866 CargoTypes not_mask = 0;
8867 CargoTypes xor_mask = ei->refit_mask;
8868
8869 /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
8870 * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
8871 only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
8872
8873 if (_gted[engine].cargo_allowed != 0) {
8874 /* Build up the list of cargo types from the set cargo classes. */
8875 for (const CargoSpec *cs : CargoSpec::Iterate()) {
8876 if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
8877 if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
8878 }
8879 }
8880
8881 ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
8882
8883 /* Apply explicit refit includes/excludes. */
8884 ei->refit_mask |= _gted[engine].ctt_include_mask;
8885 ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
8886 }
8887
8888 /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
8889 if (ei->cargo_type != CT_INVALID && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = CT_INVALID;
8890
8891 /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
8892 * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
8893 if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && ei->cargo_type != CT_INVALID && !HasBit(ei->refit_mask, ei->cargo_type)) {
8894 ei->cargo_type = CT_INVALID;
8895 }
8896
8897 /* Check if this engine's cargo type is valid. If not, set to the first refittable
8898 * cargo type. Finally disable the vehicle, if there is still no cargo. */
8899 if (ei->cargo_type == CT_INVALID && ei->refit_mask != 0) {
8900 /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
8901 const uint8 *cargo_map_for_first_refittable = nullptr;
8902 {
8903 const GRFFile *file = _gted[engine].defaultcargo_grf;
8904 if (file == nullptr) file = e->GetGRF();
8905 if (file != nullptr && file->grf_version >= 8 && file->cargo_list.size() != 0) {
8906 cargo_map_for_first_refittable = file->cargo_map;
8907 }
8908 }
8909
8910 if (cargo_map_for_first_refittable != nullptr) {
8911 /* Use first refittable cargo from cargo translation table */
8912 byte best_local_slot = 0xFF;
8913 for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
8914 byte local_slot = cargo_map_for_first_refittable[cargo_type];
8915 if (local_slot < best_local_slot) {
8916 best_local_slot = local_slot;
8917 ei->cargo_type = cargo_type;
8918 }
8919 }
8920 }
8921
8922 if (ei->cargo_type == CT_INVALID) {
8923 /* Use first refittable cargo slot */
8924 ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
8925 }
8926 }
8927 if (ei->cargo_type == CT_INVALID) ei->climates = 0;
8928
8929 /* Clear refit_mask for not refittable ships */
8930 if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
8931 ei->refit_mask = 0;
8932 }
8933 }
8934 }
8935
8937 static void FinaliseCanals()
8938 {
8939 for (uint i = 0; i < CF_END; i++) {
8940 if (_water_feature[i].grffile != nullptr) {
8941 _water_feature[i].callback_mask = _water_feature[i].grffile->canal_local_properties[i].callback_mask;
8942 _water_feature[i].flags = _water_feature[i].grffile->canal_local_properties[i].flags;
8943 }
8944 }
8945 }
8946
8948 static void FinaliseEngineArray()
8949 {
8950 for (Engine *e : Engine::Iterate()) {
8951 if (e->GetGRF() == nullptr) {
8952 const EngineIDMapping &eid = _engine_mngr[e->index];
8953 if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
8954 e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
8955 }
8956 }
8957
8958 if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
8959
8960 /* When the train does not set property 27 (misc flags), but it
8961 * is overridden by a NewGRF graphically we want to disable the
8962 * flipping possibility. */
8963 if (e->type == VEH_TRAIN && !_gted[e->index].prop27_set && e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
8964 ClrBit(e->info.misc_flags, EF_RAIL_FLIPS);
8965 }
8966
8967 /* Skip wagons, there livery is defined via the engine */
8968 if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
8969 LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, nullptr);
8970 SetBit(_loaded_newgrf_features.used_liveries, ls);
8971 /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
8972
8973 if (e->type == VEH_TRAIN) {
8974 SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
8975 switch (ls) {
8976 case LS_STEAM:
8977 case LS_DIESEL:
8978 case LS_ELECTRIC:
8979 case LS_MONORAIL:
8980 case LS_MAGLEV:
8981 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
8982 break;
8983
8984 case LS_DMU:
8985 case LS_EMU:
8986 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
8987 break;
8988
8989 default: NOT_REACHED();
8990 }
8991 }
8992 }
8993 }
8994 }
8995
8997 static void FinaliseCargoArray()
8998 {
8999 for (CargoID c = 0; c < NUM_CARGO; c++) {
9000 CargoSpec *cs = CargoSpec::Get(c);
9001 if (!cs->IsValid()) {
9002 cs->name = cs->name_single = cs->units_volume = STR_NEWGRF_INVALID_CARGO;
9003 cs->quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9004 cs->abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9005 }
9006 }
9007 }
9008
9020 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
9021 {
9022 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9023 (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9024 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9025 (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9026 next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9027 hs->enabled = false;
9028 if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9029 return false;
9030 }
9031
9032 /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9033 * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9034 * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9035 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9036 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9037 hs->enabled = false;
9038 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);
9039 return false;
9040 }
9041
9042 /* Substitute type is also used for override, and having an override with a different size causes crashes.
9043 * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9044 if (filename != nullptr && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9045 hs->enabled = false;
9046 Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9047 return false;
9048 }
9049
9050 /* Make sure that additional parts of multitile houses are not available. */
9051 if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9052 hs->enabled = false;
9053 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);
9054 return false;
9055 }
9056
9057 return true;
9058 }
9059
9066 static void EnsureEarlyHouse(HouseZones bitmask)
9067 {
9068 Year min_year = MAX_YEAR;
9069
9070 for (int i = 0; i < NUM_HOUSES; i++) {
9071 HouseSpec *hs = HouseSpec::Get(i);
9072 if (hs == nullptr || !hs->enabled) continue;
9073 if ((hs->building_availability & bitmask) != bitmask) continue;
9074 if (hs->min_year < min_year) min_year = hs->min_year;
9075 }
9076
9077 if (min_year == 0) return;
9078
9079 for (int i = 0; i < NUM_HOUSES; i++) {
9080 HouseSpec *hs = HouseSpec::Get(i);
9081 if (hs == nullptr || !hs->enabled) continue;
9082 if ((hs->building_availability & bitmask) != bitmask) continue;
9083 if (hs->min_year == min_year) hs->min_year = 0;
9084 }
9085 }
9086
9093 static void FinaliseHouseArray()
9094 {
9095 /* If there are no houses with start dates before 1930, then all houses
9096 * with start dates of 1930 have them reset to 0. This is in order to be
9097 * compatible with TTDPatch, where if no houses have start dates before
9098 * 1930 and the date is before 1930, the game pretends that this is 1930.
9099 * If there have been any houses defined with start dates before 1930 then
9100 * the dates are left alone.
9101 * On the other hand, why 1930? Just 'fix' the houses with the lowest
9102 * minimum introduction date to 0.
9103 */
9104 for (GRFFile * const file : _grf_files) {
9105 HouseSpec **&housespec = file->housespec;
9106 if (housespec == nullptr) continue;
9107
9108 for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) {
9109 HouseSpec *hs = housespec[i];
9110
9111 if (hs == nullptr) continue;
9112
9113 const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : nullptr);
9114 const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : nullptr);
9115 const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : nullptr);
9116
9117 if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9118
9119 _house_mngr.SetEntitySpec(hs);
9120 }
9121 }
9122
9123 for (int i = 0; i < NUM_HOUSES; i++) {
9124 HouseSpec *hs = HouseSpec::Get(i);
9125 const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9126 const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9127 const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9128
9129 /* We need to check all houses again to we are sure that multitile houses
9130 * did get consecutive IDs and none of the parts are missing. */
9131 if (!IsHouseSpecValid(hs, next1, next2, next3, nullptr)) {
9132 /* GetHouseNorthPart checks 3 houses that are directly before
9133 * it in the house pool. If any of those houses have multi-tile
9134 * flags set it assumes it's part of a multitile house. Since
9135 * we can have invalid houses in the pool marked as disabled, we
9136 * don't want to have them influencing valid tiles. As such set
9137 * building_flags to zero here to make sure any house following
9138 * this one in the pool is properly handled as 1x1 house. */
9139 hs->building_flags = TILE_NO_FLAG;
9140 }
9141 }
9142
9143 HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9144 EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9145 EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9146 EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9147 EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9148 EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9149
9150 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9151 EnsureEarlyHouse(HZ_ZON1 | HZ_SUBARTC_ABOVE);
9152 EnsureEarlyHouse(HZ_ZON2 | HZ_SUBARTC_ABOVE);
9153 EnsureEarlyHouse(HZ_ZON3 | HZ_SUBARTC_ABOVE);
9154 EnsureEarlyHouse(HZ_ZON4 | HZ_SUBARTC_ABOVE);
9155 EnsureEarlyHouse(HZ_ZON5 | HZ_SUBARTC_ABOVE);
9156 }
9157 }
9158
9164 static void FinaliseIndustriesArray()
9165 {
9166 for (GRFFile * const file : _grf_files) {
9167 IndustrySpec **&industryspec = file->industryspec;
9168 IndustryTileSpec **&indtspec = file->indtspec;
9169 if (industryspec != nullptr) {
9170 for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
9171 IndustrySpec *indsp = industryspec[i];
9172
9173 if (indsp != nullptr && indsp->enabled) {
9174 StringID strid;
9175 /* process the conversion of text at the end, so to be sure everything will be fine
9176 * and available. Check if it does not return undefind marker, which is a very good sign of a
9177 * substitute industry who has not changed the string been examined, thus using it as such */
9178 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9179 if (strid != STR_UNDEFINED) indsp->name = strid;
9180
9181 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9182 if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9183
9184 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9185 if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9186
9187 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9188 if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9189
9190 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9191 if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9192
9193 if (indsp->station_name != STR_NULL) {
9194 /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9195 * station's name. Don't want to lose the value, therefore, do not process. */
9196 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9197 if (strid != STR_UNDEFINED) indsp->station_name = strid;
9198 }
9199
9200 _industry_mngr.SetEntitySpec(indsp);
9201 }
9202 }
9203 }
9204
9205 if (indtspec != nullptr) {
9206 for (int i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
9207 IndustryTileSpec *indtsp = indtspec[i];
9208 if (indtsp != nullptr) {
9209 _industile_mngr.SetEntitySpec(indtsp);
9210 }
9211 }
9212 }
9213 }
9214
9215 for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
9216 IndustrySpec *indsp = &_industry_specs[j];
9217 if (indsp->enabled && indsp->grf_prop.grffile != nullptr) {
9218 for (uint i = 0; i < 3; i++) {
9219 indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
9220 }
9221 }
9222 if (!indsp->enabled) {
9223 indsp->name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9224 }
9225 }
9226 }
9227
9233 static void FinaliseObjectsArray()
9234 {
9235 for (GRFFile * const file : _grf_files) {
9236 ObjectSpec **&objectspec = file->objectspec;
9237 if (objectspec != nullptr) {
9238 for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
9239 if (objectspec[i] != nullptr && objectspec[i]->grf_prop.grffile != nullptr && objectspec[i]->enabled) {
9240 _object_mngr.SetEntitySpec(objectspec[i]);
9241 }
9242 }
9243 }
9244 }
9245 }
9246
9252 static void FinaliseAirportsArray()
9253 {
9254 for (GRFFile * const file : _grf_files) {
9255 AirportSpec **&airportspec = file->airportspec;
9256 if (airportspec != nullptr) {
9257 for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
9258 if (airportspec[i] != nullptr && airportspec[i]->enabled) {
9259 _airport_mngr.SetEntitySpec(airportspec[i]);
9260 }
9261 }
9262 }
9263
9264 AirportTileSpec **&airporttilespec = file->airtspec;
9265 if (airporttilespec != nullptr) {
9266 for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
9267 if (airporttilespec[i] != nullptr && airporttilespec[i]->enabled) {
9268 _airporttile_mngr.SetEntitySpec(airporttilespec[i]);
9269 }
9270 }
9271 }
9272 }
9273 }
9274
9275 /* Here we perform initial decoding of some special sprites (as are they
9276 * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9277 * partial implementation yet).
9278 * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9279 * a crafted invalid GRF file. We should tell that to the user somehow, or
9280 * better make this more robust in the future. */
9281 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
9282 {
9283 /* XXX: There is a difference between staged loading in TTDPatch and
9284 * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9285 * during stage 1, whilst action 3 is carried out during stage 2 (to
9286 * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9287 * IDs are valid only within a given set (action 1) block, and may be
9288 * overwritten after action 3 associates them. But overwriting happens
9289 * in an earlier stage than associating, so... We just process actions
9290 * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9291 * --pasky
9292 * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9293 * is not in memory and scanning the file every time would be too expensive.
9294 * In other stages we skip action 0x10 since it's already dealt with. */
9295 static const SpecialSpriteHandler handlers[][GLS_END] = {
9296 /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9297 /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9298 /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9299 /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9300 /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9301 /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9302 /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9303 /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9304 /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9305 /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9306 /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9307 /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9308 /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9309 /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9310 /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9311 /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9312 /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9313 /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9314 /* 0x12 */ { SkipAct12, SkipAct12, SkipAct12, SkipAct12, SkipAct12, LoadFontGlyph, },
9315 /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9316 /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9317 };
9318
9319 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9320
9321 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9322 if (it == _grf_line_to_action6_sprite_override.end()) {
9323 /* No preloaded sprite to work with; read the
9324 * pseudo sprite content. */
9325 _cur.file->ReadBlock(buf, num);
9326 } else {
9327 /* Use the preloaded sprite data. */
9328 buf = _grf_line_to_action6_sprite_override[location];
9329 grfmsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9330
9331 /* Skip the real (original) content of this action. */
9332 _cur.file->SeekTo(num, SEEK_CUR);
9333 }
9334
9335 ByteReader br(buf, buf + num);
9336 ByteReader *bufp = &br;
9337
9338 try {
9339 byte action = bufp->ReadByte();
9340
9341 if (action == 0xFF) {
9342 grfmsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9343 } else if (action == 0xFE) {
9344 grfmsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9345 } else if (action >= lengthof(handlers)) {
9346 grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
9347 } else if (handlers[action][stage] == nullptr) {
9348 grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
9349 } else {
9350 grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
9351 handlers[action][stage](bufp);
9352 }
9353 } catch (...) {
9354 grfmsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9355 DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9356 }
9357 }
9358
9365 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9366 {
9367 _cur.file = &file;
9368 _cur.grfconfig = config;
9369
9370 Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9371
9372 byte grf_container_version = file.GetContainerVersion();
9373 if (grf_container_version == 0) {
9374 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9375 return;
9376 }
9377
9378 if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9379 /* We need the sprite offsets in the init stage for NewGRF sounds
9380 * and in the activation stage for real sprites. */
9381 ReadGRFSpriteOffsets(file);
9382 } else {
9383 /* Skip sprite section offset if present. */
9384 if (grf_container_version >= 2) file.ReadDword();
9385 }
9386
9387 if (grf_container_version >= 2) {
9388 /* Read compression value. */
9389 byte compression = file.ReadByte();
9390 if (compression != 0) {
9391 Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9392 return;
9393 }
9394 }
9395
9396 /* Skip the first sprite; we don't care about how many sprites this
9397 * does contain; newest TTDPatches and George's longvehicles don't
9398 * neither, apparently. */
9399 uint32 num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9400 if (num == 4 && file.ReadByte() == 0xFF) {
9401 file.ReadDword();
9402 } else {
9403 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9404 return;
9405 }
9406
9407 _cur.ClearDataForNextFile();
9408
9409 ReusableBuffer<byte> buf;
9410
9411 while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9412 byte type = file.ReadByte();
9413 _cur.nfo_line++;
9414
9415 if (type == 0xFF) {
9416 if (_cur.skip_sprites == 0) {
9417 DecodeSpecialSprite(buf.Allocate(num), num, stage);
9418
9419 /* Stop all processing if we are to skip the remaining sprites */
9420 if (_cur.skip_sprites == -1) break;
9421
9422 continue;
9423 } else {
9424 file.SkipBytes(num);
9425 }
9426 } else {
9427 if (_cur.skip_sprites == 0) {
9428 grfmsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9429 DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9430 break;
9431 }
9432
9433 if (grf_container_version >= 2 && type == 0xFD) {
9434 /* Reference to data section. Container version >= 2 only. */
9435 file.SkipBytes(num);
9436 } else {
9437 file.SkipBytes(7);
9438 SkipSpriteData(file, type, num - 8);
9439 }
9440 }
9441
9442 if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9443 }
9444 }
9445
9454 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9455 {
9456 const char *filename = config->filename;
9457
9458 /* A .grf file is activated only if it was active when the game was
9459 * started. If a game is loaded, only its active .grfs will be
9460 * reactivated, unless "loadallgraphics on" is used. A .grf file is
9461 * considered active if its action 8 has been processed, i.e. its
9462 * action 8 hasn't been skipped using an action 7.
9463 *
9464 * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9465 * carried out. All others are ignored, because they only need to be
9466 * processed once at initialization. */
9467 if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9468 _cur.grffile = GetFileByFilename(filename);
9469 if (_cur.grffile == nullptr) usererror("File '%s' lost in cache.\n", filename);
9470 if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9471 if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9472 }
9473
9474 bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9475 if (temporary) {
9476 SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9477 LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9478 } else {
9479 LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9480 }
9481 }
9482
9490 static void ActivateOldShore()
9491 {
9492 /* Use default graphics, if no shore sprites were loaded.
9493 * Should not happen, as the base set's extra grf should include some. */
9494 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
9495
9496 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
9497 DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9498 DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9499 DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9500 DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9501 DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9502 DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9503 DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9504 DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9505 }
9506
9507 if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
9508 DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9509 DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9510 DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9511 DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9512 DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9513 DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9514 DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9515 DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9516
9517 /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9518 * If they would be used somewhen, then these grass tiles will most like not look as needed */
9519 DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9520 DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9521 }
9522 }
9523
9527 static void ActivateOldTramDepot()
9528 {
9529 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK) {
9530 DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9531 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9532 DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9533 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9534 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9535 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9536 }
9537 }
9538
9542 static void FinalisePriceBaseMultipliers()
9543 {
9544 extern const PriceBaseSpec _price_base_specs[];
9546 static const uint32 override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9547
9548 /* Evaluate grf overrides */
9549 int num_grfs = (uint)_grf_files.size();
9550 int *grf_overrides = AllocaM(int, num_grfs);
9551 for (int i = 0; i < num_grfs; i++) {
9552 grf_overrides[i] = -1;
9553
9554 GRFFile *source = _grf_files[i];
9555 uint32 override = _grf_id_overrides[source->grfid];
9556 if (override == 0) continue;
9557
9558 GRFFile *dest = GetFileByGRFID(override);
9559 if (dest == nullptr) continue;
9560
9561 grf_overrides[i] = find_index(_grf_files, dest);
9562 assert(grf_overrides[i] >= 0);
9563 }
9564
9565 /* Override features and price base multipliers of earlier loaded grfs */
9566 for (int i = 0; i < num_grfs; i++) {
9567 if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9568 GRFFile *source = _grf_files[i];
9569 GRFFile *dest = _grf_files[grf_overrides[i]];
9570
9571 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9572 source->grf_features |= features;
9573 dest->grf_features |= features;
9574
9575 for (Price p = PR_BEGIN; p < PR_END; p++) {
9576 /* No price defined -> nothing to do */
9577 if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9578 Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9579 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9580 }
9581 }
9582
9583 /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9584 for (int i = num_grfs - 1; i >= 0; i--) {
9585 if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9586 GRFFile *source = _grf_files[i];
9587 GRFFile *dest = _grf_files[grf_overrides[i]];
9588
9589 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9590 source->grf_features |= features;
9591 dest->grf_features |= features;
9592
9593 for (Price p = PR_BEGIN; p < PR_END; p++) {
9594 /* Already a price defined -> nothing to do */
9595 if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9596 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9597 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9598 }
9599 }
9600
9601 /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9602 for (int i = 0; i < num_grfs; i++) {
9603 if (grf_overrides[i] < 0) continue;
9604 GRFFile *source = _grf_files[i];
9605 GRFFile *dest = _grf_files[grf_overrides[i]];
9606
9607 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9608 source->grf_features |= features;
9609 dest->grf_features |= features;
9610
9611 for (Price p = PR_BEGIN; p < PR_END; p++) {
9612 if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9613 if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9614 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9615 }
9616 source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9617 }
9618 }
9619
9620 /* Apply fallback prices for grf version < 8 */
9621 for (GRFFile * const file : _grf_files) {
9622 if (file->grf_version >= 8) continue;
9623 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9624 for (Price p = PR_BEGIN; p < PR_END; p++) {
9625 Price fallback_price = _price_base_specs[p].fallback_price;
9626 if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9627 /* No price multiplier has been set.
9628 * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9629 price_base_multipliers[p] = price_base_multipliers[fallback_price];
9630 }
9631 }
9632 }
9633
9634 /* Decide local/global scope of price base multipliers */
9635 for (GRFFile * const file : _grf_files) {
9636 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9637 for (Price p = PR_BEGIN; p < PR_END; p++) {
9638 if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9639 /* No multiplier was set; set it to a neutral value */
9640 price_base_multipliers[p] = 0;
9641 } else {
9642 if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9643 /* The grf does not define any objects of the feature,
9644 * so it must be a difficulty setting. Apply it globally */
9645 Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9646 SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9647 price_base_multipliers[p] = 0;
9648 } else {
9649 Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9650 }
9651 }
9652 }
9653 }
9654 }
9655
9656 extern void InitGRFTownGeneratorNames();
9657
9659 static void AfterLoadGRFs()
9660 {
9661 for (StringIDMapping &it : _string_to_grf_mapping) {
9662 *it.target = MapGRFStringID(it.grfid, it.source);
9663 }
9664 _string_to_grf_mapping.clear();
9665
9666 /* Free the action 6 override sprites. */
9667 for (GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.begin(); it != _grf_line_to_action6_sprite_override.end(); it++) {
9668 free((*it).second);
9669 }
9670 _grf_line_to_action6_sprite_override.clear();
9671
9672 /* Polish cargoes */
9673 FinaliseCargoArray();
9674
9675 /* Pre-calculate all refit masks after loading GRF files. */
9676 CalculateRefitMasks();
9677
9678 /* Polish engines */
9679 FinaliseEngineArray();
9680
9681 /* Set the actually used Canal properties */
9682 FinaliseCanals();
9683
9684 /* Add all new houses to the house array. */
9685 FinaliseHouseArray();
9686
9687 /* Add all new industries to the industry array. */
9688 FinaliseIndustriesArray();
9689
9690 /* Add all new objects to the object array. */
9691 FinaliseObjectsArray();
9692
9693 InitializeSortedCargoSpecs();
9694
9695 /* Sort the list of industry types. */
9696 SortIndustryTypes();
9697
9698 /* Create dynamic list of industry legends for smallmap_gui.cpp */
9699 BuildIndustriesLegend();
9700
9701 /* Build the routemap legend, based on the available cargos */
9702 BuildLinkStatsLegend();
9703
9704 /* Add all new airports to the airports array. */
9705 FinaliseAirportsArray();
9706 BindAirportSpecs();
9707
9708 /* Update the townname generators list */
9709 InitGRFTownGeneratorNames();
9710
9711 /* Run all queued vehicle list order changes */
9712 CommitVehicleListOrderChanges();
9713
9714 /* Load old shore sprites in new position, if they were replaced by ActionA */
9715 ActivateOldShore();
9716
9717 /* Load old tram depot sprites in new position, if no new ones are present */
9718 ActivateOldTramDepot();
9719
9720 /* Set up custom rail types */
9721 InitRailTypes();
9722 InitRoadTypes();
9723
9724 for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9725 if (_gted[e->index].rv_max_speed != 0) {
9726 /* Set RV maximum speed from the mph/0.8 unit value */
9727 e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9728 }
9729
9730 RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9731
9732 const GRFFile *file = e->GetGRF();
9733 if (file == nullptr || _gted[e->index].roadtramtype == 0) {
9734 e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
9735 continue;
9736 }
9737
9738 /* Remove +1 offset. */
9739 _gted[e->index].roadtramtype--;
9740
9741 const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
9742 if (_gted[e->index].roadtramtype < list->size())
9743 {
9744 RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
9745 RoadType rt = GetRoadTypeByLabel(rtl);
9746 if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
9747 e->u.road.roadtype = rt;
9748 continue;
9749 }
9750 }
9751
9752 /* Road type is not available, so disable this engine */
9753 e->info.climates = 0;
9754 }
9755
9756 for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
9757 RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
9758 if (railtype == INVALID_RAILTYPE) {
9759 /* Rail type is not available, so disable this engine */
9760 e->info.climates = 0;
9761 } else {
9762 e->u.rail.railtype = railtype;
9763 }
9764 }
9765
9766 SetYearEngineAgingStops();
9767
9768 FinalisePriceBaseMultipliers();
9769
9770 /* Deallocate temporary loading data */
9771 free(_gted);
9772 _grm_sprites.clear();
9773 }
9774
9780 void LoadNewGRF(uint load_index, uint num_baseset)
9781 {
9782 /* In case of networking we need to "sync" the start values
9783 * so all NewGRFs are loaded equally. For this we use the
9784 * start date of the game and we set the counters, etc. to
9785 * 0 so they're the same too. */
9786 Date date = _date;
9787 Year year = _cur_year;
9788 DateFract date_fract = _date_fract;
9789 uint16 tick_counter = _tick_counter;
9790 byte display_opt = _display_opt;
9791
9792 if (_networking) {
9793 _cur_year = _settings_game.game_creation.starting_year;
9794 _date = ConvertYMDToDate(_cur_year, 0, 1);
9795 _date_fract = 0;
9796 _tick_counter = 0;
9797 _display_opt = 0;
9798 }
9799
9800 InitializeGRFSpecial();
9801
9802 ResetNewGRFData();
9803
9804 /*
9805 * Reset the status of all files, so we can 'retry' to load them.
9806 * This is needed when one for example rearranges the NewGRFs in-game
9807 * and a previously disabled NewGRF becomes usable. If it would not
9808 * be reset, the NewGRF would remain disabled even though it should
9809 * have been enabled.
9810 */
9811 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9812 if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
9813 }
9814
9815 _cur.spriteid = load_index;
9816
9817 /* Load newgrf sprites
9818 * in each loading stage, (try to) open each file specified in the config
9819 * and load information from it. */
9820 for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
9821 /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
9822 * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
9823 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9824 if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
9825 }
9826
9827 if (stage == GLS_RESERVE) {
9828 static const uint32 overrides[][2] = {
9829 { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
9830 { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
9831 { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
9832 };
9833 for (size_t i = 0; i < lengthof(overrides); i++) {
9834 SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
9835 }
9836 }
9837
9838 uint num_grfs = 0;
9839 uint num_non_static = 0;
9840
9841 _cur.stage = stage;
9842 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9843 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
9844 if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
9845
9846 Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
9847 if (!FioCheckFileExists(c->filename, subdir)) {
9848 Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
9849 c->status = GCS_NOT_FOUND;
9850 continue;
9851 }
9852
9853 if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
9854
9855 if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
9856 if (num_non_static == NETWORK_MAX_GRF_COUNT) {
9857 Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
9858 c->status = GCS_DISABLED;
9859 c->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9860 continue;
9861 }
9862 num_non_static++;
9863 }
9864
9865 num_grfs++;
9866
9867 LoadNewGRFFile(c, stage, subdir, false);
9868 if (stage == GLS_RESERVE) {
9869 SetBit(c->flags, GCF_RESERVED);
9870 } else if (stage == GLS_ACTIVATION) {
9871 ClrBit(c->flags, GCF_RESERVED);
9872 assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
9873 ClearTemporaryNewGRFData(_cur.grffile);
9874 BuildCargoTranslationMap();
9875 Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
9876 } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
9877 /* We're not going to activate this, so free whatever data we allocated */
9878 ClearTemporaryNewGRFData(_cur.grffile);
9879 }
9880 }
9881 }
9882
9883 /* Pseudo sprite processing is finished; free temporary stuff */
9884 _cur.ClearDataForNextFile();
9885
9886 /* Call any functions that should be run after GRFs have been loaded. */
9887 AfterLoadGRFs();
9888
9889 /* Now revert back to the original situation */
9890 _cur_year = year;
9891 _date = date;
9892 _date_fract = date_fract;
9893 _tick_counter = tick_counter;
9894 _display_opt = display_opt;
9895 }
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:8446
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:124
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:7830
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:8110
RoadTypeInfo::new_engine
StringID new_engine
Name of an engine for this type of road in the engine preview GUI.
Definition: road.h:105
StationChangeInfo
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
Define properties for stations.
Definition: newgrf.cpp:1875
ParamSet
static void ParamSet(ByteReader *buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:7104
GRFLocation
Definition: newgrf.cpp:360
TE_WATER
@ TE_WATER
Cargo behaves water-like.
Definition: cargotype.h:32
CalculateRefitMasks
static void CalculateRefitMasks()
Precalculate refit masks from cargo classes for all vehicles.
Definition: newgrf.cpp:8765
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:101
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:175
EngineInfo::base_life
Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life.
Definition: engine_type.h:136
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:6120
OrderSettings::improved_load
bool improved_load
improved loading algorithm
Definition: settings_type.h:468
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:75
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:3776
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:313
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:70
AllowedSubtags::AllowedSubtags
AllowedSubtags()
Create empty subtags object used to identify the end of a list.
Definition: newgrf.cpp:8045
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
RAILTYPE_MAGLEV
@ RAILTYPE_MAGLEV
Maglev.
Definition: rail_type.h:32
ResetCustomObjects
static void ResetCustomObjects()
Reset and clear all NewObjects.
Definition: newgrf.cpp:8527
RailVehicleInfo::pow_wag_weight
byte pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition: engine_type.h:56
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:161
IndustrySpec::map_colour
byte map_colour
colour used for the small map
Definition: industrytype.h:126
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:89
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:140
GRFFile::roadtype_list
std::vector< RoadTypeLabel > roadtype_list
Roadtype translation table (road)
Definition: newgrf.h:132
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:473
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:8092
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:588
WChar
char32_t WChar
Type for wide characters, i.e.
Definition: string_type.h:35
ResetCustomAirports
static void ResetCustomAirports()
Reset and clear all NewGRF airports.
Definition: newgrf.cpp:8461
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:4030
EngineIDMapping::grfid
uint32 grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:168
RoadTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: road.h:102
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:103
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:102
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:1549
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:58
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:60
GrfProcessingState::grffile
GRFFile * grffile
Currently processed GRF file.
Definition: newgrf.cpp:103
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:66
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:8498
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:66
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1525
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:321
StringIDMapping::grfid
uint32 grfid
Source NewGRF.
Definition: newgrf.cpp:474
ShipVehicleInfo::canal_speed_frac
byte canal_speed_frac
Fraction of maximum speed for canal/river tiles.
Definition: engine_type.h:76
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:174
_engine_counts
const uint8 _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:50
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:8055
GRFFile::price_base_multipliers
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:146
FeatureTownName
static void FeatureTownName(ByteReader *buf)
Action 0x0F - Define Town names.
Definition: newgrf.cpp:7454
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:3396
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:8107
HandleNodes
static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
Handle the contents of a 'C' choice of an Action14.
Definition: newgrf.cpp:8302
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:179
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:1540
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:611
_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
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:27
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:8937
RailtypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: rail.h:177
TE_FOOD
@ TE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:33
GRFFile::grf_features
uint32 grf_features
Bitset of GrfSpecFeature the grf uses.
Definition: newgrf.h:145
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:334
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:107
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:93
A5BLOCK_INVALID
@ A5BLOCK_INVALID
unknown/not-implemented type
Definition: newgrf.cpp:6115
Action5BlockType
Action5BlockType
The type of action 5 type.
Definition: newgrf.cpp:6112
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:7977
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:204
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:119
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:8660
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:49
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:114
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:7911
SortIndustryTypes
void SortIndustryTypes()
Initialize the list of sorted industry types.
Definition: industry_gui.cpp:208
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:874
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:7946
ResetRailTypes
void ResetRailTypes()
Reset all rail type information to its default values.
Definition: rail_cmd.cpp:63
GrfProcessingState::spritesets
std::map< uint, SpriteSet > spritesets[GSF_END]
Currently referenceable spritesets.
Definition: newgrf.cpp:94
GrfProcessingState::spriteid
SpriteID spriteid
First available SpriteID for loading realsprites.
Definition: newgrf.cpp:99
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:483
CIR_INVALID_ID
@ CIR_INVALID_ID
Attempt to modify an invalid ID.
Definition: newgrf.cpp:1002
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:597
_tags_info
AllowedSubtags _tags_info[]
Action14 tags for the INFO node.
Definition: newgrf.cpp:8198
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:8328
GRFParameterInfo::def_value
uint32 def_value
Default value of this parameter.
Definition: newgrf_config.h:142
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:26
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:977
newgrf_airport.h
SetupCargoForClimate
void SetupCargoForClimate(LandscapeID l)
Set up the default cargo types for the given landscape type.
Definition: cargotype.cpp:39
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:69
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:168
SetupEngines
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:529
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
TE_NONE
@ TE_NONE
Cargo has no effect.
Definition: cargotype.h:28
AircraftVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
Definition: engine_type.h:105
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:8067
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:83
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:48
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:133
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:7960
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:102
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:4952
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:134
CIR_SUCCESS
@ CIR_SUCCESS
Variable was parsed and read.
Definition: newgrf.cpp:998
MAX_SPRITEGROUP
static const uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
Definition: newgrf.cpp:82
GRFLoadedFeatures::used_liveries
uint64 used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:176
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:494
RoadTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: road.h:104
AllowedSubtags::text
TextHandler text
Callback function for a text node, only valid if type == 'T'.
Definition: newgrf.cpp:8104
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:27
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:169
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:3051
_tags_parameters
AllowedSubtags _tags_parameters[]
Action14 parameter tags.
Definition: newgrf.cpp:8154
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:126
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:163
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:24
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:7777
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:9542
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
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:65
GRFFile::GetParam
uint32 GetParam(uint number) const
Get GRF Parameter with range checking.
Definition: newgrf.h:152
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:496
ObjectSpec::callback_mask
uint16 callback_mask
Bitmask of requested/allowed callbacks.
Definition: newgrf_object.h:72
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
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:71
CIR_UNHANDLED
@ CIR_UNHANDLED
Variable was parsed but unread.
Definition: newgrf.cpp:1000
RoadVehicleInfo::air_drag
uint8 air_drag
Coefficient of air drag.
Definition: engine_type.h:123
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
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:577
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:138
AirportChangeInfo
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
Define properties for airports.
Definition: newgrf.cpp:3805
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
IsInsideMM
static bool IsInsideMM(const T x, const size_t min, const size_t max)
Checks if a value is in an interval.
Definition: math_func.hpp:204
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:68
TE_MAIL
@ TE_MAIL
Cargo behaves mail-like.
Definition: cargotype.h:30
StringIDMapping::target
StringID * target
Destination for mapping result.
Definition: newgrf.cpp:476
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:135
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:142
GrfProcessingState::SpriteSet::sprite
SpriteID sprite
SpriteID of the first sprite of the set.
Definition: newgrf.cpp:89
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:142
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
TE_PASSENGERS
@ TE_PASSENGERS
Cargo behaves passenger-like.
Definition: cargotype.h:29
ShipVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:74
RoadVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:118
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:318
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:584
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
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:84
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:175
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:57
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:150
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:6542
LoadNewGRF
void LoadNewGRF(uint load_index, uint num_baseset)
Load all the NewGRFs.
Definition: newgrf.cpp:9780
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:9454
SHORE_REPLACE_NONE
@ SHORE_REPLACE_NONE
No shore sprites were replaced.
Definition: newgrf.h:162
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:54
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:520
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:177
_gted
static GRFTempEngineData * _gted
Temporary engine data used during NewGRF loading.
Definition: newgrf.cpp:349
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:119
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:52
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:583
VE_TYPE_START
@ VE_TYPE_START
First bit used for the type of effect.
Definition: vehicle_base.h:82
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:135
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:645
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:60
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:2559
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:475
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:886
IndustrySpec::conflicting
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:112
EngineInfo::callback_mask
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:144
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:9164
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:8171
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:255
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:74
CargoSpec::IsValid
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:100
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:112
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:8034
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:124
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:1538
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:541
EF_USES_2CC
@ EF_USES_2CC
Vehicle uses two company colours.
Definition: engine_type.h:156
ROADTYPE_TRAM
@ ROADTYPE_TRAM
Trams.
Definition: road_type.h:25
SHORE_REPLACE_ONLY_NEW
@ SHORE_REPLACE_ONLY_NEW
Only corner-shores were loaded by Action5 (openttd(w/d).grf only).
Definition: newgrf.h:165
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:28
AircraftVehicleInfo::max_range
uint16 max_range
Maximum range of this aircraft.
Definition: engine_type.h:108
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:9066
GrfProcessingState::SpriteSet
Definition of a single Action1 spriteset.
Definition: newgrf.cpp:88
CargoSpec::multipliertowngrowth
uint16 multipliertowngrowth
Size of the effect.
Definition: cargotype.h:69
LoadNewGRFFileFromFile
static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
Load a particular NewGRF from a SpriteFile.
Definition: newgrf.cpp:9365
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:81
StaticGRFInfo
static void StaticGRFInfo(ByteReader *buf)
Handle Action 0x14.
Definition: newgrf.cpp:8317
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:552
AfterLoadGRFs
static void AfterLoadGRFs()
Finish loading NewGRFs and execute needed post-processing.
Definition: newgrf.cpp:9659
_cur_parameter
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:7943
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:189
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:163
StringIDMapping
Information for mapping static StringIDs.
Definition: newgrf.cpp:473
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:53
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:3374
RoadTypeInfo::alternate_labels
RoadTypeLabelList alternate_labels
Road type labels this type provides in addition to the main label.
Definition: road.h:149
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:7844
_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:78
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:586
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:8264
_tick_counter
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:30
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:6127
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
GRFFile::label
GRFLabel * label
Pointer to the first label. This is a linked list, not an array.
Definition: newgrf.h:124
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:7999
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:8124
ImportGRFSound
static void ImportGRFSound(SoundEntry *sound)
Process a sound import from another GRF file.
Definition: newgrf.cpp:7569
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:122
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:76
GrfProcessingState
Temporary data during loading of GRFs.
Definition: newgrf.cpp:85
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1537
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:64
_tags_root
AllowedSubtags _tags_root[]
Action14 root tags.
Definition: newgrf.cpp:8212
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:9233
GRFTempEngineData::EMPTY
@ EMPTY
GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
Definition: newgrf.cpp:320
TranslateRefitMask
static CargoTypes TranslateRefitMask(uint32 refit_mask)
Translate the refit mask.
Definition: newgrf.cpp:960
ObjectSpec::height
uint8 height
The height of this structure, in heightlevels; max MAX_TILE_HEIGHT.
Definition: newgrf_object.h:73
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
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:57
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:2092
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:2576
GlobalVarChangeInfo
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
Define properties for global variables.
Definition: newgrf.cpp:2616
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:61
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:100
error.h
GrfProcessingState::GetSprite
SpriteID GetSprite(byte feature, uint set) const
Returns the first sprite of a spriteset.
Definition: newgrf.cpp:175
RailVehicleChangeInfo
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for rail vehicles.
Definition: newgrf.cpp:1057
CargoSpec::is_freight
bool is_freight
Cargo type is considered to be freight (affects train freight multiplier).
Definition: cargotype.h:67
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
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:328
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:167
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:80
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:145
GetNewEngineID
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
Return the ID of a new engine.
Definition: newgrf.cpp:707
RailVehicleInfo::tractive_effort
byte tractive_effort
Tractive effort coefficient.
Definition: engine_type.h:59
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:143
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:171
CargoChangeInfo
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
Define properties for cargoes.
Definition: newgrf.cpp:2912
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:104
TLF_NON_GROUND_FLAGS
@ TLF_NON_GROUND_FLAGS
Flags which do not work for the (first) ground sprite.
Definition: newgrf_commons.h:56
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:22
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:76
RailVehicleInfo::pow_wag_power
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:55
RailtypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: rail.h:174
OTTDByteReaderSignal
Definition: newgrf.cpp:209
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:49
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:301
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:1539
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:3284
GRFTempEngineData::refittability
Refittability refittability
Did the newgrf set any refittability property? If not, default refittability will be applied.
Definition: newgrf.cpp:329
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:143
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:6113
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:6114
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:8675
Utf8Decode
size_t Utf8Decode(WChar *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:574
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:58
ShipVehicleInfo::old_refittable
bool old_refittable
Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
Definition: engine_type.h:73
AllowedSubtags::type
byte type
The type of the node, must be one of 'C', 'B' or 'T'.
Definition: newgrf.cpp:8101
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:626
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:62
ChangeGRFBlitter
static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
Callback function for 'INFO'->'BLTR' to set the blitter info.
Definition: newgrf.cpp:7889
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:8948
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:7851
GRFTempEngineData::UNSET
@ UNSET
No properties assigned. Default refit masks shall be activated.
Definition: newgrf.cpp:319
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:7924
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
TE_GOODS
@ TE_GOODS
Cargo behaves goods/candy-like.
Definition: cargotype.h:31
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:337
ObjectSpec::clear_cost_multiplier
uint8 clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_object.h:67
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:75
GRFFile::canal_local_properties
CanalProperties canal_local_properties[CF_END]
Canal properties as set by this NewGRF.
Definition: newgrf.h:138
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:184
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:7837
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:176
CIR_DISABLED
@ CIR_DISABLED
GRF was disabled due to error.
Definition: newgrf.cpp:999
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:158
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:8715
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:491
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:125
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:9020
IndustrytilesChangeInfo
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
Define properties for industry tiles.
Definition: newgrf.cpp:3146
RailVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:47
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:316
CC_ARMOURED
@ CC_ARMOURED
Armoured cargo (Valuables, Gold, Diamonds)
Definition: cargotype.h:44
ResetNewGRFErrors
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8553
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:8542
GRFLoadedFeatures::tram
TramReplacement tram
In which way tram depots were replaced.
Definition: newgrf.h:178
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:8043
FinaliseAirportsArray
static void FinaliseAirportsArray()
Add all new airports to the airport array.
Definition: newgrf.cpp:9252
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:164
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:6090
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:74
TRAMWAY_REPLACE_DEPOT_WITH_TRACK
@ TRAMWAY_REPLACE_DEPOT_WITH_TRACK
Electrified depot graphics with tram track were loaded.
Definition: newgrf.h:170
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:723
GetGlobalVariable
bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
Definition: newgrf.cpp:6260
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:1014
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:335
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:8108
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:8033
Action5Type::block_type
Action5BlockType block_type
How is this Action5 type processed?
Definition: newgrf.cpp:6119
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:75
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:6121
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:86
InitializeSortedCargoSpecs
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
Definition: cargotype.cpp:188
GrfProcessingState::AddSpriteSets
void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
Records new spritesets.
Definition: newgrf.cpp:134
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:169
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:61
AlterVehicleListOrder
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
Definition: newgrf_engine.cpp:1291
CargoSpec::classes
uint16 classes
Classes of this cargo type.
Definition: cargotype.h:80
RoadVehicleChangeInfo
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for road vehicles.
Definition: newgrf.cpp:1355
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:171
RoadTypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: road.h:154
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:616
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:340
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:127
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:484
InitNewGRFFile
static void InitNewGRFFile(const GRFConfig *config)
Prepare loading a NewGRF file with its config.
Definition: newgrf.cpp:8698
CommitVehicleListOrderChanges
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
Definition: newgrf_engine.cpp:1321
ShipVehicleInfo
Information about a ship vehicle.
Definition: engine_type.h:66
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
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:72
PROP_ROADVEH_CARGO_CAPACITY
@ PROP_ROADVEH_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:34
ResetNewGRFData
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8566
AircraftVehicleChangeInfo
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for aircraft.
Definition: newgrf.cpp:1721
GRFFile::cargo_list
std::vector< CargoLabel > cargo_list
Cargo translation table (local ID -> label)
Definition: newgrf.h:126
GameCreationSettings::starting_year
Year starting_year
starting date
Definition: settings_type.h:306
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
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:9527
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:122
GrfProcessingState::stage
GrfLoadingStage stage
Current loading stage.
Definition: newgrf.cpp:98
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:3984
CHECK_NOTHING
@ CHECK_NOTHING
Always succeeds.
Definition: industrytype.h:40
AircraftVehicleInfo::mail_capacity
byte mail_capacity
Mail capacity (bags).
Definition: engine_type.h:106
CargoSpec::name_single
StringID name_single
Name of a single entity of this type of cargo.
Definition: cargotype.h:73
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:187
CargoSpec::abbrev
StringID abbrev
Two letter abbreviation for this cargo type.
Definition: cargotype.h:76
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:120
Action5Type::name
const char * name
Name for error messages.
Definition: newgrf.cpp:6123
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, byte type, uint16 num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:125
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:137
FinaliseHouseArray
static void FinaliseHouseArray()
Add all new houses to the house array.
Definition: newgrf.cpp:9093
GRFConfig::palette
uint8 palette
GRFPalette, bitset.
Definition: newgrf_config.h:179
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:132
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:58
_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:129
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:1001
GRFTempEngineData::NONEMPTY
@ NONEMPTY
GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not av...
Definition: newgrf.cpp:321
AllowedSubtags::id
uint32 id
The identifier for this node.
Definition: newgrf.cpp:8100
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
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:378
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
SPR_FLAGS_BASE
static const SpriteID SPR_FLAGS_BASE
Flags sprites (in same order as enum NetworkLanguage)
Definition: sprites.h:297
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:139
InitializeGRFSpecial
static void InitializeGRFSpecial()
Initialize the TTDPatch flags.
Definition: newgrf.cpp:8338
DataHandler
bool(* DataHandler)(size_t, ByteReader *)
Type of callback function for binary nodes.
Definition: newgrf.cpp:8032
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:9490
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:121
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:8224
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:159
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:16
IgnoreTownHouseProperty
static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
Ignore a house property.
Definition: newgrf.cpp:2240
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
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:492
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
EF_RAIL_FLIPS
@ EF_RAIL_FLIPS
Rail vehicle can be flipped in the depot.
Definition: engine_type.h:158
GrfProcessingState::SpriteSet::num_sprites
uint num_sprites
Number of sprites in the set.
Definition: newgrf.cpp:90
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:997
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:2130
LiveryScheme
LiveryScheme
List of different livery schemes.
Definition: livery.h:20
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:2598
VehicleSettings::plane_speed
uint8 plane_speed
divisor for speed of aircraft
Definition: settings_type.h:489
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:4166
Engine::grf_prop
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:64
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:550
ShipVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:69
GRFTempEngineData::prop27_set
bool prop27_set
Did the NewGRF set property 27 (misc flags)?
Definition: newgrf.cpp:330
RailVehicleInfo::running_cost
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition: engine_type.h:50
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:155
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:500
FinaliseCargoArray
static void FinaliseCargoArray()
Check for invalid cargoes.
Definition: newgrf.cpp:8997
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:578
GrfProcessingState::IsValidSpriteSet
bool IsValidSpriteSet(byte feature, uint set) const
Check whether a specific set is defined.
Definition: newgrf.cpp:163
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:585
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:206
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:139
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:678
ResetRoadTypes
void ResetRoadTypes()
Reset all road type information to its default values.
Definition: road_cmd.cpp:62
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
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:8020
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:74
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:53
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:7537
ByteReader
Class to read from a NewGRF file.
Definition: newgrf.cpp:212
LoadGRFSound
static void LoadGRFSound(size_t offs, SoundEntry *sound)
Load a sound from a file.
Definition: newgrf.cpp:7600
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32 id, BranchHandler handler)
Create a branch node with a callback handler.
Definition: newgrf.cpp:8079
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:499
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:83
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:8103
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:146
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition: engine_type.h:98
GetLanguage
const LanguageMetadata * GetLanguage(byte newgrflangid)
Get the language with the given NewGRF language ID.
Definition: strings.cpp:1885
ObjectSpec::climate
uint8 climate
In which climates is this object available?
Definition: newgrf_object.h:64
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:460
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
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:563
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:2307
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:73
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:490
ChangeGRFPalette
static bool ChangeGRFPalette(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PALS' to set the number of valid parameters.
Definition: newgrf.cpp:7863
LoadFontGlyph
static void LoadFontGlyph(ByteReader *buf)
Action 0x12.
Definition: newgrf.cpp:7720
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:174
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:138
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:447
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:118
RoadTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: road.h:103
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:108
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:95
ResetCustomStations
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8426
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:394
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:518
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:77
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:7953
EngineInfo::cargo_age_period
uint16 cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:147
GrfProcessingState::nfo_line
uint32 nfo_line
Currently processed pseudo sprite number in the GRF.
Definition: newgrf.cpp:105
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:169
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:865
GetCargoIDByLabel
CargoID GetCargoIDByLabel(CargoLabel cl)
Get the cargo ID by cargo label.
Definition: cargotype.cpp:107
newgrf_cargo.h
SetYearEngineAgingStops
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:601
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:129
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:754
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:7751
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:486
GetGRFConfig
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:762
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:6118
_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:62
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:469
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:6122
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:105
ObjectSpec::cls_id
ObjectClassID cls_id
The class to which this spec belongs.
Definition: newgrf_object.h:61
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:75
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:46
IgnoreIndustryTileProperty
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
Ignore an industry tile property.
Definition: newgrf.cpp:3106
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:134
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:70
RoadTypeChangeInfo
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
Define properties for roadtypes.
Definition: newgrf.cpp:4384
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:812
GRFP_BLT_MASK
@ GRFP_BLT_MASK
Bitmask to only get the blitter information.
Definition: newgrf_config.h:78