OpenTTD Source  14.0-RC1
newgrf.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 
12 #include "core/container_func.hpp"
13 #include "debug.h"
14 #include "fileio_func.h"
15 #include "engine_func.h"
16 #include "engine_base.h"
17 #include "bridge.h"
18 #include "town.h"
19 #include "newgrf_engine.h"
20 #include "newgrf_text.h"
21 #include "fontcache.h"
22 #include "currency.h"
23 #include "landscape.h"
24 #include "newgrf_cargo.h"
25 #include "newgrf_house.h"
26 #include "newgrf_sound.h"
27 #include "newgrf_station.h"
28 #include "industrytype.h"
29 #include "industry_map.h"
30 #include "newgrf_canal.h"
31 #include "newgrf_townname.h"
32 #include "newgrf_industries.h"
33 #include "newgrf_airporttiles.h"
34 #include "newgrf_airport.h"
35 #include "newgrf_object.h"
36 #include "rev.h"
37 #include "fios.h"
38 #include "strings_func.h"
39 #include "timer/timer_game_tick.h"
41 #include "string_func.h"
42 #include "network/core/config.h"
43 #include "smallmap_gui.h"
44 #include "genworld.h"
45 #include "error.h"
46 #include "error_func.h"
47 #include "vehicle_func.h"
48 #include "language.h"
49 #include "vehicle_base.h"
50 #include "road.h"
51 #include "newgrf_roadstop.h"
52 
53 #include "table/strings.h"
54 #include "table/build_industry.h"
55 
56 #include "safeguards.h"
57 
58 /* TTDPatch extended GRF format codec
59  * (c) Petr Baudis 2004 (GPL'd)
60  * Changes by Florian octo Forster are (c) by the OpenTTD development team.
61  *
62  * Contains portions of documentation by TTDPatch team.
63  * Thanks especially to Josef Drexler for the documentation as well as a lot
64  * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
65  * served as subject to the initial testing of this codec. */
66 
68 static std::vector<GRFFile *> _grf_files;
69 
70 const std::vector<GRFFile *> &GetAllGRFFiles()
71 {
72  return _grf_files;
73 }
74 
77 
79 static uint32_t _ttdpatch_flags[8];
80 
83 
84 static const uint MAX_SPRITEGROUP = UINT8_MAX;
85 
88 private:
90  struct SpriteSet {
92  uint num_sprites;
93  };
94 
96  std::map<uint, SpriteSet> spritesets[GSF_END];
97 
98 public:
99  /* Global state */
100  GrfLoadingStage stage;
102 
103  /* Local state in the file */
107  uint32_t nfo_line;
108 
109  /* Kind of return values when processing certain actions */
111 
112  /* Currently referenceable spritegroups */
113  const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
114 
117  {
118  this->nfo_line = 0;
119  this->skip_sprites = 0;
120 
121  for (uint i = 0; i < GSF_END; i++) {
122  this->spritesets[i].clear();
123  }
124 
125  memset(this->spritegroups, 0, sizeof(this->spritegroups));
126  }
127 
136  void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
137  {
138  assert(feature < GSF_END);
139  for (uint i = 0; i < numsets; i++) {
140  SpriteSet &set = this->spritesets[feature][first_set + i];
141  set.sprite = first_sprite + i * numents;
142  set.num_sprites = numents;
143  }
144  }
145 
152  bool HasValidSpriteSets(byte feature) const
153  {
154  assert(feature < GSF_END);
155  return !this->spritesets[feature].empty();
156  }
157 
165  bool IsValidSpriteSet(byte feature, uint set) const
166  {
167  assert(feature < GSF_END);
168  return this->spritesets[feature].find(set) != this->spritesets[feature].end();
169  }
170 
177  SpriteID GetSprite(byte feature, uint set) const
178  {
179  assert(IsValidSpriteSet(feature, set));
180  return this->spritesets[feature].find(set)->second.sprite;
181  }
182 
189  uint GetNumEnts(byte feature, uint set) const
190  {
191  assert(IsValidSpriteSet(feature, set));
192  return this->spritesets[feature].find(set)->second.num_sprites;
193  }
194 };
195 
196 static GrfProcessingState _cur;
197 
198 
205 template <VehicleType T>
206 static inline bool IsValidNewGRFImageIndex(uint8_t image_index)
207 {
208  return image_index == 0xFD || IsValidImageIndex<T>(image_index);
209 }
210 
212 
214 class ByteReader {
215 protected:
216  byte *data;
217  byte *end;
218 
219 public:
220  ByteReader(byte *data, byte *end) : data(data), end(end) { }
221 
222  inline byte *ReadBytes(size_t size)
223  {
224  if (data + size >= end) {
225  /* Put data at the end, as would happen if every byte had been individually read. */
226  data = end;
227  throw OTTDByteReaderSignal();
228  }
229 
230  byte *ret = data;
231  data += size;
232  return ret;
233  }
234 
235  inline byte ReadByte()
236  {
237  if (data < end) return *(data)++;
238  throw OTTDByteReaderSignal();
239  }
240 
241  uint16_t ReadWord()
242  {
243  uint16_t val = ReadByte();
244  return val | (ReadByte() << 8);
245  }
246 
247  uint16_t ReadExtendedByte()
248  {
249  uint16_t val = ReadByte();
250  return val == 0xFF ? ReadWord() : val;
251  }
252 
253  uint32_t ReadDWord()
254  {
255  uint32_t val = ReadWord();
256  return val | (ReadWord() << 16);
257  }
258 
259  uint32_t ReadVarSize(byte size)
260  {
261  switch (size) {
262  case 1: return ReadByte();
263  case 2: return ReadWord();
264  case 4: return ReadDWord();
265  default:
266  NOT_REACHED();
267  return 0;
268  }
269  }
270 
271  const char *ReadString()
272  {
273  char *string = reinterpret_cast<char *>(data);
274  size_t string_length = ttd_strnlen(string, Remaining());
275 
276  if (string_length == Remaining()) {
277  /* String was not NUL terminated, so make sure it is now. */
278  string[string_length - 1] = '\0';
279  GrfMsg(7, "String was not terminated with a zero byte.");
280  } else {
281  /* Increase the string length to include the NUL byte. */
282  string_length++;
283  }
284  Skip(string_length);
285 
286  return string;
287  }
288 
289  inline size_t Remaining() const
290  {
291  return end - data;
292  }
293 
294  inline bool HasData(size_t count = 1) const
295  {
296  return data + count <= end;
297  }
298 
299  inline byte *Data()
300  {
301  return data;
302  }
303 
304  inline void Skip(size_t len)
305  {
306  data += len;
307  /* It is valid to move the buffer to exactly the end of the data,
308  * as there may not be any more data read. */
309  if (data > end) throw OTTDByteReaderSignal();
310  }
311 };
312 
313 typedef void (*SpecialSpriteHandler)(ByteReader *buf);
314 
316 static const uint NUM_STATIONS_PER_GRF = UINT16_MAX - 1;
317 
322  UNSET = 0,
325  };
326 
327  uint16_t cargo_allowed;
328  uint16_t cargo_disallowed;
329  RailTypeLabel railtypelabel;
330  uint8_t roadtramtype;
333  uint8_t rv_max_speed;
334  CargoTypes ctt_include_mask;
335  CargoTypes ctt_exclude_mask;
336 
341  void UpdateRefittability(bool non_empty)
342  {
343  if (non_empty) {
344  this->refittability = NONEMPTY;
345  } else if (this->refittability == UNSET) {
346  this->refittability = EMPTY;
347  }
348  }
349 };
350 
351 static std::vector<GRFTempEngineData> _gted;
352 
357 static uint32_t _grm_engines[256];
358 
360 static uint32_t _grm_cargoes[NUM_CARGO * 2];
361 
362 struct GRFLocation {
363  uint32_t grfid;
364  uint32_t nfoline;
365 
366  GRFLocation(uint32_t grfid, uint32_t nfoline) : grfid(grfid), nfoline(nfoline) { }
367 
368  bool operator<(const GRFLocation &other) const
369  {
370  return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
371  }
372 
373  bool operator == (const GRFLocation &other) const
374  {
375  return this->grfid == other.grfid && this->nfoline == other.nfoline;
376  }
377 };
378 
379 static std::map<GRFLocation, SpriteID> _grm_sprites;
380 typedef std::map<GRFLocation, std::vector<byte>> GRFLineToSpriteOverride;
381 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
382 
393 void GrfMsgI(int severity, const std::string &msg)
394 {
395  Debug(grf, severity, "[{}:{}] {}", _cur.grfconfig->filename, _cur.nfo_line, msg);
396 }
397 
403 static GRFFile *GetFileByGRFID(uint32_t grfid)
404 {
405  for (GRFFile * const file : _grf_files) {
406  if (file->grfid == grfid) return file;
407  }
408  return nullptr;
409 }
410 
416 static GRFFile *GetFileByFilename(const std::string &filename)
417 {
418  for (GRFFile * const file : _grf_files) {
419  if (file->filename == filename) return file;
420  }
421  return nullptr;
422 }
423 
426 {
427  gf->labels.clear();
428 }
429 
436 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
437 {
438  GRFFile *file;
439  if (config != nullptr) {
440  file = GetFileByGRFID(config->ident.grfid);
441  } else {
442  config = _cur.grfconfig;
443  file = _cur.grffile;
444  }
445 
446  config->status = GCS_DISABLED;
447  if (file != nullptr) ClearTemporaryNewGRFData(file);
448  if (config == _cur.grfconfig) _cur.skip_sprites = -1;
449 
450  if (message == STR_NULL) return nullptr;
451 
452  config->error = {STR_NEWGRF_ERROR_MSG_FATAL, message};
453  if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
454  return &config->error.value();
455 }
456 
461  uint32_t grfid;
464 };
465 typedef std::vector<StringIDMapping> StringIDMappingVector;
466 static StringIDMappingVector _string_to_grf_mapping;
467 
473 static void AddStringForMapping(StringID source, StringID *target)
474 {
475  *target = STR_UNDEFINED;
476  _string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
477 }
478 
487 {
488  /* StringID table for TextIDs 0x4E->0x6D */
489  static const StringID units_volume[] = {
490  STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
491  STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
492  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
493  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
494  STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
495  STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
496  STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
497  STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
498  };
499 
500  /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
501  assert(!IsInsideMM(str, 0xD000, 0xD7FF));
502 
503 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
504  static_assert(stringend - stringid == end - begin); \
505  if (str >= begin && str <= end) return str + (stringid - begin)
506 
507  /* We have some changes in our cargo strings, resulting in some missing. */
508  TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
509  TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
510  if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
511  TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
512  TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
513  TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
514 
515  /* Map building names according to our lang file changes. There are several
516  * ranges of house ids, all of which need to be remapped to allow newgrfs
517  * to use original house names. */
518  TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
519  TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
520  TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
521 
522  /* Same thing for industries */
523  TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
524  TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
525  TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
526  TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
527  TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
528 
529  switch (str) {
530  case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
531  case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
532  case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
533  }
534 #undef TEXTID_TO_STRINGID
535 
536  if (str == STR_NULL) return STR_EMPTY;
537 
538  Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
539 
540  return STR_EMPTY;
541 }
542 
550 StringID MapGRFStringID(uint32_t grfid, StringID str)
551 {
552  if (IsInsideMM(str, 0xD800, 0x10000)) {
553  /* General text provided by NewGRF.
554  * In the specs this is called the 0xDCxx range (misc persistent texts),
555  * but we meanwhile extended the range to 0xD800-0xFFFF.
556  * Note: We are not involved in the "persistent" business, since we do not store
557  * any NewGRF strings in savegames. */
558  return GetGRFStringID(grfid, str);
559  } else if (IsInsideMM(str, 0xD000, 0xD800)) {
560  /* Callback text provided by NewGRF.
561  * In the specs this is called the 0xD0xx range (misc graphics texts).
562  * These texts can be returned by various callbacks.
563  *
564  * Due to how TTDP implements the GRF-local- to global-textid translation
565  * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
566  * We do not care about that difference and just mask out the 0x400 bit.
567  */
568  str &= ~0x400;
569  return GetGRFStringID(grfid, str);
570  } else {
571  /* The NewGRF wants to include/reference an original TTD string.
572  * Try our best to find an equivalent one. */
574  }
575 }
576 
577 static std::map<uint32_t, uint32_t> _grf_id_overrides;
578 
584 static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
585 {
586  _grf_id_overrides[source_grfid] = target_grfid;
587  GrfMsg(5, "SetNewGRFOverride: Added override of 0x{:X} to 0x{:X}", BSWAP32(source_grfid), BSWAP32(target_grfid));
588 }
589 
598 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access = false)
599 {
600  /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
601  * them use the same engine slots. */
602  uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
604  /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
605  scope_grfid = file->grfid;
606  uint32_t override = _grf_id_overrides[file->grfid];
607  if (override != 0) {
608  scope_grfid = override;
609  const GRFFile *grf_match = GetFileByGRFID(override);
610  if (grf_match == nullptr) {
611  GrfMsg(5, "Tried mapping from GRFID {:x} to {:x} but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
612  } else {
613  GrfMsg(5, "Mapping from GRFID {:x} to {:x}", BSWAP32(file->grfid), BSWAP32(override));
614  }
615  }
616 
617  /* Check if the engine is registered in the override manager */
618  EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
619  if (engine != INVALID_ENGINE) {
620  Engine *e = Engine::Get(engine);
621  if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
622  return e;
623  }
624  }
625 
626  /* Check if there is an unreserved slot */
627  EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
628  if (engine != INVALID_ENGINE) {
629  Engine *e = Engine::Get(engine);
630 
631  if (e->grf_prop.grffile == nullptr) {
632  e->grf_prop.grffile = file;
633  GrfMsg(5, "Replaced engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
634  }
635 
636  /* Reserve the engine slot */
637  if (!static_access) {
638  EngineIDMapping *eid = _engine_mngr.data() + engine;
639  eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
640  }
641 
642  return e;
643  }
644 
645  if (static_access) return nullptr;
646 
647  if (!Engine::CanAllocateItem()) {
648  GrfMsg(0, "Can't allocate any more engines");
649  return nullptr;
650  }
651 
652  size_t engine_pool_size = Engine::GetPoolSize();
653 
654  /* ... it's not, so create a new one based off an existing engine */
655  Engine *e = new Engine(type, internal_id);
656  e->grf_prop.grffile = file;
657 
658  /* Reserve the engine slot */
659  assert(_engine_mngr.size() == e->index);
660  _engine_mngr.push_back({
661  scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
662  internal_id,
663  type,
664  std::min<uint8_t>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
665  });
666 
667  if (engine_pool_size != Engine::GetPoolSize()) {
668  /* Resize temporary engine data ... */
669  _gted.resize(Engine::GetPoolSize());
670  }
671  if (type == VEH_TRAIN) {
672  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
673  }
674 
675  GrfMsg(5, "Created new engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
676 
677  return e;
678 }
679 
690 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
691 {
692  uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
694  scope_grfid = file->grfid;
695  uint32_t override = _grf_id_overrides[file->grfid];
696  if (override != 0) scope_grfid = override;
697  }
698 
699  return _engine_mngr.GetID(type, internal_id, scope_grfid);
700 }
701 
706 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
707 {
708  if (HasBit(grf_sprite->pal, 14)) {
709  ClrBit(grf_sprite->pal, 14);
710  SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
711  }
712 
713  if (HasBit(grf_sprite->sprite, 14)) {
714  ClrBit(grf_sprite->sprite, 14);
716  }
717 
718  if (HasBit(grf_sprite->sprite, 15)) {
719  ClrBit(grf_sprite->sprite, 15);
720  SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
721  }
722 }
723 
737 static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16_t *max_sprite_offset = nullptr, uint16_t *max_palette_offset = nullptr)
738 {
739  grf_sprite->sprite = buf->ReadWord();
740  grf_sprite->pal = buf->ReadWord();
741  TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
742 
743  MapSpriteMappingRecolour(grf_sprite);
744 
745  bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
746  ClrBit(grf_sprite->pal, 15);
747  if (custom_sprite) {
748  /* Use sprite from Action 1 */
749  uint index = GB(grf_sprite->sprite, 0, 14);
750  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
751  GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {}", index);
752  grf_sprite->sprite = SPR_IMG_QUERY;
753  grf_sprite->pal = PAL_NONE;
754  } else {
755  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
756  if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
757  SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
759  }
760  } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
761  GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
762  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
763  return flags;
764  }
765 
766  if (flags & TLF_CUSTOM_PALETTE) {
767  /* Use palette from Action 1 */
768  uint index = GB(grf_sprite->pal, 0, 14);
769  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
770  GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {} for 'palette'", index);
771  grf_sprite->pal = PAL_NONE;
772  } else {
773  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
774  if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
775  SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
777  }
778  } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
779  GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
780  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
781  return flags;
782  }
783 
784  return flags;
785 }
786 
795 static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
796 {
797  if (!(flags & TLF_DRAWING_FLAGS)) return;
798 
799  if (dts->registers == nullptr) dts->AllocateRegisters();
800  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
801  regs.flags = flags & TLF_DRAWING_FLAGS;
802 
803  if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
804  if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
805  if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
806 
807  if (is_parent) {
808  if (flags & TLF_BB_XY_OFFSET) {
809  regs.delta.parent[0] = buf->ReadByte();
810  regs.delta.parent[1] = buf->ReadByte();
811  }
812  if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
813  } else {
814  if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
815  if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
816  }
817 
818  if (flags & TLF_SPRITE_VAR10) {
819  regs.sprite_var10 = buf->ReadByte();
820  if (regs.sprite_var10 > TLR_MAX_VAR10) {
821  GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.sprite_var10, TLR_MAX_VAR10);
822  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
823  return;
824  }
825  }
826 
827  if (flags & TLF_PALETTE_VAR10) {
828  regs.palette_var10 = buf->ReadByte();
829  if (regs.palette_var10 > TLR_MAX_VAR10) {
830  GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.palette_var10, TLR_MAX_VAR10);
831  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
832  return;
833  }
834  }
835 }
836 
848 static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
849 {
850  bool has_flags = HasBit(num_building_sprites, 6);
851  ClrBit(num_building_sprites, 6);
852  TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
853  if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
854  dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
855 
856  std::vector<uint16_t> max_sprite_offset(num_building_sprites + 1, 0);
857  std::vector<uint16_t> max_palette_offset(num_building_sprites + 1, 0);
858 
859  /* Groundsprite */
860  TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset.data(), max_palette_offset.data());
861  if (_cur.skip_sprites < 0) return true;
862 
863  if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
864  GrfMsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x{:X} for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
865  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
866  return true;
867  }
868 
869  ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
870  if (_cur.skip_sprites < 0) return true;
871 
872  for (uint i = 0; i < num_building_sprites; i++) {
873  DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
874 
875  flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset.data() + i + 1, max_palette_offset.data() + i + 1);
876  if (_cur.skip_sprites < 0) return true;
877 
878  if (flags & ~valid_flags) {
879  GrfMsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x{:X}", flags & ~valid_flags);
880  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
881  return true;
882  }
883 
884  seq->delta_x = buf->ReadByte();
885  seq->delta_y = buf->ReadByte();
886 
887  if (!no_z_position) seq->delta_z = buf->ReadByte();
888 
889  if (seq->IsParentSprite()) {
890  seq->size_x = buf->ReadByte();
891  seq->size_y = buf->ReadByte();
892  seq->size_z = buf->ReadByte();
893  }
894 
895  ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
896  if (_cur.skip_sprites < 0) return true;
897  }
898 
899  /* Check if the number of sprites per spriteset is consistent */
900  bool is_consistent = true;
901  dts->consistent_max_offset = 0;
902  for (uint i = 0; i < num_building_sprites + 1; i++) {
903  if (max_sprite_offset[i] > 0) {
904  if (dts->consistent_max_offset == 0) {
905  dts->consistent_max_offset = max_sprite_offset[i];
906  } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
907  is_consistent = false;
908  break;
909  }
910  }
911  if (max_palette_offset[i] > 0) {
912  if (dts->consistent_max_offset == 0) {
913  dts->consistent_max_offset = max_palette_offset[i];
914  } else if (dts->consistent_max_offset != max_palette_offset[i]) {
915  is_consistent = false;
916  break;
917  }
918  }
919  }
920 
921  /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
922  assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
923 
924  if (!is_consistent || dts->registers != nullptr) {
925  dts->consistent_max_offset = 0;
926  if (dts->registers == nullptr) dts->AllocateRegisters();
927 
928  for (uint i = 0; i < num_building_sprites + 1; i++) {
929  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
930  regs.max_sprite_offset = max_sprite_offset[i];
931  regs.max_palette_offset = max_palette_offset[i];
932  }
933  }
934 
935  return false;
936 }
937 
941 static CargoTypes TranslateRefitMask(uint32_t refit_mask)
942 {
943  CargoTypes result = 0;
944  for (uint8_t bit : SetBitIterator(refit_mask)) {
945  CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
946  if (IsValidCargoID(cargo)) SetBit(result, cargo);
947  }
948  return result;
949 }
950 
958 static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
959 {
960  /* Special value for 'none' */
961  if (base_pointer == 0) {
962  *index = INVALID_PRICE;
963  return;
964  }
965 
966  static const uint32_t start = 0x4B34;
967  static const uint32_t size = 6;
968 
969  if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
970  GrfMsg(1, "{}: Unsupported running cost base 0x{:04X}, ignoring", error_location, base_pointer);
971  return;
972  }
973 
974  *index = (Price)((base_pointer - start) / size);
975 }
976 
984 };
985 
986 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader *buf);
987 
996 {
997  switch (prop) {
998  case 0x00: // Introduction date
1000  break;
1001 
1002  case 0x02: // Decay speed
1003  ei->decay_speed = buf->ReadByte();
1004  break;
1005 
1006  case 0x03: // Vehicle life
1007  ei->lifelength = buf->ReadByte();
1008  break;
1009 
1010  case 0x04: // Model life
1011  ei->base_life = buf->ReadByte();
1012  break;
1013 
1014  case 0x06: // Climates available
1015  ei->climates = buf->ReadByte();
1016  break;
1017 
1018  case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1019  /* Amount of cargo loaded during a vehicle's "loading tick" */
1020  ei->load_amount = buf->ReadByte();
1021  break;
1022 
1023  default:
1024  return CIR_UNKNOWN;
1025  }
1026 
1027  return CIR_SUCCESS;
1028 }
1029 
1038 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1039 {
1041 
1042  for (int i = 0; i < numinfo; i++) {
1043  Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1044  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1045 
1046  EngineInfo *ei = &e->info;
1047  RailVehicleInfo *rvi = &e->u.rail;
1048 
1049  switch (prop) {
1050  case 0x05: { // Track type
1051  uint8_t tracktype = buf->ReadByte();
1052 
1053  if (tracktype < _cur.grffile->railtype_list.size()) {
1054  _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1055  break;
1056  }
1057 
1058  switch (tracktype) {
1059  case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_LABEL_ELECTRIC : RAILTYPE_LABEL_RAIL; break;
1060  case 1: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MONO; break;
1061  case 2: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MAGLEV; break;
1062  default:
1063  GrfMsg(1, "RailVehicleChangeInfo: Invalid track type {} specified, ignoring", tracktype);
1064  break;
1065  }
1066  break;
1067  }
1068 
1069  case 0x08: // AI passenger service
1070  /* Tells the AI that this engine is designed for
1071  * passenger services and shouldn't be used for freight. */
1072  rvi->ai_passenger_only = buf->ReadByte();
1073  break;
1074 
1075  case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1076  uint16_t speed = buf->ReadWord();
1077  if (speed == 0xFFFF) speed = 0;
1078 
1079  rvi->max_speed = speed;
1080  break;
1081  }
1082 
1083  case PROP_TRAIN_POWER: // 0x0B Power
1084  rvi->power = buf->ReadWord();
1085 
1086  /* Set engine / wagon state based on power */
1087  if (rvi->power != 0) {
1088  if (rvi->railveh_type == RAILVEH_WAGON) {
1089  rvi->railveh_type = RAILVEH_SINGLEHEAD;
1090  }
1091  } else {
1092  rvi->railveh_type = RAILVEH_WAGON;
1093  }
1094  break;
1095 
1096  case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1097  rvi->running_cost = buf->ReadByte();
1098  break;
1099 
1100  case 0x0E: // Running cost base
1101  ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1102  break;
1103 
1104  case 0x12: { // Sprite ID
1105  uint8_t spriteid = buf->ReadByte();
1106  uint8_t orig_spriteid = spriteid;
1107 
1108  /* TTD sprite IDs point to a location in a 16bit array, but we use it
1109  * as an array index, so we need it to be half the original value. */
1110  if (spriteid < 0xFD) spriteid >>= 1;
1111 
1112  if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1113  rvi->image_index = spriteid;
1114  } else {
1115  GrfMsg(1, "RailVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1116  rvi->image_index = 0;
1117  }
1118  break;
1119  }
1120 
1121  case 0x13: { // Dual-headed
1122  uint8_t dual = buf->ReadByte();
1123 
1124  if (dual != 0) {
1125  rvi->railveh_type = RAILVEH_MULTIHEAD;
1126  } else {
1127  rvi->railveh_type = rvi->power == 0 ?
1129  }
1130  break;
1131  }
1132 
1133  case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1134  rvi->capacity = buf->ReadByte();
1135  break;
1136 
1137  case 0x15: { // Cargo type
1138  _gted[e->index].defaultcargo_grf = _cur.grffile;
1139  uint8_t ctype = buf->ReadByte();
1140 
1141  if (ctype == 0xFF) {
1142  /* 0xFF is specified as 'use first refittable' */
1143  ei->cargo_type = INVALID_CARGO;
1144  } else if (_cur.grffile->grf_version >= 8) {
1145  /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1146  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1147  } else if (ctype < NUM_CARGO) {
1148  /* Use untranslated cargo. */
1149  ei->cargo_type = ctype;
1150  } else {
1151  ei->cargo_type = INVALID_CARGO;
1152  GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1153  }
1154  ei->cargo_label = CT_INVALID;
1155  break;
1156  }
1157 
1158  case PROP_TRAIN_WEIGHT: // 0x16 Weight
1159  SB(rvi->weight, 0, 8, buf->ReadByte());
1160  break;
1161 
1162  case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1163  rvi->cost_factor = buf->ReadByte();
1164  break;
1165 
1166  case 0x18: // AI rank
1167  GrfMsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1168  buf->ReadByte();
1169  break;
1170 
1171  case 0x19: { // Engine traction type
1172  /* What do the individual numbers mean?
1173  * 0x00 .. 0x07: Steam
1174  * 0x08 .. 0x27: Diesel
1175  * 0x28 .. 0x31: Electric
1176  * 0x32 .. 0x37: Monorail
1177  * 0x38 .. 0x41: Maglev
1178  */
1179  uint8_t traction = buf->ReadByte();
1180  EngineClass engclass;
1181 
1182  if (traction <= 0x07) {
1183  engclass = EC_STEAM;
1184  } else if (traction <= 0x27) {
1185  engclass = EC_DIESEL;
1186  } else if (traction <= 0x31) {
1187  engclass = EC_ELECTRIC;
1188  } else if (traction <= 0x37) {
1189  engclass = EC_MONORAIL;
1190  } else if (traction <= 0x41) {
1191  engclass = EC_MAGLEV;
1192  } else {
1193  break;
1194  }
1195 
1196  if (_cur.grffile->railtype_list.empty()) {
1197  /* Use traction type to select between normal and electrified
1198  * rail only when no translation list is in place. */
1199  if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_RAIL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_ELECTRIC;
1200  if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_ELECTRIC && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_RAIL;
1201  }
1202 
1203  rvi->engclass = engclass;
1204  break;
1205  }
1206 
1207  case 0x1A: // Alter purchase list sort order
1208  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1209  break;
1210 
1211  case 0x1B: // Powered wagons power bonus
1212  rvi->pow_wag_power = buf->ReadWord();
1213  break;
1214 
1215  case 0x1C: // Refit cost
1216  ei->refit_cost = buf->ReadByte();
1217  break;
1218 
1219  case 0x1D: { // Refit cargo
1220  uint32_t mask = buf->ReadDWord();
1221  _gted[e->index].UpdateRefittability(mask != 0);
1222  ei->refit_mask = TranslateRefitMask(mask);
1223  _gted[e->index].defaultcargo_grf = _cur.grffile;
1224  break;
1225  }
1226 
1227  case 0x1E: // Callback
1228  SB(ei->callback_mask, 0, 8, buf->ReadByte());
1229  break;
1230 
1231  case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1232  rvi->tractive_effort = buf->ReadByte();
1233  break;
1234 
1235  case 0x20: // Air drag
1236  rvi->air_drag = buf->ReadByte();
1237  break;
1238 
1239  case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1240  rvi->shorten_factor = buf->ReadByte();
1241  break;
1242 
1243  case 0x22: // Visual effect
1244  rvi->visual_effect = buf->ReadByte();
1245  /* Avoid accidentally setting visual_effect to the default value
1246  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1247  if (rvi->visual_effect == VE_DEFAULT) {
1248  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1250  }
1251  break;
1252 
1253  case 0x23: // Powered wagons weight bonus
1254  rvi->pow_wag_weight = buf->ReadByte();
1255  break;
1256 
1257  case 0x24: { // High byte of vehicle weight
1258  byte weight = buf->ReadByte();
1259 
1260  if (weight > 4) {
1261  GrfMsg(2, "RailVehicleChangeInfo: Nonsensical weight of {} tons, ignoring", weight << 8);
1262  } else {
1263  SB(rvi->weight, 8, 8, weight);
1264  }
1265  break;
1266  }
1267 
1268  case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1269  rvi->user_def_data = buf->ReadByte();
1270  break;
1271 
1272  case 0x26: // Retire vehicle early
1273  ei->retire_early = buf->ReadByte();
1274  break;
1275 
1276  case 0x27: // Miscellaneous flags
1277  ei->misc_flags = buf->ReadByte();
1279  break;
1280 
1281  case 0x28: // Cargo classes allowed
1282  _gted[e->index].cargo_allowed = buf->ReadWord();
1283  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1284  _gted[e->index].defaultcargo_grf = _cur.grffile;
1285  break;
1286 
1287  case 0x29: // Cargo classes disallowed
1288  _gted[e->index].cargo_disallowed = buf->ReadWord();
1289  _gted[e->index].UpdateRefittability(false);
1290  break;
1291 
1292  case 0x2A: // Long format introduction date (days since year 0)
1293  ei->base_intro = buf->ReadDWord();
1294  break;
1295 
1296  case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1297  ei->cargo_age_period = buf->ReadWord();
1298  break;
1299 
1300  case 0x2C: // CTT refit include list
1301  case 0x2D: { // CTT refit exclude list
1302  uint8_t count = buf->ReadByte();
1303  _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1304  if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1305  CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1306  ctt = 0;
1307  while (count--) {
1308  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1309  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1310  }
1311  break;
1312  }
1313 
1314  case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1315  rvi->curve_speed_mod = buf->ReadWord();
1316  break;
1317 
1318  case 0x2F: // Engine variant
1319  ei->variant_id = buf->ReadWord();
1320  break;
1321 
1322  case 0x30: // Extra miscellaneous flags
1323  ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1324  break;
1325 
1326  case 0x31: // Callback additional mask
1327  SB(ei->callback_mask, 8, 8, buf->ReadByte());
1328  break;
1329 
1330  default:
1331  ret = CommonVehicleChangeInfo(ei, prop, buf);
1332  break;
1333  }
1334  }
1335 
1336  return ret;
1337 }
1338 
1347 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1348 {
1350 
1351  for (int i = 0; i < numinfo; i++) {
1352  Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1353  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1354 
1355  EngineInfo *ei = &e->info;
1356  RoadVehicleInfo *rvi = &e->u.road;
1357 
1358  switch (prop) {
1359  case 0x05: // Road/tram type
1360  /* RoadTypeLabel is looked up later after the engine's road/tram
1361  * flag is set, however 0 means the value has not been set. */
1362  _gted[e->index].roadtramtype = buf->ReadByte() + 1;
1363  break;
1364 
1365  case 0x08: // Speed (1 unit is 0.5 kmh)
1366  rvi->max_speed = buf->ReadByte();
1367  break;
1368 
1369  case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1370  rvi->running_cost = buf->ReadByte();
1371  break;
1372 
1373  case 0x0A: // Running cost base
1374  ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1375  break;
1376 
1377  case 0x0E: { // Sprite ID
1378  uint8_t spriteid = buf->ReadByte();
1379  uint8_t orig_spriteid = spriteid;
1380 
1381  /* cars have different custom id in the GRF file */
1382  if (spriteid == 0xFF) spriteid = 0xFD;
1383 
1384  if (spriteid < 0xFD) spriteid >>= 1;
1385 
1386  if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1387  rvi->image_index = spriteid;
1388  } else {
1389  GrfMsg(1, "RoadVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1390  rvi->image_index = 0;
1391  }
1392  break;
1393  }
1394 
1395  case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1396  rvi->capacity = buf->ReadByte();
1397  break;
1398 
1399  case 0x10: { // Cargo type
1400  _gted[e->index].defaultcargo_grf = _cur.grffile;
1401  uint8_t ctype = buf->ReadByte();
1402 
1403  if (ctype == 0xFF) {
1404  /* 0xFF is specified as 'use first refittable' */
1405  ei->cargo_type = INVALID_CARGO;
1406  } else if (_cur.grffile->grf_version >= 8) {
1407  /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1408  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1409  } else if (ctype < NUM_CARGO) {
1410  /* Use untranslated cargo. */
1411  ei->cargo_type = ctype;
1412  } else {
1413  ei->cargo_type = INVALID_CARGO;
1414  GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1415  }
1416  ei->cargo_label = CT_INVALID;
1417  break;
1418  }
1419 
1420  case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1421  rvi->cost_factor = buf->ReadByte();
1422  break;
1423 
1424  case 0x12: // SFX
1425  rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1426  break;
1427 
1428  case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1429  rvi->power = buf->ReadByte();
1430  break;
1431 
1432  case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1433  rvi->weight = buf->ReadByte();
1434  break;
1435 
1436  case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1437  _gted[e->index].rv_max_speed = buf->ReadByte();
1438  break;
1439 
1440  case 0x16: { // Cargoes available for refitting
1441  uint32_t mask = buf->ReadDWord();
1442  _gted[e->index].UpdateRefittability(mask != 0);
1443  ei->refit_mask = TranslateRefitMask(mask);
1444  _gted[e->index].defaultcargo_grf = _cur.grffile;
1445  break;
1446  }
1447 
1448  case 0x17: // Callback mask
1449  SB(ei->callback_mask, 0, 8, buf->ReadByte());
1450  break;
1451 
1452  case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1453  rvi->tractive_effort = buf->ReadByte();
1454  break;
1455 
1456  case 0x19: // Air drag
1457  rvi->air_drag = buf->ReadByte();
1458  break;
1459 
1460  case 0x1A: // Refit cost
1461  ei->refit_cost = buf->ReadByte();
1462  break;
1463 
1464  case 0x1B: // Retire vehicle early
1465  ei->retire_early = buf->ReadByte();
1466  break;
1467 
1468  case 0x1C: // Miscellaneous flags
1469  ei->misc_flags = buf->ReadByte();
1471  break;
1472 
1473  case 0x1D: // Cargo classes allowed
1474  _gted[e->index].cargo_allowed = buf->ReadWord();
1475  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1476  _gted[e->index].defaultcargo_grf = _cur.grffile;
1477  break;
1478 
1479  case 0x1E: // Cargo classes disallowed
1480  _gted[e->index].cargo_disallowed = buf->ReadWord();
1481  _gted[e->index].UpdateRefittability(false);
1482  break;
1483 
1484  case 0x1F: // Long format introduction date (days since year 0)
1485  ei->base_intro = buf->ReadDWord();
1486  break;
1487 
1488  case 0x20: // Alter purchase list sort order
1489  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1490  break;
1491 
1492  case 0x21: // Visual effect
1493  rvi->visual_effect = buf->ReadByte();
1494  /* Avoid accidentally setting visual_effect to the default value
1495  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1496  if (rvi->visual_effect == VE_DEFAULT) {
1497  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1499  }
1500  break;
1501 
1502  case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1503  ei->cargo_age_period = buf->ReadWord();
1504  break;
1505 
1506  case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1507  rvi->shorten_factor = buf->ReadByte();
1508  break;
1509 
1510  case 0x24: // CTT refit include list
1511  case 0x25: { // CTT refit exclude list
1512  uint8_t count = buf->ReadByte();
1513  _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1514  if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1515  CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1516  ctt = 0;
1517  while (count--) {
1518  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1519  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1520  }
1521  break;
1522  }
1523 
1524  case 0x26: // Engine variant
1525  ei->variant_id = buf->ReadWord();
1526  break;
1527 
1528  case 0x27: // Extra miscellaneous flags
1529  ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1530  break;
1531 
1532  case 0x28: // Callback additional mask
1533  SB(ei->callback_mask, 8, 8, buf->ReadByte());
1534  break;
1535 
1536  default:
1537  ret = CommonVehicleChangeInfo(ei, prop, buf);
1538  break;
1539  }
1540  }
1541 
1542  return ret;
1543 }
1544 
1553 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1554 {
1556 
1557  for (int i = 0; i < numinfo; i++) {
1558  Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1559  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1560 
1561  EngineInfo *ei = &e->info;
1562  ShipVehicleInfo *svi = &e->u.ship;
1563 
1564  switch (prop) {
1565  case 0x08: { // Sprite ID
1566  uint8_t spriteid = buf->ReadByte();
1567  uint8_t orig_spriteid = spriteid;
1568 
1569  /* ships have different custom id in the GRF file */
1570  if (spriteid == 0xFF) spriteid = 0xFD;
1571 
1572  if (spriteid < 0xFD) spriteid >>= 1;
1573 
1574  if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1575  svi->image_index = spriteid;
1576  } else {
1577  GrfMsg(1, "ShipVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1578  svi->image_index = 0;
1579  }
1580  break;
1581  }
1582 
1583  case 0x09: // Refittable
1584  svi->old_refittable = (buf->ReadByte() != 0);
1585  break;
1586 
1587  case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1588  svi->cost_factor = buf->ReadByte();
1589  break;
1590 
1591  case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h). Use 0x23 to achieve higher speeds.
1592  svi->max_speed = buf->ReadByte();
1593  break;
1594 
1595  case 0x0C: { // Cargo type
1596  _gted[e->index].defaultcargo_grf = _cur.grffile;
1597  uint8_t ctype = buf->ReadByte();
1598 
1599  if (ctype == 0xFF) {
1600  /* 0xFF is specified as 'use first refittable' */
1601  ei->cargo_type = INVALID_CARGO;
1602  } else if (_cur.grffile->grf_version >= 8) {
1603  /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1604  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1605  } else if (ctype < NUM_CARGO) {
1606  /* Use untranslated cargo. */
1607  ei->cargo_type = ctype;
1608  } else {
1609  ei->cargo_type = INVALID_CARGO;
1610  GrfMsg(2, "ShipVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1611  }
1612  ei->cargo_label = CT_INVALID;
1613  break;
1614  }
1615 
1616  case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1617  svi->capacity = buf->ReadWord();
1618  break;
1619 
1620  case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1621  svi->running_cost = buf->ReadByte();
1622  break;
1623 
1624  case 0x10: // SFX
1625  svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1626  break;
1627 
1628  case 0x11: { // Cargoes available for refitting
1629  uint32_t mask = buf->ReadDWord();
1630  _gted[e->index].UpdateRefittability(mask != 0);
1631  ei->refit_mask = TranslateRefitMask(mask);
1632  _gted[e->index].defaultcargo_grf = _cur.grffile;
1633  break;
1634  }
1635 
1636  case 0x12: // Callback mask
1637  SB(ei->callback_mask, 0, 8, buf->ReadByte());
1638  break;
1639 
1640  case 0x13: // Refit cost
1641  ei->refit_cost = buf->ReadByte();
1642  break;
1643 
1644  case 0x14: // Ocean speed fraction
1645  svi->ocean_speed_frac = buf->ReadByte();
1646  break;
1647 
1648  case 0x15: // Canal speed fraction
1649  svi->canal_speed_frac = buf->ReadByte();
1650  break;
1651 
1652  case 0x16: // Retire vehicle early
1653  ei->retire_early = buf->ReadByte();
1654  break;
1655 
1656  case 0x17: // Miscellaneous flags
1657  ei->misc_flags = buf->ReadByte();
1659  break;
1660 
1661  case 0x18: // Cargo classes allowed
1662  _gted[e->index].cargo_allowed = buf->ReadWord();
1663  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1664  _gted[e->index].defaultcargo_grf = _cur.grffile;
1665  break;
1666 
1667  case 0x19: // Cargo classes disallowed
1668  _gted[e->index].cargo_disallowed = buf->ReadWord();
1669  _gted[e->index].UpdateRefittability(false);
1670  break;
1671 
1672  case 0x1A: // Long format introduction date (days since year 0)
1673  ei->base_intro = buf->ReadDWord();
1674  break;
1675 
1676  case 0x1B: // Alter purchase list sort order
1677  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1678  break;
1679 
1680  case 0x1C: // Visual effect
1681  svi->visual_effect = buf->ReadByte();
1682  /* Avoid accidentally setting visual_effect to the default value
1683  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1684  if (svi->visual_effect == VE_DEFAULT) {
1685  assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1687  }
1688  break;
1689 
1690  case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1691  ei->cargo_age_period = buf->ReadWord();
1692  break;
1693 
1694  case 0x1E: // CTT refit include list
1695  case 0x1F: { // CTT refit exclude list
1696  uint8_t count = buf->ReadByte();
1697  _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1698  if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1699  CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1700  ctt = 0;
1701  while (count--) {
1702  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1703  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1704  }
1705  break;
1706  }
1707 
1708  case 0x20: // Engine variant
1709  ei->variant_id = buf->ReadWord();
1710  break;
1711 
1712  case 0x21: // Extra miscellaneous flags
1713  ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1714  break;
1715 
1716  case 0x22: // Callback additional mask
1717  SB(ei->callback_mask, 8, 8, buf->ReadByte());
1718  break;
1719 
1720  case 0x23: // Speed (1 unit is 0.5 km-ish/h)
1721  svi->max_speed = buf->ReadWord();
1722  break;
1723 
1724  case 0x24: // Acceleration (1 unit is 0.5 km-ish/h per tick)
1725  svi->acceleration = std::max<uint8_t>(1, buf->ReadByte());
1726  break;
1727 
1728  default:
1729  ret = CommonVehicleChangeInfo(ei, prop, buf);
1730  break;
1731  }
1732  }
1733 
1734  return ret;
1735 }
1736 
1745 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1746 {
1748 
1749  for (int i = 0; i < numinfo; i++) {
1750  Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1751  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1752 
1753  EngineInfo *ei = &e->info;
1754  AircraftVehicleInfo *avi = &e->u.air;
1755 
1756  switch (prop) {
1757  case 0x08: { // Sprite ID
1758  uint8_t spriteid = buf->ReadByte();
1759  uint8_t orig_spriteid = spriteid;
1760 
1761  /* aircraft have different custom id in the GRF file */
1762  if (spriteid == 0xFF) spriteid = 0xFD;
1763 
1764  if (spriteid < 0xFD) spriteid >>= 1;
1765 
1766  if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1767  avi->image_index = spriteid;
1768  } else {
1769  GrfMsg(1, "AircraftVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1770  avi->image_index = 0;
1771  }
1772  break;
1773  }
1774 
1775  case 0x09: // Helicopter
1776  if (buf->ReadByte() == 0) {
1777  avi->subtype = AIR_HELI;
1778  } else {
1779  SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1780  }
1781  break;
1782 
1783  case 0x0A: // Large
1784  SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1785  break;
1786 
1787  case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1788  avi->cost_factor = buf->ReadByte();
1789  break;
1790 
1791  case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1792  avi->max_speed = (buf->ReadByte() * 128) / 10;
1793  break;
1794 
1795  case 0x0D: // Acceleration
1796  avi->acceleration = buf->ReadByte();
1797  break;
1798 
1799  case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1800  avi->running_cost = buf->ReadByte();
1801  break;
1802 
1803  case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1804  avi->passenger_capacity = buf->ReadWord();
1805  break;
1806 
1807  case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1808  avi->mail_capacity = buf->ReadByte();
1809  break;
1810 
1811  case 0x12: // SFX
1812  avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1813  break;
1814 
1815  case 0x13: { // Cargoes available for refitting
1816  uint32_t mask = buf->ReadDWord();
1817  _gted[e->index].UpdateRefittability(mask != 0);
1818  ei->refit_mask = TranslateRefitMask(mask);
1819  _gted[e->index].defaultcargo_grf = _cur.grffile;
1820  break;
1821  }
1822 
1823  case 0x14: // Callback mask
1824  SB(ei->callback_mask, 0, 8, buf->ReadByte());
1825  break;
1826 
1827  case 0x15: // Refit cost
1828  ei->refit_cost = buf->ReadByte();
1829  break;
1830 
1831  case 0x16: // Retire vehicle early
1832  ei->retire_early = buf->ReadByte();
1833  break;
1834 
1835  case 0x17: // Miscellaneous flags
1836  ei->misc_flags = buf->ReadByte();
1838  break;
1839 
1840  case 0x18: // Cargo classes allowed
1841  _gted[e->index].cargo_allowed = buf->ReadWord();
1842  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1843  _gted[e->index].defaultcargo_grf = _cur.grffile;
1844  break;
1845 
1846  case 0x19: // Cargo classes disallowed
1847  _gted[e->index].cargo_disallowed = buf->ReadWord();
1848  _gted[e->index].UpdateRefittability(false);
1849  break;
1850 
1851  case 0x1A: // Long format introduction date (days since year 0)
1852  ei->base_intro = buf->ReadDWord();
1853  break;
1854 
1855  case 0x1B: // Alter purchase list sort order
1856  AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1857  break;
1858 
1859  case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1860  ei->cargo_age_period = buf->ReadWord();
1861  break;
1862 
1863  case 0x1D: // CTT refit include list
1864  case 0x1E: { // CTT refit exclude list
1865  uint8_t count = buf->ReadByte();
1866  _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1867  if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1868  CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1869  ctt = 0;
1870  while (count--) {
1871  CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1872  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1873  }
1874  break;
1875  }
1876 
1877  case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1878  avi->max_range = buf->ReadWord();
1879  break;
1880 
1881  case 0x20: // Engine variant
1882  ei->variant_id = buf->ReadWord();
1883  break;
1884 
1885  case 0x21: // Extra miscellaneous flags
1886  ei->extra_flags = static_cast<ExtraEngineFlags>(buf->ReadDWord());
1887  break;
1888 
1889  case 0x22: // Callback additional mask
1890  SB(ei->callback_mask, 8, 8, buf->ReadByte());
1891  break;
1892 
1893  default:
1894  ret = CommonVehicleChangeInfo(ei, prop, buf);
1895  break;
1896  }
1897  }
1898 
1899  return ret;
1900 }
1901 
1910 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
1911 {
1913 
1914  if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1915  GrfMsg(1, "StationChangeInfo: Station {} is invalid, max {}, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1916  return CIR_INVALID_ID;
1917  }
1918 
1919  /* Allocate station specs if necessary */
1920  if (_cur.grffile->stations.size() < stid + numinfo) _cur.grffile->stations.resize(stid + numinfo);
1921 
1922  for (int i = 0; i < numinfo; i++) {
1923  StationSpec *statspec = _cur.grffile->stations[stid + i].get();
1924 
1925  /* Check that the station we are modifying is defined. */
1926  if (statspec == nullptr && prop != 0x08) {
1927  GrfMsg(2, "StationChangeInfo: Attempt to modify undefined station {}, ignoring", stid + i);
1928  return CIR_INVALID_ID;
1929  }
1930 
1931  switch (prop) {
1932  case 0x08: { // Class ID
1933  /* Property 0x08 is special; it is where the station is allocated */
1934  if (statspec == nullptr) {
1935  _cur.grffile->stations[stid + i] = std::make_unique<StationSpec>();
1936  statspec = _cur.grffile->stations[stid + i].get();
1937  }
1938 
1939  /* Swap classid because we read it in BE meaning WAYP or DFLT */
1940  uint32_t classid = buf->ReadDWord();
1941  statspec->cls_id = StationClass::Allocate(BSWAP32(classid));
1942  break;
1943  }
1944 
1945  case 0x09: { // Define sprite layout
1946  uint16_t tiles = buf->ReadExtendedByte();
1947  statspec->renderdata.clear(); // delete earlier loaded stuff
1948  statspec->renderdata.reserve(tiles);
1949 
1950  for (uint t = 0; t < tiles; t++) {
1951  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1952  dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1953 
1954  if (buf->HasData(4) && *(uint32_t*)buf->Data() == 0) {
1955  buf->Skip(4);
1956  extern const DrawTileSprites _station_display_datas_rail[8];
1957  dts->Clone(&_station_display_datas_rail[t % 8]);
1958  continue;
1959  }
1960 
1961  ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1962  /* On error, bail out immediately. Temporary GRF data was already freed */
1963  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1964 
1965  static std::vector<DrawTileSeqStruct> tmp_layout;
1966  tmp_layout.clear();
1967  for (;;) {
1968  /* no relative bounding box support */
1969  DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1970  MemSetT(&dtss, 0);
1971 
1972  dtss.delta_x = buf->ReadByte();
1973  if (dtss.IsTerminator()) break;
1974  dtss.delta_y = buf->ReadByte();
1975  dtss.delta_z = buf->ReadByte();
1976  dtss.size_x = buf->ReadByte();
1977  dtss.size_y = buf->ReadByte();
1978  dtss.size_z = buf->ReadByte();
1979 
1980  ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1981  /* On error, bail out immediately. Temporary GRF data was already freed */
1982  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1983  }
1984  dts->Clone(tmp_layout.data());
1985  }
1986 
1987  /* Number of layouts must be even, alternating X and Y */
1988  if (statspec->renderdata.size() & 1) {
1989  GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
1990  statspec->renderdata.pop_back();
1991  }
1992  break;
1993  }
1994 
1995  case 0x0A: { // Copy sprite layout
1996  uint16_t srcid = buf->ReadExtendedByte();
1997  const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
1998 
1999  if (srcstatspec == nullptr) {
2000  GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy sprite layout to {}.", srcid, stid + i);
2001  continue;
2002  }
2003 
2004  statspec->renderdata.clear(); // delete earlier loaded stuff
2005  statspec->renderdata.reserve(srcstatspec->renderdata.size());
2006 
2007  for (const auto &it : srcstatspec->renderdata) {
2008  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2009  dts->Clone(&it);
2010  }
2011  break;
2012  }
2013 
2014  case 0x0B: // Callback mask
2015  statspec->callback_mask = buf->ReadByte();
2016  break;
2017 
2018  case 0x0C: // Disallowed number of platforms
2019  statspec->disallowed_platforms = buf->ReadByte();
2020  break;
2021 
2022  case 0x0D: // Disallowed platform lengths
2023  statspec->disallowed_lengths = buf->ReadByte();
2024  break;
2025 
2026  case 0x0E: // Define custom layout
2027  while (buf->HasData()) {
2028  byte length = buf->ReadByte();
2029  byte number = buf->ReadByte();
2030 
2031  if (length == 0 || number == 0) break;
2032 
2033  if (statspec->layouts.size() < length) statspec->layouts.resize(length);
2034  if (statspec->layouts[length - 1].size() < number) statspec->layouts[length - 1].resize(number);
2035 
2036  const byte *layout = buf->ReadBytes(length * number);
2037  statspec->layouts[length - 1][number - 1].assign(layout, layout + length * number);
2038 
2039  /* Validate tile values are only the permitted 00, 02, 04 and 06. */
2040  for (auto &tile : statspec->layouts[length - 1][number - 1]) {
2041  if ((tile & 6) != tile) {
2042  GrfMsg(1, "StationChangeInfo: Invalid tile {} in layout {}x{}", tile, length, number);
2043  tile &= 6;
2044  }
2045  }
2046  }
2047  break;
2048 
2049  case 0x0F: { // Copy custom layout
2050  uint16_t srcid = buf->ReadExtendedByte();
2051  const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
2052 
2053  if (srcstatspec == nullptr) {
2054  GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy tile layout to {}.", srcid, stid + i);
2055  continue;
2056  }
2057 
2058  statspec->layouts = srcstatspec->layouts;
2059  break;
2060  }
2061 
2062  case 0x10: // Little/lots cargo threshold
2063  statspec->cargo_threshold = buf->ReadWord();
2064  break;
2065 
2066  case 0x11: // Pylon placement
2067  statspec->pylons = buf->ReadByte();
2068  break;
2069 
2070  case 0x12: // Cargo types for random triggers
2071  if (_cur.grffile->grf_version >= 7) {
2072  statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
2073  } else {
2074  statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
2075  }
2076  break;
2077 
2078  case 0x13: // General flags
2079  statspec->flags = buf->ReadByte();
2080  break;
2081 
2082  case 0x14: // Overhead wire placement
2083  statspec->wires = buf->ReadByte();
2084  break;
2085 
2086  case 0x15: // Blocked tiles
2087  statspec->blocked = buf->ReadByte();
2088  break;
2089 
2090  case 0x16: // Animation info
2091  statspec->animation.frames = buf->ReadByte();
2092  statspec->animation.status = buf->ReadByte();
2093  break;
2094 
2095  case 0x17: // Animation speed
2096  statspec->animation.speed = buf->ReadByte();
2097  break;
2098 
2099  case 0x18: // Animation triggers
2100  statspec->animation.triggers = buf->ReadWord();
2101  break;
2102 
2103  /* 0x19 road routing (not implemented) */
2104 
2105  case 0x1A: { // Advanced sprite layout
2106  uint16_t tiles = buf->ReadExtendedByte();
2107  statspec->renderdata.clear(); // delete earlier loaded stuff
2108  statspec->renderdata.reserve(tiles);
2109 
2110  for (uint t = 0; t < tiles; t++) {
2111  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2112  uint num_building_sprites = buf->ReadByte();
2113  /* On error, bail out immediately. Temporary GRF data was already freed */
2114  if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2115  }
2116 
2117  /* Number of layouts must be even, alternating X and Y */
2118  if (statspec->renderdata.size() & 1) {
2119  GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
2120  statspec->renderdata.pop_back();
2121  }
2122  break;
2123  }
2124 
2125  case 0x1B: // Minimum bridge height (not implemented)
2126  buf->ReadWord();
2127  buf->ReadWord();
2128  buf->ReadWord();
2129  buf->ReadWord();
2130  break;
2131 
2132  case 0x1C: // Station Name
2133  AddStringForMapping(buf->ReadWord(), &statspec->name);
2134  break;
2135 
2136  case 0x1D: // Station Class name
2137  AddStringForMapping(buf->ReadWord(), &StationClass::Get(statspec->cls_id)->name);
2138  break;
2139 
2140  default:
2141  ret = CIR_UNKNOWN;
2142  break;
2143  }
2144  }
2145 
2146  return ret;
2147 }
2148 
2157 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
2158 {
2160 
2161  if (id + numinfo > CF_END) {
2162  GrfMsg(1, "CanalChangeInfo: Canal feature 0x{:02X} is invalid, max {}, ignoring", id + numinfo, CF_END);
2163  return CIR_INVALID_ID;
2164  }
2165 
2166  for (int i = 0; i < numinfo; i++) {
2167  CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2168 
2169  switch (prop) {
2170  case 0x08:
2171  cp->callback_mask = buf->ReadByte();
2172  break;
2173 
2174  case 0x09:
2175  cp->flags = buf->ReadByte();
2176  break;
2177 
2178  default:
2179  ret = CIR_UNKNOWN;
2180  break;
2181  }
2182  }
2183 
2184  return ret;
2185 }
2186 
2195 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
2196 {
2198 
2199  if (brid + numinfo > MAX_BRIDGES) {
2200  GrfMsg(1, "BridgeChangeInfo: Bridge {} is invalid, max {}, ignoring", brid + numinfo, MAX_BRIDGES);
2201  return CIR_INVALID_ID;
2202  }
2203 
2204  for (int i = 0; i < numinfo; i++) {
2205  BridgeSpec *bridge = &_bridge[brid + i];
2206 
2207  switch (prop) {
2208  case 0x08: { // Year of availability
2209  /* We treat '0' as always available */
2210  byte year = buf->ReadByte();
2211  bridge->avail_year = (year > 0 ? CalendarTime::ORIGINAL_BASE_YEAR + year : 0);
2212  break;
2213  }
2214 
2215  case 0x09: // Minimum length
2216  bridge->min_length = buf->ReadByte();
2217  break;
2218 
2219  case 0x0A: // Maximum length
2220  bridge->max_length = buf->ReadByte();
2221  if (bridge->max_length > 16) bridge->max_length = UINT16_MAX;
2222  break;
2223 
2224  case 0x0B: // Cost factor
2225  bridge->price = buf->ReadByte();
2226  break;
2227 
2228  case 0x0C: // Maximum speed
2229  bridge->speed = buf->ReadWord();
2230  if (bridge->speed == 0) bridge->speed = UINT16_MAX;
2231  break;
2232 
2233  case 0x0D: { // Bridge sprite tables
2234  byte tableid = buf->ReadByte();
2235  byte numtables = buf->ReadByte();
2236 
2237  if (bridge->sprite_table == nullptr) {
2238  /* Allocate memory for sprite table pointers and zero out */
2239  bridge->sprite_table = CallocT<PalSpriteID*>(7);
2240  }
2241 
2242  for (; numtables-- != 0; tableid++) {
2243  if (tableid >= 7) { // skip invalid data
2244  GrfMsg(1, "BridgeChangeInfo: Table {} >= 7, skipping", tableid);
2245  for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
2246  continue;
2247  }
2248 
2249  if (bridge->sprite_table[tableid] == nullptr) {
2250  bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2251  }
2252 
2253  for (byte sprite = 0; sprite < 32; sprite++) {
2254  SpriteID image = buf->ReadWord();
2255  PaletteID pal = buf->ReadWord();
2256 
2257  bridge->sprite_table[tableid][sprite].sprite = image;
2258  bridge->sprite_table[tableid][sprite].pal = pal;
2259 
2260  MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2261  }
2262  }
2263  break;
2264  }
2265 
2266  case 0x0E: // Flags; bit 0 - disable far pillars
2267  bridge->flags = buf->ReadByte();
2268  break;
2269 
2270  case 0x0F: // Long format year of availability (year since year 0)
2272  break;
2273 
2274  case 0x10: { // purchase string
2275  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2276  if (newone != STR_UNDEFINED) bridge->material = newone;
2277  break;
2278  }
2279 
2280  case 0x11: // description of bridge with rails or roads
2281  case 0x12: {
2282  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2283  if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2284  break;
2285  }
2286 
2287  case 0x13: // 16 bits cost multiplier
2288  bridge->price = buf->ReadWord();
2289  break;
2290 
2291  default:
2292  ret = CIR_UNKNOWN;
2293  break;
2294  }
2295  }
2296 
2297  return ret;
2298 }
2299 
2307 {
2309 
2310  switch (prop) {
2311  case 0x09:
2312  case 0x0B:
2313  case 0x0C:
2314  case 0x0D:
2315  case 0x0E:
2316  case 0x0F:
2317  case 0x11:
2318  case 0x14:
2319  case 0x15:
2320  case 0x16:
2321  case 0x18:
2322  case 0x19:
2323  case 0x1A:
2324  case 0x1B:
2325  case 0x1C:
2326  case 0x1D:
2327  case 0x1F:
2328  buf->ReadByte();
2329  break;
2330 
2331  case 0x0A:
2332  case 0x10:
2333  case 0x12:
2334  case 0x13:
2335  case 0x21:
2336  case 0x22:
2337  buf->ReadWord();
2338  break;
2339 
2340  case 0x1E:
2341  buf->ReadDWord();
2342  break;
2343 
2344  case 0x17:
2345  for (uint j = 0; j < 4; j++) buf->ReadByte();
2346  break;
2347 
2348  case 0x20: {
2349  byte count = buf->ReadByte();
2350  for (byte j = 0; j < count; j++) buf->ReadByte();
2351  break;
2352  }
2353 
2354  case 0x23:
2355  buf->Skip(buf->ReadByte() * 2);
2356  break;
2357 
2358  default:
2359  ret = CIR_UNKNOWN;
2360  break;
2361  }
2362  return ret;
2363 }
2364 
2373 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
2374 {
2376 
2377  if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2378  GrfMsg(1, "TownHouseChangeInfo: Too many houses loaded ({}), max ({}). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2379  return CIR_INVALID_ID;
2380  }
2381 
2382  /* Allocate house specs if they haven't been allocated already. */
2383  if (_cur.grffile->housespec.size() < hid + numinfo) _cur.grffile->housespec.resize(hid + numinfo);
2384 
2385  for (int i = 0; i < numinfo; i++) {
2386  HouseSpec *housespec = _cur.grffile->housespec[hid + i].get();
2387 
2388  if (prop != 0x08 && housespec == nullptr) {
2389  /* If the house property 08 is not yet set, ignore this property */
2390  ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2391  if (cir > ret) ret = cir;
2392  continue;
2393  }
2394 
2395  switch (prop) {
2396  case 0x08: { // Substitute building type, and definition of a new house
2397  byte subs_id = buf->ReadByte();
2398  if (subs_id == 0xFF) {
2399  /* Instead of defining a new house, a substitute house id
2400  * of 0xFF disables the old house with the current id. */
2401  if (hid + i < NEW_HOUSE_OFFSET) HouseSpec::Get(hid + i)->enabled = false;
2402  continue;
2403  } else if (subs_id >= NEW_HOUSE_OFFSET) {
2404  /* The substitute id must be one of the original houses. */
2405  GrfMsg(2, "TownHouseChangeInfo: Attempt to use new house {} as substitute house for {}. Ignoring.", subs_id, hid + i);
2406  continue;
2407  }
2408 
2409  /* Allocate space for this house. */
2410  if (housespec == nullptr) {
2411  /* Only the first property 08 setting copies properties; if you later change it, properties will stay. */
2412  _cur.grffile->housespec[hid + i] = std::make_unique<HouseSpec>(*HouseSpec::Get(subs_id));
2413  housespec = _cur.grffile->housespec[hid + i].get();
2414 
2415  housespec->enabled = true;
2416  housespec->grf_prop.local_id = hid + i;
2417  housespec->grf_prop.subst_id = subs_id;
2418  housespec->grf_prop.grffile = _cur.grffile;
2419  /* Set default colours for randomization, used if not overridden. */
2420  housespec->random_colour[0] = COLOUR_RED;
2421  housespec->random_colour[1] = COLOUR_BLUE;
2422  housespec->random_colour[2] = COLOUR_ORANGE;
2423  housespec->random_colour[3] = COLOUR_GREEN;
2424 
2425  /* House flags 40 and 80 are exceptions; these flags are never set automatically. */
2426  housespec->building_flags &= ~(BUILDING_IS_CHURCH | BUILDING_IS_STADIUM);
2427 
2428  /* Make sure that the third cargo type is valid in this
2429  * climate. This can cause problems when copying the properties
2430  * of a house that accepts food, where the new house is valid
2431  * in the temperate climate. */
2432  CargoID cid = housespec->accepts_cargo[2];
2433  if (!IsValidCargoID(cid)) cid = GetCargoIDByLabel(housespec->accepts_cargo_label[2]);
2434  if (!IsValidCargoID(cid)) {
2435  housespec->cargo_acceptance[2] = 0;
2436  }
2437  }
2438  break;
2439  }
2440 
2441  case 0x09: // Building flags
2442  housespec->building_flags = (BuildingFlags)buf->ReadByte();
2443  break;
2444 
2445  case 0x0A: { // Availability years
2446  uint16_t years = buf->ReadWord();
2447  housespec->min_year = GB(years, 0, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2448  housespec->max_year = GB(years, 8, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2449  break;
2450  }
2451 
2452  case 0x0B: // Population
2453  housespec->population = buf->ReadByte();
2454  break;
2455 
2456  case 0x0C: // Mail generation multiplier
2457  housespec->mail_generation = buf->ReadByte();
2458  break;
2459 
2460  case 0x0D: // Passenger acceptance
2461  case 0x0E: // Mail acceptance
2462  housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
2463  break;
2464 
2465  case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2466  int8_t goods = buf->ReadByte();
2467 
2468  /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2469  * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2470  CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_CANDY) : GetCargoIDByLabel(CT_GOODS)) :
2471  ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_FIZZY_DRINKS) : GetCargoIDByLabel(CT_FOOD));
2472 
2473  /* Make sure the cargo type is valid in this climate. */
2474  if (!IsValidCargoID(cid)) goods = 0;
2475 
2476  housespec->accepts_cargo[2] = cid;
2477  housespec->accepts_cargo_label[2] = CT_INVALID;
2478  housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2479  break;
2480  }
2481 
2482  case 0x10: // Local authority rating decrease on removal
2483  housespec->remove_rating_decrease = buf->ReadWord();
2484  break;
2485 
2486  case 0x11: // Removal cost multiplier
2487  housespec->removal_cost = buf->ReadByte();
2488  break;
2489 
2490  case 0x12: // Building name ID
2491  AddStringForMapping(buf->ReadWord(), &housespec->building_name);
2492  break;
2493 
2494  case 0x13: // Building availability mask
2495  housespec->building_availability = (HouseZones)buf->ReadWord();
2496  break;
2497 
2498  case 0x14: // House callback mask
2499  housespec->callback_mask |= buf->ReadByte();
2500  break;
2501 
2502  case 0x15: { // House override byte
2503  byte override = buf->ReadByte();
2504 
2505  /* The house being overridden must be an original house. */
2506  if (override >= NEW_HOUSE_OFFSET) {
2507  GrfMsg(2, "TownHouseChangeInfo: Attempt to override new house {} with house id {}. Ignoring.", override, hid + i);
2508  continue;
2509  }
2510 
2511  _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2512  break;
2513  }
2514 
2515  case 0x16: // Periodic refresh multiplier
2516  housespec->processing_time = std::min<byte>(buf->ReadByte(), 63u);
2517  break;
2518 
2519  case 0x17: // Four random colours to use
2520  for (uint j = 0; j < 4; j++) housespec->random_colour[j] = static_cast<Colours>(GB(buf->ReadByte(), 0, 4));
2521  break;
2522 
2523  case 0x18: // Relative probability of appearing
2524  housespec->probability = buf->ReadByte();
2525  break;
2526 
2527  case 0x19: // Extra flags
2528  housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
2529  break;
2530 
2531  case 0x1A: // Animation frames
2532  housespec->animation.frames = buf->ReadByte();
2533  housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2534  SB(housespec->animation.frames, 7, 1, 0);
2535  break;
2536 
2537  case 0x1B: // Animation speed
2538  housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
2539  break;
2540 
2541  case 0x1C: // Class of the building type
2542  housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
2543  break;
2544 
2545  case 0x1D: // Callback mask part 2
2546  housespec->callback_mask |= (buf->ReadByte() << 8);
2547  break;
2548 
2549  case 0x1E: { // Accepted cargo types
2550  uint32_t cargotypes = buf->ReadDWord();
2551 
2552  /* Check if the cargo types should not be changed */
2553  if (cargotypes == 0xFFFFFFFF) break;
2554 
2555  for (uint j = 0; j < 3; j++) {
2556  /* Get the cargo number from the 'list' */
2557  uint8_t cargo_part = GB(cargotypes, 8 * j, 8);
2558  CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2559 
2560  if (!IsValidCargoID(cargo)) {
2561  /* Disable acceptance of invalid cargo type */
2562  housespec->cargo_acceptance[j] = 0;
2563  } else {
2564  housespec->accepts_cargo[j] = cargo;
2565  }
2566  }
2567  break;
2568  }
2569 
2570  case 0x1F: // Minimum life span
2571  housespec->minimum_life = buf->ReadByte();
2572  break;
2573 
2574  case 0x20: { // Cargo acceptance watch list
2575  byte count = buf->ReadByte();
2576  for (byte j = 0; j < count; j++) {
2577  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2578  if (IsValidCargoID(cargo)) SetBit(housespec->watched_cargoes, cargo);
2579  }
2580  break;
2581  }
2582 
2583  case 0x21: // long introduction year
2584  housespec->min_year = buf->ReadWord();
2585  break;
2586 
2587  case 0x22: // long maximum year
2588  housespec->max_year = buf->ReadWord();
2589  break;
2590 
2591  case 0x23: { // variable length cargo types accepted
2592  uint count = buf->ReadByte();
2593  if (count > lengthof(housespec->accepts_cargo)) {
2594  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2595  error->param_value[1] = prop;
2596  return CIR_DISABLED;
2597  }
2598  /* Always write the full accepts_cargo array, and check each index for being inside the
2599  * provided data. This ensures all values are properly initialized, and also avoids
2600  * any risks of array overrun. */
2601  for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2602  if (i < count) {
2603  housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2604  housespec->cargo_acceptance[i] = buf->ReadByte();
2605  } else {
2606  housespec->accepts_cargo[i] = INVALID_CARGO;
2607  housespec->cargo_acceptance[i] = 0;
2608  }
2609  housespec->accepts_cargo_label[i] = CT_INVALID;
2610  }
2611  break;
2612  }
2613 
2614  default:
2615  ret = CIR_UNKNOWN;
2616  break;
2617  }
2618  }
2619 
2620  return ret;
2621 }
2622 
2629 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32_t grfid, uint8_t language_id)
2630 {
2631  /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2632  const GRFFile *grffile = GetFileByGRFID(grfid);
2633  return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
2634 }
2635 
2645 template <typename T>
2646 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, std::vector<T> &translation_table, const char *name)
2647 {
2648  if (gvid != 0) {
2649  GrfMsg(1, "LoadTranslationTable: {} translation table must start at zero", name);
2650  return CIR_INVALID_ID;
2651  }
2652 
2653  translation_table.clear();
2654  for (int i = 0; i < numinfo; i++) {
2655  translation_table.push_back(T(BSWAP32(buf->ReadDWord())));
2656  }
2657 
2658  return CIR_SUCCESS;
2659 }
2660 
2667 static std::string ReadDWordAsString(ByteReader *reader)
2668 {
2669  std::string output;
2670  for (int i = 0; i < 4; i++) output.push_back(reader->ReadByte());
2671  return StrMakeValid(output);
2672 }
2673 
2682 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2683 {
2684  /* Properties which are handled as a whole */
2685  switch (prop) {
2686  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2687  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2688 
2689  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2690  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2691 
2692  case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2693  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2694 
2695  case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2696  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2697 
2698  default:
2699  break;
2700  }
2701 
2702  /* Properties which are handled per item */
2704  for (int i = 0; i < numinfo; i++) {
2705  switch (prop) {
2706  case 0x08: { // Cost base factor
2707  int factor = buf->ReadByte();
2708  uint price = gvid + i;
2709 
2710  if (price < PR_END) {
2711  _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2712  } else {
2713  GrfMsg(1, "GlobalVarChangeInfo: Price {} out of range, ignoring", price);
2714  }
2715  break;
2716  }
2717 
2718  case 0x0A: { // Currency display names
2719  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2720  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2721 
2722  if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2723  _currency_specs[curidx].name = newone;
2724  _currency_specs[curidx].code.clear();
2725  }
2726  break;
2727  }
2728 
2729  case 0x0B: { // Currency multipliers
2730  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2731  uint32_t rate = buf->ReadDWord();
2732 
2733  if (curidx < CURRENCY_END) {
2734  /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2735  * which OTTD does not. For this reason, divide grf value by 1000,
2736  * to be compatible */
2737  _currency_specs[curidx].rate = rate / 1000;
2738  } else {
2739  GrfMsg(1, "GlobalVarChangeInfo: Currency multipliers {} out of range, ignoring", curidx);
2740  }
2741  break;
2742  }
2743 
2744  case 0x0C: { // Currency options
2745  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2746  uint16_t options = buf->ReadWord();
2747 
2748  if (curidx < CURRENCY_END) {
2749  /* Ignore the thousands separator, as this is a translated thing. */
2750  /* By specifying only one bit, we prevent errors,
2751  * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2752  _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2753  } else {
2754  GrfMsg(1, "GlobalVarChangeInfo: Currency option {} out of range, ignoring", curidx);
2755  }
2756  break;
2757  }
2758 
2759  case 0x0D: { // Currency prefix symbol
2760  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2761  std::string prefix = ReadDWordAsString(buf);
2762 
2763  if (curidx < CURRENCY_END) {
2764  _currency_specs[curidx].prefix = prefix;
2765  } else {
2766  GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2767  }
2768  break;
2769  }
2770 
2771  case 0x0E: { // Currency suffix symbol
2772  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2773  std::string suffix = ReadDWordAsString(buf);
2774 
2775  if (curidx < CURRENCY_END) {
2776  _currency_specs[curidx].suffix = suffix;
2777  } else {
2778  GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2779  }
2780  break;
2781  }
2782 
2783  case 0x0F: { // Euro introduction dates
2784  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2785  TimerGameCalendar::Year year_euro = buf->ReadWord();
2786 
2787  if (curidx < CURRENCY_END) {
2788  _currency_specs[curidx].to_euro = year_euro;
2789  } else {
2790  GrfMsg(1, "GlobalVarChangeInfo: Euro intro date {} out of range, ignoring", curidx);
2791  }
2792  break;
2793  }
2794 
2795  case 0x10: // Snow line height table
2796  if (numinfo > 1 || IsSnowLineSet()) {
2797  GrfMsg(1, "GlobalVarChangeInfo: The snowline can only be set once ({})", numinfo);
2798  } else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2799  GrfMsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table ({})", buf->Remaining());
2800  } else {
2801  byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2802 
2803  for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2804  for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2805  table[i][j] = buf->ReadByte();
2806  if (_cur.grffile->grf_version >= 8) {
2807  if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2808  } else {
2809  if (table[i][j] >= 128) {
2810  /* no snow */
2811  table[i][j] = 0xFF;
2812  } else {
2813  table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2814  }
2815  }
2816  }
2817  }
2818  SetSnowLine(table);
2819  }
2820  break;
2821 
2822  case 0x11: // GRF match for engine allocation
2823  /* This is loaded during the reservation stage, so just skip it here. */
2824  /* Each entry is 8 bytes. */
2825  buf->Skip(8);
2826  break;
2827 
2828  case 0x13: // Gender translation table
2829  case 0x14: // Case translation table
2830  case 0x15: { // Plural form translation
2831  uint curidx = gvid + i; // The current index, i.e. language.
2832  const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2833  if (lang == nullptr) {
2834  GrfMsg(1, "GlobalVarChangeInfo: Language {} is not known, ignoring", curidx);
2835  /* Skip over the data. */
2836  if (prop == 0x15) {
2837  buf->ReadByte();
2838  } else {
2839  while (buf->ReadByte() != 0) {
2840  buf->ReadString();
2841  }
2842  }
2843  break;
2844  }
2845 
2846  if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
2847 
2848  if (prop == 0x15) {
2849  uint plural_form = buf->ReadByte();
2850  if (plural_form >= LANGUAGE_MAX_PLURAL) {
2851  GrfMsg(1, "GlobalVarChanceInfo: Plural form {} is out of range, ignoring", plural_form);
2852  } else {
2853  _cur.grffile->language_map[curidx].plural_form = plural_form;
2854  }
2855  break;
2856  }
2857 
2858  byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
2859  while (newgrf_id != 0) {
2860  const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
2861 
2862  /* We'll just ignore the UTF8 identifier character. This is (fairly)
2863  * safe as OpenTTD's strings gender/cases are usually in ASCII which
2864  * is just a subset of UTF8, or they need the bigger UTF8 characters
2865  * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2866  char32_t c;
2867  size_t len = Utf8Decode(&c, name);
2868  if (c == NFO_UTF8_IDENTIFIER) name += len;
2869 
2871  map.newgrf_id = newgrf_id;
2872  if (prop == 0x13) {
2873  map.openttd_id = lang->GetGenderIndex(name);
2874  if (map.openttd_id >= MAX_NUM_GENDERS) {
2875  GrfMsg(1, "GlobalVarChangeInfo: Gender name {} is not known, ignoring", name);
2876  } else {
2877  _cur.grffile->language_map[curidx].gender_map.push_back(map);
2878  }
2879  } else {
2880  map.openttd_id = lang->GetCaseIndex(name);
2881  if (map.openttd_id >= MAX_NUM_CASES) {
2882  GrfMsg(1, "GlobalVarChangeInfo: Case name {} is not known, ignoring", name);
2883  } else {
2884  _cur.grffile->language_map[curidx].case_map.push_back(map);
2885  }
2886  }
2887  newgrf_id = buf->ReadByte();
2888  }
2889  break;
2890  }
2891 
2892  default:
2893  ret = CIR_UNKNOWN;
2894  break;
2895  }
2896  }
2897 
2898  return ret;
2899 }
2900 
2901 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2902 {
2903  /* Properties which are handled as a whole */
2904  switch (prop) {
2905  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2906  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2907 
2908  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2909  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2910 
2911  case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2912  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2913 
2914  case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2915  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2916 
2917  default:
2918  break;
2919  }
2920 
2921  /* Properties which are handled per item */
2923  for (int i = 0; i < numinfo; i++) {
2924  switch (prop) {
2925  case 0x08: // Cost base factor
2926  case 0x15: // Plural form translation
2927  buf->ReadByte();
2928  break;
2929 
2930  case 0x0A: // Currency display names
2931  case 0x0C: // Currency options
2932  case 0x0F: // Euro introduction dates
2933  buf->ReadWord();
2934  break;
2935 
2936  case 0x0B: // Currency multipliers
2937  case 0x0D: // Currency prefix symbol
2938  case 0x0E: // Currency suffix symbol
2939  buf->ReadDWord();
2940  break;
2941 
2942  case 0x10: // Snow line height table
2943  buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2944  break;
2945 
2946  case 0x11: { // GRF match for engine allocation
2947  uint32_t s = buf->ReadDWord();
2948  uint32_t t = buf->ReadDWord();
2949  SetNewGRFOverride(s, t);
2950  break;
2951  }
2952 
2953  case 0x13: // Gender translation table
2954  case 0x14: // Case translation table
2955  while (buf->ReadByte() != 0) {
2956  buf->ReadString();
2957  }
2958  break;
2959 
2960  default:
2961  ret = CIR_UNKNOWN;
2962  break;
2963  }
2964  }
2965 
2966  return ret;
2967 }
2968 
2969 
2978 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
2979 {
2981 
2982  if (cid + numinfo > NUM_CARGO) {
2983  GrfMsg(2, "CargoChangeInfo: Cargo type {} out of range (max {})", cid + numinfo, NUM_CARGO - 1);
2984  return CIR_INVALID_ID;
2985  }
2986 
2987  for (int i = 0; i < numinfo; i++) {
2988  CargoSpec *cs = CargoSpec::Get(cid + i);
2989 
2990  switch (prop) {
2991  case 0x08: // Bit number of cargo
2992  cs->bitnum = buf->ReadByte();
2993  if (cs->IsValid()) {
2994  cs->grffile = _cur.grffile;
2995  SetBit(_cargo_mask, cid + i);
2996  } else {
2997  ClrBit(_cargo_mask, cid + i);
2998  }
3000  break;
3001 
3002  case 0x09: // String ID for cargo type name
3003  AddStringForMapping(buf->ReadWord(), &cs->name);
3004  break;
3005 
3006  case 0x0A: // String for 1 unit of cargo
3007  AddStringForMapping(buf->ReadWord(), &cs->name_single);
3008  break;
3009 
3010  case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
3011  case 0x1B: // String for cargo units
3012  /* String for units of cargo. This is different in OpenTTD
3013  * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
3014  * Property 1B is used to set OpenTTD's behaviour. */
3015  AddStringForMapping(buf->ReadWord(), &cs->units_volume);
3016  break;
3017 
3018  case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
3019  case 0x1C: // String for any amount of cargo
3020  /* Strings for an amount of cargo. This is different in OpenTTD
3021  * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
3022  * Property 1C is used to set OpenTTD's behaviour. */
3023  AddStringForMapping(buf->ReadWord(), &cs->quantifier);
3024  break;
3025 
3026  case 0x0D: // String for two letter cargo abbreviation
3027  AddStringForMapping(buf->ReadWord(), &cs->abbrev);
3028  break;
3029 
3030  case 0x0E: // Sprite ID for cargo icon
3031  cs->sprite = buf->ReadWord();
3032  break;
3033 
3034  case 0x0F: // Weight of one unit of cargo
3035  cs->weight = buf->ReadByte();
3036  break;
3037 
3038  case 0x10: // Used for payment calculation
3039  cs->transit_periods[0] = buf->ReadByte();
3040  break;
3041 
3042  case 0x11: // Used for payment calculation
3043  cs->transit_periods[1] = buf->ReadByte();
3044  break;
3045 
3046  case 0x12: // Base cargo price
3047  cs->initial_payment = buf->ReadDWord();
3048  break;
3049 
3050  case 0x13: // Colour for station rating bars
3051  cs->rating_colour = buf->ReadByte();
3052  break;
3053 
3054  case 0x14: // Colour for cargo graph
3055  cs->legend_colour = buf->ReadByte();
3056  break;
3057 
3058  case 0x15: // Freight status
3059  cs->is_freight = (buf->ReadByte() != 0);
3060  break;
3061 
3062  case 0x16: // Cargo classes
3063  cs->classes = buf->ReadWord();
3064  break;
3065 
3066  case 0x17: // Cargo label
3067  cs->label = CargoLabel{BSWAP32(buf->ReadDWord())};
3069  break;
3070 
3071  case 0x18: { // Town growth substitute type
3072  uint8_t substitute_type = buf->ReadByte();
3073 
3074  switch (substitute_type) {
3075  case 0x00: cs->town_acceptance_effect = TAE_PASSENGERS; break;
3076  case 0x02: cs->town_acceptance_effect = TAE_MAIL; break;
3077  case 0x05: cs->town_acceptance_effect = TAE_GOODS; break;
3078  case 0x09: cs->town_acceptance_effect = TAE_WATER; break;
3079  case 0x0B: cs->town_acceptance_effect = TAE_FOOD; break;
3080  default:
3081  GrfMsg(1, "CargoChangeInfo: Unknown town growth substitute value {}, setting to none.", substitute_type);
3082  [[fallthrough]];
3083  case 0xFF: cs->town_acceptance_effect = TAE_NONE; break;
3084  }
3085  break;
3086  }
3087 
3088  case 0x19: // Town growth coefficient
3089  buf->ReadWord();
3090  break;
3091 
3092  case 0x1A: // Bitmask of callbacks to use
3093  cs->callback_mask = buf->ReadByte();
3094  break;
3095 
3096  case 0x1D: // Vehicle capacity muliplier
3097  cs->multiplier = std::max<uint16_t>(1u, buf->ReadWord());
3098  break;
3099 
3100  case 0x1E: { // Town production substitute type
3101  uint8_t substitute_type = buf->ReadByte();
3102 
3103  switch (substitute_type) {
3104  case 0x00: cs->town_production_effect = TPE_PASSENGERS; break;
3105  case 0x02: cs->town_production_effect = TPE_MAIL; break;
3106  default:
3107  GrfMsg(1, "CargoChangeInfo: Unknown town production substitute value {}, setting to none.", substitute_type);
3108  [[fallthrough]];
3109  case 0xFF: cs->town_production_effect = TPE_NONE; break;
3110  }
3111  break;
3112  }
3113 
3114  case 0x1F: // Town production multiplier
3115  cs->town_production_multiplier = std::max<uint16_t>(1U, buf->ReadWord());
3116  break;
3117 
3118  default:
3119  ret = CIR_UNKNOWN;
3120  break;
3121  }
3122  }
3123 
3124  return ret;
3125 }
3126 
3127 
3136 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
3137 {
3139 
3140  if (_cur.grffile->sound_offset == 0) {
3141  GrfMsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3142  return CIR_INVALID_ID;
3143  }
3144 
3145  if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3146  GrfMsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect ({}), max ({}). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3147  return CIR_INVALID_ID;
3148  }
3149 
3150  for (int i = 0; i < numinfo; i++) {
3151  SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3152 
3153  switch (prop) {
3154  case 0x08: // Relative volume
3155  sound->volume = buf->ReadByte();
3156  break;
3157 
3158  case 0x09: // Priority
3159  sound->priority = buf->ReadByte();
3160  break;
3161 
3162  case 0x0A: { // Override old sound
3163  SoundID orig_sound = buf->ReadByte();
3164 
3165  if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3166  GrfMsg(1, "SoundEffectChangeInfo: Original sound {} not defined (max {})", orig_sound, ORIGINAL_SAMPLE_COUNT);
3167  } else {
3168  SoundEntry *old_sound = GetSound(orig_sound);
3169 
3170  /* Literally copy the data of the new sound over the original */
3171  *old_sound = *sound;
3172  }
3173  break;
3174  }
3175 
3176  default:
3177  ret = CIR_UNKNOWN;
3178  break;
3179  }
3180  }
3181 
3182  return ret;
3183 }
3184 
3192 {
3194 
3195  switch (prop) {
3196  case 0x09:
3197  case 0x0D:
3198  case 0x0E:
3199  case 0x10:
3200  case 0x11:
3201  case 0x12:
3202  buf->ReadByte();
3203  break;
3204 
3205  case 0x0A:
3206  case 0x0B:
3207  case 0x0C:
3208  case 0x0F:
3209  buf->ReadWord();
3210  break;
3211 
3212  case 0x13:
3213  buf->Skip(buf->ReadByte() * 2);
3214  break;
3215 
3216  default:
3217  ret = CIR_UNKNOWN;
3218  break;
3219  }
3220  return ret;
3221 }
3222 
3231 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
3232 {
3234 
3235  if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3236  GrfMsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded ({}), max ({}). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3237  return CIR_INVALID_ID;
3238  }
3239 
3240  /* Allocate industry tile specs if they haven't been allocated already. */
3241  if (_cur.grffile->indtspec.size() < indtid + numinfo) _cur.grffile->indtspec.resize(indtid + numinfo);
3242 
3243  for (int i = 0; i < numinfo; i++) {
3244  IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i].get();
3245 
3246  if (prop != 0x08 && tsp == nullptr) {
3248  if (cir > ret) ret = cir;
3249  continue;
3250  }
3251 
3252  switch (prop) {
3253  case 0x08: { // Substitute industry tile type
3254  byte subs_id = buf->ReadByte();
3255  if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3256  /* The substitute id must be one of the original industry tile. */
3257  GrfMsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile {} as substitute industry tile for {}. Ignoring.", subs_id, indtid + i);
3258  continue;
3259  }
3260 
3261  /* Allocate space for this industry. */
3262  if (tsp == nullptr) {
3263  _cur.grffile->indtspec[indtid + i] = std::make_unique<IndustryTileSpec>(_industry_tile_specs[subs_id]);
3264  tsp = _cur.grffile->indtspec[indtid + i].get();
3265 
3266  tsp->enabled = true;
3267 
3268  /* A copied tile should not have the animation infos copied too.
3269  * The anim_state should be left untouched, though
3270  * It is up to the author to animate them */
3273 
3274  tsp->grf_prop.local_id = indtid + i;
3275  tsp->grf_prop.subst_id = subs_id;
3276  tsp->grf_prop.grffile = _cur.grffile;
3277  _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3278  }
3279  break;
3280  }
3281 
3282  case 0x09: { // Industry tile override
3283  byte ovrid = buf->ReadByte();
3284 
3285  /* The industry being overridden must be an original industry. */
3286  if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3287  GrfMsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile {} with industry tile id {}. Ignoring.", ovrid, indtid + i);
3288  continue;
3289  }
3290 
3291  _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3292  break;
3293  }
3294 
3295  case 0x0A: // Tile acceptance
3296  case 0x0B:
3297  case 0x0C: {
3298  uint16_t acctp = buf->ReadWord();
3299  tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3300  tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3301  break;
3302  }
3303 
3304  case 0x0D: // Land shape flags
3305  tsp->slopes_refused = (Slope)buf->ReadByte();
3306  break;
3307 
3308  case 0x0E: // Callback mask
3309  tsp->callback_mask = buf->ReadByte();
3310  break;
3311 
3312  case 0x0F: // Animation information
3313  tsp->animation.frames = buf->ReadByte();
3314  tsp->animation.status = buf->ReadByte();
3315  break;
3316 
3317  case 0x10: // Animation speed
3318  tsp->animation.speed = buf->ReadByte();
3319  break;
3320 
3321  case 0x11: // Triggers for callback 25
3322  tsp->animation.triggers = buf->ReadByte();
3323  break;
3324 
3325  case 0x12: // Special flags
3326  tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
3327  break;
3328 
3329  case 0x13: { // variable length cargo acceptance
3330  byte num_cargoes = buf->ReadByte();
3331  if (num_cargoes > std::size(tsp->acceptance)) {
3332  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3333  error->param_value[1] = prop;
3334  return CIR_DISABLED;
3335  }
3336  for (uint i = 0; i < std::size(tsp->acceptance); i++) {
3337  if (i < num_cargoes) {
3338  tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3339  /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3340  tsp->acceptance[i] = (int8_t)buf->ReadByte();
3341  } else {
3342  tsp->accepts_cargo[i] = INVALID_CARGO;
3343  tsp->acceptance[i] = 0;
3344  }
3345  tsp->accepts_cargo_label[i] = CT_INVALID;
3346  }
3347  break;
3348  }
3349 
3350  default:
3351  ret = CIR_UNKNOWN;
3352  break;
3353  }
3354  }
3355 
3356  return ret;
3357 }
3358 
3366 {
3368 
3369  switch (prop) {
3370  case 0x09:
3371  case 0x0B:
3372  case 0x0F:
3373  case 0x12:
3374  case 0x13:
3375  case 0x14:
3376  case 0x17:
3377  case 0x18:
3378  case 0x19:
3379  case 0x21:
3380  case 0x22:
3381  buf->ReadByte();
3382  break;
3383 
3384  case 0x0C:
3385  case 0x0D:
3386  case 0x0E:
3387  case 0x10:
3388  case 0x1B:
3389  case 0x1F:
3390  case 0x24:
3391  buf->ReadWord();
3392  break;
3393 
3394  case 0x11:
3395  case 0x1A:
3396  case 0x1C:
3397  case 0x1D:
3398  case 0x1E:
3399  case 0x20:
3400  case 0x23:
3401  buf->ReadDWord();
3402  break;
3403 
3404  case 0x0A: {
3405  byte num_table = buf->ReadByte();
3406  for (byte j = 0; j < num_table; j++) {
3407  for (uint k = 0;; k++) {
3408  byte x = buf->ReadByte();
3409  if (x == 0xFE && k == 0) {
3410  buf->ReadByte();
3411  buf->ReadByte();
3412  break;
3413  }
3414 
3415  byte y = buf->ReadByte();
3416  if (x == 0 && y == 0x80) break;
3417 
3418  byte gfx = buf->ReadByte();
3419  if (gfx == 0xFE) buf->ReadWord();
3420  }
3421  }
3422  break;
3423  }
3424 
3425  case 0x16:
3426  for (byte j = 0; j < 3; j++) buf->ReadByte();
3427  break;
3428 
3429  case 0x15:
3430  case 0x25:
3431  case 0x26:
3432  case 0x27:
3433  buf->Skip(buf->ReadByte());
3434  break;
3435 
3436  case 0x28: {
3437  int num_inputs = buf->ReadByte();
3438  int num_outputs = buf->ReadByte();
3439  buf->Skip(num_inputs * num_outputs * 2);
3440  break;
3441  }
3442 
3443  default:
3444  ret = CIR_UNKNOWN;
3445  break;
3446  }
3447  return ret;
3448 }
3449 
3455 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3456 {
3457  const size_t size = layout.size();
3458  if (size == 0) return false;
3459 
3460  for (size_t i = 0; i < size - 1; i++) {
3461  for (size_t j = i + 1; j < size; j++) {
3462  if (layout[i].ti.x == layout[j].ti.x &&
3463  layout[i].ti.y == layout[j].ti.y) {
3464  return false;
3465  }
3466  }
3467  }
3468 
3469  bool have_regular_tile = false;
3470  for (const auto &tilelayout : layout) {
3471  if (tilelayout.gfx != GFX_WATERTILE_SPECIALCHECK) {
3472  have_regular_tile = true;
3473  break;
3474  }
3475  }
3476 
3477  return have_regular_tile;
3478 }
3479 
3488 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
3489 {
3491 
3492  if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3493  GrfMsg(1, "IndustriesChangeInfo: Too many industries loaded ({}), max ({}). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3494  return CIR_INVALID_ID;
3495  }
3496 
3497  /* Allocate industry specs if they haven't been allocated already. */
3498  if (_cur.grffile->industryspec.size() < indid + numinfo) _cur.grffile->industryspec.resize(indid + numinfo);
3499 
3500  for (int i = 0; i < numinfo; i++) {
3501  IndustrySpec *indsp = _cur.grffile->industryspec[indid + i].get();
3502 
3503  if (prop != 0x08 && indsp == nullptr) {
3504  ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3505  if (cir > ret) ret = cir;
3506  continue;
3507  }
3508 
3509  switch (prop) {
3510  case 0x08: { // Substitute industry type
3511  byte subs_id = buf->ReadByte();
3512  if (subs_id == 0xFF) {
3513  /* Instead of defining a new industry, a substitute industry id
3514  * of 0xFF disables the old industry with the current id. */
3515  _industry_specs[indid + i].enabled = false;
3516  continue;
3517  } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3518  /* The substitute id must be one of the original industry. */
3519  GrfMsg(2, "_industry_specs: Attempt to use new industry {} as substitute industry for {}. Ignoring.", subs_id, indid + i);
3520  continue;
3521  }
3522 
3523  /* Allocate space for this industry.
3524  * Only need to do it once. If ever it is called again, it should not
3525  * do anything */
3526  if (indsp == nullptr) {
3527  _cur.grffile->industryspec[indid + i] = std::make_unique<IndustrySpec>(_origin_industry_specs[subs_id]);
3528  indsp = _cur.grffile->industryspec[indid + i].get();
3529 
3530  indsp->enabled = true;
3531  indsp->grf_prop.local_id = indid + i;
3532  indsp->grf_prop.subst_id = subs_id;
3533  indsp->grf_prop.grffile = _cur.grffile;
3534  /* If the grf industry needs to check its surrounding upon creation, it should
3535  * rely on callbacks, not on the original placement functions */
3536  indsp->check_proc = CHECK_NOTHING;
3537  }
3538  break;
3539  }
3540 
3541  case 0x09: { // Industry type override
3542  byte ovrid = buf->ReadByte();
3543 
3544  /* The industry being overridden must be an original industry. */
3545  if (ovrid >= NEW_INDUSTRYOFFSET) {
3546  GrfMsg(2, "IndustriesChangeInfo: Attempt to override new industry {} with industry id {}. Ignoring.", ovrid, indid + i);
3547  continue;
3548  }
3549  indsp->grf_prop.override = ovrid;
3550  _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3551  break;
3552  }
3553 
3554  case 0x0A: { // Set industry layout(s)
3555  byte new_num_layouts = buf->ReadByte();
3556  uint32_t definition_size = buf->ReadDWord();
3557  uint32_t bytes_read = 0;
3558  std::vector<IndustryTileLayout> new_layouts;
3559  IndustryTileLayout layout;
3560 
3561  for (byte j = 0; j < new_num_layouts; j++) {
3562  layout.clear();
3563 
3564  for (uint k = 0;; k++) {
3565  if (bytes_read >= definition_size) {
3566  GrfMsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry {}.", indid);
3567  /* Avoid warning twice */
3568  definition_size = UINT32_MAX;
3569  }
3570 
3571  layout.push_back(IndustryTileLayoutTile{});
3572  IndustryTileLayoutTile &it = layout.back();
3573 
3574  it.ti.x = buf->ReadByte(); // Offsets from northermost tile
3575  ++bytes_read;
3576 
3577  if (it.ti.x == 0xFE && k == 0) {
3578  /* This means we have to borrow the layout from an old industry */
3579  IndustryType type = buf->ReadByte();
3580  byte laynbr = buf->ReadByte();
3581  bytes_read += 2;
3582 
3583  if (type >= lengthof(_origin_industry_specs)) {
3584  GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", indid);
3585  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3586  return CIR_DISABLED;
3587  }
3588  if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3589  GrfMsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry {}", indid);
3590  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3591  return CIR_DISABLED;
3592  }
3593  layout = _origin_industry_specs[type].layouts[laynbr];
3594  break;
3595  }
3596 
3597  it.ti.y = buf->ReadByte(); // Or table definition finalisation
3598  ++bytes_read;
3599 
3600  if (it.ti.x == 0 && it.ti.y == 0x80) {
3601  /* Terminator, remove and finish up */
3602  layout.pop_back();
3603  break;
3604  }
3605 
3606  it.gfx = buf->ReadByte();
3607  ++bytes_read;
3608 
3609  if (it.gfx == 0xFE) {
3610  /* Use a new tile from this GRF */
3611  int local_tile_id = buf->ReadWord();
3612  bytes_read += 2;
3613 
3614  /* Read the ID from the _industile_mngr. */
3615  int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3616 
3617  if (tempid == INVALID_INDUSTRYTILE) {
3618  GrfMsg(2, "IndustriesChangeInfo: Attempt to use industry tile {} with industry id {}, not yet defined. Ignoring.", local_tile_id, indid);
3619  } else {
3620  /* Declared as been valid, can be used */
3621  it.gfx = tempid;
3622  }
3623  } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
3624  it.ti.x = (int8_t)GB(it.ti.x, 0, 8);
3625  it.ti.y = (int8_t)GB(it.ti.y, 0, 8);
3626 
3627  /* When there were only 256x256 maps, TileIndex was a uint16_t and
3628  * it.ti was just a TileIndexDiff that was added to it.
3629  * As such negative "x" values were shifted into the "y" position.
3630  * x = -1, y = 1 -> x = 255, y = 0
3631  * Since GRF version 8 the position is interpreted as pair of independent int8.
3632  * For GRF version < 8 we need to emulate the old shifting behaviour.
3633  */
3634  if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3635  }
3636  }
3637 
3638  if (!ValidateIndustryLayout(layout)) {
3639  /* The industry layout was not valid, so skip this one. */
3640  GrfMsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id {}. Ignoring", indid);
3641  new_num_layouts--;
3642  j--;
3643  } else {
3644  new_layouts.push_back(layout);
3645  }
3646  }
3647 
3648  /* Install final layout construction in the industry spec */
3649  indsp->layouts = new_layouts;
3650  break;
3651  }
3652 
3653  case 0x0B: // Industry production flags
3654  indsp->life_type = (IndustryLifeType)buf->ReadByte();
3655  break;
3656 
3657  case 0x0C: // Industry closure message
3658  AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
3659  break;
3660 
3661  case 0x0D: // Production increase message
3662  AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
3663  break;
3664 
3665  case 0x0E: // Production decrease message
3666  AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
3667  break;
3668 
3669  case 0x0F: // Fund cost multiplier
3670  indsp->cost_multiplier = buf->ReadByte();
3671  break;
3672 
3673  case 0x10: // Production cargo types
3674  for (byte j = 0; j < 2; j++) {
3675  indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3676  indsp->produced_cargo_label[j] = CT_INVALID;
3677  }
3678  break;
3679 
3680  case 0x11: // Acceptance cargo types
3681  for (byte j = 0; j < 3; j++) {
3682  indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3683  indsp->accepts_cargo_label[j] = CT_INVALID;
3684  }
3685  buf->ReadByte(); // Unnused, eat it up
3686  break;
3687 
3688  case 0x12: // Production multipliers
3689  case 0x13:
3690  indsp->production_rate[prop - 0x12] = buf->ReadByte();
3691  break;
3692 
3693  case 0x14: // Minimal amount of cargo distributed
3694  indsp->minimal_cargo = buf->ReadByte();
3695  break;
3696 
3697  case 0x15: { // Random sound effects
3698  indsp->number_of_sounds = buf->ReadByte();
3699  uint8_t *sounds = MallocT<uint8_t>(indsp->number_of_sounds);
3700 
3701  try {
3702  for (uint8_t j = 0; j < indsp->number_of_sounds; j++) {
3703  sounds[j] = buf->ReadByte();
3704  }
3705  } catch (...) {
3706  free(sounds);
3707  throw;
3708  }
3709 
3710  if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3711  free(indsp->random_sounds);
3712  }
3713  indsp->random_sounds = sounds;
3715  break;
3716  }
3717 
3718  case 0x16: // Conflicting industry types
3719  for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
3720  break;
3721 
3722  case 0x17: // Probability in random game
3723  indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
3724  break;
3725 
3726  case 0x18: // Probability during gameplay
3727  indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
3728  break;
3729 
3730  case 0x19: // Map colour
3731  indsp->map_colour = buf->ReadByte();
3732  break;
3733 
3734  case 0x1A: // Special industry flags to define special behavior
3735  indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
3736  break;
3737 
3738  case 0x1B: // New industry text ID
3739  AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
3740  break;
3741 
3742  case 0x1C: // Input cargo multipliers for the three input cargo types
3743  case 0x1D:
3744  case 0x1E: {
3745  uint32_t multiples = buf->ReadDWord();
3746  indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3747  indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3748  break;
3749  }
3750 
3751  case 0x1F: // Industry name
3752  AddStringForMapping(buf->ReadWord(), &indsp->name);
3753  break;
3754 
3755  case 0x20: // Prospecting success chance
3756  indsp->prospecting_chance = buf->ReadDWord();
3757  break;
3758 
3759  case 0x21: // Callback mask
3760  case 0x22: { // Callback additional mask
3761  byte aflag = buf->ReadByte();
3762  SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3763  break;
3764  }
3765 
3766  case 0x23: // removal cost multiplier
3767  indsp->removal_cost_multiplier = buf->ReadDWord();
3768  break;
3769 
3770  case 0x24: { // name for nearby station
3771  uint16_t str = buf->ReadWord();
3772  if (str == 0) {
3773  indsp->station_name = STR_NULL;
3774  } else {
3775  AddStringForMapping(str, &indsp->station_name);
3776  }
3777  break;
3778  }
3779 
3780  case 0x25: { // variable length produced cargoes
3781  byte num_cargoes = buf->ReadByte();
3782  if (num_cargoes > lengthof(indsp->produced_cargo)) {
3783  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3784  error->param_value[1] = prop;
3785  return CIR_DISABLED;
3786  }
3787  for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
3788  if (i < num_cargoes) {
3789  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3790  indsp->produced_cargo[i] = cargo;
3791  } else {
3792  indsp->produced_cargo[i] = INVALID_CARGO;
3793  }
3794  indsp->produced_cargo_label[i] = CT_INVALID;
3795  }
3796  break;
3797  }
3798 
3799  case 0x26: { // variable length accepted cargoes
3800  byte num_cargoes = buf->ReadByte();
3801  if (num_cargoes > lengthof(indsp->accepts_cargo)) {
3802  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3803  error->param_value[1] = prop;
3804  return CIR_DISABLED;
3805  }
3806  for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3807  if (i < num_cargoes) {
3808  CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3809  indsp->accepts_cargo[i] = cargo;
3810  } else {
3811  indsp->accepts_cargo[i] = INVALID_CARGO;
3812  }
3813  indsp->accepts_cargo_label[i] = CT_INVALID;
3814  }
3815  break;
3816  }
3817 
3818  case 0x27: { // variable length production rates
3819  byte num_cargoes = buf->ReadByte();
3820  if (num_cargoes > lengthof(indsp->production_rate)) {
3821  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3822  error->param_value[1] = prop;
3823  return CIR_DISABLED;
3824  }
3825  for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3826  if (i < num_cargoes) {
3827  indsp->production_rate[i] = buf->ReadByte();
3828  } else {
3829  indsp->production_rate[i] = 0;
3830  }
3831  }
3832  break;
3833  }
3834 
3835  case 0x28: { // variable size input/output production multiplier table
3836  byte num_inputs = buf->ReadByte();
3837  byte num_outputs = buf->ReadByte();
3838  if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
3839  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3840  error->param_value[1] = prop;
3841  return CIR_DISABLED;
3842  }
3843  for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3844  for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
3845  uint16_t mult = 0;
3846  if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
3847  indsp->input_cargo_multiplier[i][j] = mult;
3848  }
3849  }
3850  break;
3851  }
3852 
3853  default:
3854  ret = CIR_UNKNOWN;
3855  break;
3856  }
3857  }
3858 
3859  return ret;
3860 }
3861 
3868 {
3869  AirportTileTable **table_list = MallocT<AirportTileTable*>(as->num_table);
3870  for (int i = 0; i < as->num_table; i++) {
3871  uint num_tiles = 1;
3872  const AirportTileTable *it = as->table[0];
3873  do {
3874  num_tiles++;
3875  } while ((++it)->ti.x != -0x80);
3876  table_list[i] = MallocT<AirportTileTable>(num_tiles);
3877  MemCpyT(table_list[i], as->table[i], num_tiles);
3878  }
3879  as->table = table_list;
3880  HangarTileTable *depot_table = MallocT<HangarTileTable>(as->nof_depots);
3881  MemCpyT(depot_table, as->depot_table, as->nof_depots);
3882  as->depot_table = depot_table;
3883  Direction *rotation = MallocT<Direction>(as->num_table);
3884  MemCpyT(rotation, as->rotation, as->num_table);
3885  as->rotation = rotation;
3886 }
3887 
3896 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
3897 {
3899 
3900  if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3901  GrfMsg(1, "AirportChangeInfo: Too many airports, trying id ({}), max ({}). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3902  return CIR_INVALID_ID;
3903  }
3904 
3905  /* Allocate industry specs if they haven't been allocated already. */
3906  if (_cur.grffile->airportspec.size() < airport + numinfo) _cur.grffile->airportspec.resize(airport + numinfo);
3907 
3908  for (int i = 0; i < numinfo; i++) {
3909  AirportSpec *as = _cur.grffile->airportspec[airport + i].get();
3910 
3911  if (as == nullptr && prop != 0x08 && prop != 0x09) {
3912  GrfMsg(2, "AirportChangeInfo: Attempt to modify undefined airport {}, ignoring", airport + i);
3913  return CIR_INVALID_ID;
3914  }
3915 
3916  switch (prop) {
3917  case 0x08: { // Modify original airport
3918  byte subs_id = buf->ReadByte();
3919  if (subs_id == 0xFF) {
3920  /* Instead of defining a new airport, an airport id
3921  * of 0xFF disables the old airport with the current id. */
3922  AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3923  continue;
3924  } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3925  /* The substitute id must be one of the original airports. */
3926  GrfMsg(2, "AirportChangeInfo: Attempt to use new airport {} as substitute airport for {}. Ignoring.", subs_id, airport + i);
3927  continue;
3928  }
3929 
3930  /* Allocate space for this airport.
3931  * Only need to do it once. If ever it is called again, it should not
3932  * do anything */
3933  if (as == nullptr) {
3934  _cur.grffile->airportspec[airport + i] = std::make_unique<AirportSpec>(*AirportSpec::GetWithoutOverride(subs_id));
3935  as = _cur.grffile->airportspec[airport + i].get();
3936 
3937  as->enabled = true;
3938  as->grf_prop.local_id = airport + i;
3939  as->grf_prop.subst_id = subs_id;
3940  as->grf_prop.grffile = _cur.grffile;
3941  /* override the default airport */
3942  _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3943  /* Create a copy of the original tiletable so it can be freed later. */
3944  DuplicateTileTable(as);
3945  }
3946  break;
3947  }
3948 
3949  case 0x0A: { // Set airport layout
3950  byte old_num_table = as->num_table;
3951  free(as->rotation);
3952  as->num_table = buf->ReadByte(); // Number of layaouts
3953  as->rotation = MallocT<Direction>(as->num_table);
3954  uint32_t defsize = buf->ReadDWord(); // Total size of the definition
3955  AirportTileTable **tile_table = CallocT<AirportTileTable*>(as->num_table); // Table with tiles to compose the airport
3956  AirportTileTable *att = CallocT<AirportTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
3957  int size;
3958  const AirportTileTable *copy_from;
3959  try {
3960  for (byte j = 0; j < as->num_table; j++) {
3961  const_cast<Direction&>(as->rotation[j]) = (Direction)buf->ReadByte();
3962  for (int k = 0;; k++) {
3963  att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3964  att[k].ti.y = buf->ReadByte();
3965 
3966  if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
3967  /* Not the same terminator. The one we are using is rather
3968  * x = -80, y = 0 . So, adjust it. */
3969  att[k].ti.x = -0x80;
3970  att[k].ti.y = 0;
3971  att[k].gfx = 0;
3972 
3973  size = k + 1;
3974  copy_from = att;
3975  break;
3976  }
3977 
3978  att[k].gfx = buf->ReadByte();
3979 
3980  if (att[k].gfx == 0xFE) {
3981  /* Use a new tile from this GRF */
3982  int local_tile_id = buf->ReadWord();
3983 
3984  /* Read the ID from the _airporttile_mngr. */
3985  uint16_t tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3986 
3987  if (tempid == INVALID_AIRPORTTILE) {
3988  GrfMsg(2, "AirportChangeInfo: Attempt to use airport tile {} with airport id {}, not yet defined. Ignoring.", local_tile_id, airport + i);
3989  } else {
3990  /* Declared as been valid, can be used */
3991  att[k].gfx = tempid;
3992  }
3993  } else if (att[k].gfx == 0xFF) {
3994  att[k].ti.x = (int8_t)GB(att[k].ti.x, 0, 8);
3995  att[k].ti.y = (int8_t)GB(att[k].ti.y, 0, 8);
3996  }
3997 
3998  if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
3999  as->size_x = std::max<byte>(as->size_x, att[k].ti.y + 1);
4000  as->size_y = std::max<byte>(as->size_y, att[k].ti.x + 1);
4001  } else {
4002  as->size_x = std::max<byte>(as->size_x, att[k].ti.x + 1);
4003  as->size_y = std::max<byte>(as->size_y, att[k].ti.y + 1);
4004  }
4005  }
4006  tile_table[j] = CallocT<AirportTileTable>(size);
4007  memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
4008  }
4009  /* Free old layouts in the airport spec */
4010  for (int j = 0; j < old_num_table; j++) {
4011  /* remove the individual layouts */
4012  free(as->table[j]);
4013  }
4014  free(as->table);
4015  /* Install final layout construction in the airport spec */
4016  as->table = tile_table;
4017  free(att);
4018  } catch (...) {
4019  for (int i = 0; i < as->num_table; i++) {
4020  free(tile_table[i]);
4021  }
4022  free(tile_table);
4023  free(att);
4024  throw;
4025  }
4026  break;
4027  }
4028 
4029  case 0x0C:
4030  as->min_year = buf->ReadWord();
4031  as->max_year = buf->ReadWord();
4032  if (as->max_year == 0xFFFF) as->max_year = CalendarTime::MAX_YEAR;
4033  break;
4034 
4035  case 0x0D:
4036  as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
4037  break;
4038 
4039  case 0x0E:
4040  as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
4041  break;
4042 
4043  case 0x0F:
4044  as->noise_level = buf->ReadByte();
4045  break;
4046 
4047  case 0x10:
4048  AddStringForMapping(buf->ReadWord(), &as->name);
4049  break;
4050 
4051  case 0x11: // Maintenance cost factor
4052  as->maintenance_cost = buf->ReadWord();
4053  break;
4054 
4055  default:
4056  ret = CIR_UNKNOWN;
4057  break;
4058  }
4059  }
4060 
4061  return ret;
4062 }
4063 
4071 {
4073 
4074  switch (prop) {
4075  case 0x0B:
4076  case 0x0C:
4077  case 0x0D:
4078  case 0x12:
4079  case 0x14:
4080  case 0x16:
4081  case 0x17:
4082  case 0x18:
4083  buf->ReadByte();
4084  break;
4085 
4086  case 0x09:
4087  case 0x0A:
4088  case 0x10:
4089  case 0x11:
4090  case 0x13:
4091  case 0x15:
4092  buf->ReadWord();
4093  break;
4094 
4095  case 0x08:
4096  case 0x0E:
4097  case 0x0F:
4098  buf->ReadDWord();
4099  break;
4100 
4101  default:
4102  ret = CIR_UNKNOWN;
4103  break;
4104  }
4105 
4106  return ret;
4107 }
4108 
4117 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4118 {
4120 
4121  if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4122  GrfMsg(1, "ObjectChangeInfo: Too many objects loaded ({}), max ({}). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4123  return CIR_INVALID_ID;
4124  }
4125 
4126  /* Allocate object specs if they haven't been allocated already. */
4127  if (_cur.grffile->objectspec.size() < id + numinfo) _cur.grffile->objectspec.resize(id + numinfo);
4128 
4129  for (int i = 0; i < numinfo; i++) {
4130  ObjectSpec *spec = _cur.grffile->objectspec[id + i].get();
4131 
4132  if (prop != 0x08 && spec == nullptr) {
4133  /* If the object property 08 is not yet set, ignore this property */
4134  ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4135  if (cir > ret) ret = cir;
4136  continue;
4137  }
4138 
4139  switch (prop) {
4140  case 0x08: { // Class ID
4141  /* Allocate space for this object. */
4142  if (spec == nullptr) {
4143  _cur.grffile->objectspec[id + i] = std::make_unique<ObjectSpec>();
4144  spec = _cur.grffile->objectspec[id + i].get();
4145  spec->views = 1; // Default for NewGRFs that don't set it.
4146  spec->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
4147  }
4148 
4149  /* Swap classid because we read it in BE. */
4150  uint32_t classid = buf->ReadDWord();
4151  spec->cls_id = ObjectClass::Allocate(BSWAP32(classid));
4152  break;
4153  }
4154 
4155  case 0x09: { // Class name
4156  ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
4157  AddStringForMapping(buf->ReadWord(), &objclass->name);
4158  break;
4159  }
4160 
4161  case 0x0A: // Object name
4162  AddStringForMapping(buf->ReadWord(), &spec->name);
4163  break;
4164 
4165  case 0x0B: // Climate mask
4166  spec->climate = buf->ReadByte();
4167  break;
4168 
4169  case 0x0C: // Size
4170  spec->size = buf->ReadByte();
4171  if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4172  GrfMsg(0, "ObjectChangeInfo: Invalid object size requested (0x{:X}) for object id {}. Ignoring.", spec->size, id + i);
4173  spec->size = OBJECT_SIZE_1X1;
4174  }
4175  break;
4176 
4177  case 0x0D: // Build cost multipler
4178  spec->build_cost_multiplier = buf->ReadByte();
4180  break;
4181 
4182  case 0x0E: // Introduction date
4183  spec->introduction_date = buf->ReadDWord();
4184  break;
4185 
4186  case 0x0F: // End of life
4187  spec->end_of_life_date = buf->ReadDWord();
4188  break;
4189 
4190  case 0x10: // Flags
4191  spec->flags = (ObjectFlags)buf->ReadWord();
4193  break;
4194 
4195  case 0x11: // Animation info
4196  spec->animation.frames = buf->ReadByte();
4197  spec->animation.status = buf->ReadByte();
4198  break;
4199 
4200  case 0x12: // Animation speed
4201  spec->animation.speed = buf->ReadByte();
4202  break;
4203 
4204  case 0x13: // Animation triggers
4205  spec->animation.triggers = buf->ReadWord();
4206  break;
4207 
4208  case 0x14: // Removal cost multiplier
4209  spec->clear_cost_multiplier = buf->ReadByte();
4210  break;
4211 
4212  case 0x15: // Callback mask
4213  spec->callback_mask = buf->ReadWord();
4214  break;
4215 
4216  case 0x16: // Building height
4217  spec->height = buf->ReadByte();
4218  break;
4219 
4220  case 0x17: // Views
4221  spec->views = buf->ReadByte();
4222  if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4223  GrfMsg(2, "ObjectChangeInfo: Invalid number of views ({}) for object id {}. Ignoring.", spec->views, id + i);
4224  spec->views = 1;
4225  }
4226  break;
4227 
4228  case 0x18: // Amount placed on 256^2 map on map creation
4229  spec->generate_amount = buf->ReadByte();
4230  break;
4231 
4232  default:
4233  ret = CIR_UNKNOWN;
4234  break;
4235  }
4236  }
4237 
4238  return ret;
4239 }
4240 
4249 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4250 {
4252 
4253  extern RailTypeInfo _railtypes[RAILTYPE_END];
4254 
4255  if (id + numinfo > RAILTYPE_END) {
4256  GrfMsg(1, "RailTypeChangeInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4257  return CIR_INVALID_ID;
4258  }
4259 
4260  for (int i = 0; i < numinfo; i++) {
4261  RailType rt = _cur.grffile->railtype_map[id + i];
4262  if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4263 
4264  RailTypeInfo *rti = &_railtypes[rt];
4265 
4266  switch (prop) {
4267  case 0x08: // Label of rail type
4268  /* Skipped here as this is loaded during reservation stage. */
4269  buf->ReadDWord();
4270  break;
4271 
4272  case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4273  uint16_t str = buf->ReadWord();
4275  if (_cur.grffile->grf_version < 8) {
4276  AddStringForMapping(str, &rti->strings.name);
4277  }
4278  break;
4279  }
4280 
4281  case 0x0A: // Menu text of railtype
4282  AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4283  break;
4284 
4285  case 0x0B: // Build window caption
4286  AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4287  break;
4288 
4289  case 0x0C: // Autoreplace text
4290  AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4291  break;
4292 
4293  case 0x0D: // New locomotive text
4294  AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
4295  break;
4296 
4297  case 0x0E: // Compatible railtype list
4298  case 0x0F: // Powered railtype list
4299  case 0x18: // Railtype list required for date introduction
4300  case 0x19: // Introduced railtype list
4301  {
4302  /* Rail type compatibility bits are added to the existing bits
4303  * to allow multiple GRFs to modify compatibility with the
4304  * default rail types. */
4305  int n = buf->ReadByte();
4306  for (int j = 0; j != n; j++) {
4307  RailTypeLabel label = buf->ReadDWord();
4308  RailType resolved_rt = GetRailTypeByLabel(BSWAP32(label), false);
4309  if (resolved_rt != INVALID_RAILTYPE) {
4310  switch (prop) {
4311  case 0x0F: SetBit(rti->powered_railtypes, resolved_rt); [[fallthrough]]; // Powered implies compatible.
4312  case 0x0E: SetBit(rti->compatible_railtypes, resolved_rt); break;
4313  case 0x18: SetBit(rti->introduction_required_railtypes, resolved_rt); break;
4314  case 0x19: SetBit(rti->introduces_railtypes, resolved_rt); break;
4315  }
4316  }
4317  }
4318  break;
4319  }
4320 
4321  case 0x10: // Rail Type flags
4322  rti->flags = (RailTypeFlags)buf->ReadByte();
4323  break;
4324 
4325  case 0x11: // Curve speed advantage
4326  rti->curve_speed = buf->ReadByte();
4327  break;
4328 
4329  case 0x12: // Station graphic
4330  rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
4331  break;
4332 
4333  case 0x13: // Construction cost factor
4334  rti->cost_multiplier = buf->ReadWord();
4335  break;
4336 
4337  case 0x14: // Speed limit
4338  rti->max_speed = buf->ReadWord();
4339  break;
4340 
4341  case 0x15: // Acceleration model
4342  rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
4343  break;
4344 
4345  case 0x16: // Map colour
4346  rti->map_colour = buf->ReadByte();
4347  break;
4348 
4349  case 0x17: // Introduction date
4350  rti->introduction_date = buf->ReadDWord();
4351  break;
4352 
4353  case 0x1A: // Sort order
4354  rti->sorting_order = buf->ReadByte();
4355  break;
4356 
4357  case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4358  AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4359  break;
4360 
4361  case 0x1C: // Maintenance cost factor
4362  rti->maintenance_multiplier = buf->ReadWord();
4363  break;
4364 
4365  case 0x1D: // Alternate rail type label list
4366  /* Skipped here as this is loaded during reservation stage. */
4367  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4368  break;
4369 
4370  default:
4371  ret = CIR_UNKNOWN;
4372  break;
4373  }
4374  }
4375 
4376  return ret;
4377 }
4378 
4379 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4380 {
4382 
4383  extern RailTypeInfo _railtypes[RAILTYPE_END];
4384 
4385  if (id + numinfo > RAILTYPE_END) {
4386  GrfMsg(1, "RailTypeReserveInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4387  return CIR_INVALID_ID;
4388  }
4389 
4390  for (int i = 0; i < numinfo; i++) {
4391  switch (prop) {
4392  case 0x08: // Label of rail type
4393  {
4394  RailTypeLabel rtl = buf->ReadDWord();
4395  rtl = BSWAP32(rtl);
4396 
4397  RailType rt = GetRailTypeByLabel(rtl, false);
4398  if (rt == INVALID_RAILTYPE) {
4399  /* Set up new rail type */
4400  rt = AllocateRailType(rtl);
4401  }
4402 
4403  _cur.grffile->railtype_map[id + i] = rt;
4404  break;
4405  }
4406 
4407  case 0x09: // Toolbar caption of railtype
4408  case 0x0A: // Menu text
4409  case 0x0B: // Build window caption
4410  case 0x0C: // Autoreplace text
4411  case 0x0D: // New loco
4412  case 0x13: // Construction cost
4413  case 0x14: // Speed limit
4414  case 0x1B: // Name of railtype
4415  case 0x1C: // Maintenance cost factor
4416  buf->ReadWord();
4417  break;
4418 
4419  case 0x1D: // Alternate rail type label list
4420  if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4421  int n = buf->ReadByte();
4422  for (int j = 0; j != n; j++) {
4423  _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4424  }
4425  break;
4426  }
4427  GrfMsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type {} because no label was set", id + i);
4428  [[fallthrough]];
4429 
4430  case 0x0E: // Compatible railtype list
4431  case 0x0F: // Powered railtype list
4432  case 0x18: // Railtype list required for date introduction
4433  case 0x19: // Introduced railtype list
4434  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4435  break;
4436 
4437  case 0x10: // Rail Type flags
4438  case 0x11: // Curve speed advantage
4439  case 0x12: // Station graphic
4440  case 0x15: // Acceleration model
4441  case 0x16: // Map colour
4442  case 0x1A: // Sort order
4443  buf->ReadByte();
4444  break;
4445 
4446  case 0x17: // Introduction date
4447  buf->ReadDWord();
4448  break;
4449 
4450  default:
4451  ret = CIR_UNKNOWN;
4452  break;
4453  }
4454  }
4455 
4456  return ret;
4457 }
4458 
4467 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4468 {
4470 
4471  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4472  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4473 
4474  if (id + numinfo > ROADTYPE_END) {
4475  GrfMsg(1, "RoadTypeChangeInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4476  return CIR_INVALID_ID;
4477  }
4478 
4479  for (int i = 0; i < numinfo; i++) {
4480  RoadType rt = type_map[id + i];
4481  if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4482 
4483  RoadTypeInfo *rti = &_roadtypes[rt];
4484 
4485  switch (prop) {
4486  case 0x08: // Label of road type
4487  /* Skipped here as this is loaded during reservation stage. */
4488  buf->ReadDWord();
4489  break;
4490 
4491  case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4492  uint16_t str = buf->ReadWord();
4494  break;
4495  }
4496 
4497  case 0x0A: // Menu text of roadtype
4498  AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4499  break;
4500 
4501  case 0x0B: // Build window caption
4502  AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4503  break;
4504 
4505  case 0x0C: // Autoreplace text
4506  AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4507  break;
4508 
4509  case 0x0D: // New engine text
4510  AddStringForMapping(buf->ReadWord(), &rti->strings.new_engine);
4511  break;
4512 
4513  case 0x0F: // Powered roadtype list
4514  case 0x18: // Roadtype list required for date introduction
4515  case 0x19: { // Introduced roadtype list
4516  /* Road type compatibility bits are added to the existing bits
4517  * to allow multiple GRFs to modify compatibility with the
4518  * default road types. */
4519  int n = buf->ReadByte();
4520  for (int j = 0; j != n; j++) {
4521  RoadTypeLabel label = buf->ReadDWord();
4522  RoadType resolved_rt = GetRoadTypeByLabel(BSWAP32(label), false);
4523  if (resolved_rt != INVALID_ROADTYPE) {
4524  switch (prop) {
4525  case 0x0F:
4526  if (GetRoadTramType(resolved_rt) == rtt) {
4527  SetBit(rti->powered_roadtypes, resolved_rt);
4528  } else {
4529  GrfMsg(1, "RoadTypeChangeInfo: Powered road type list: Road type {} road/tram type does not match road type {}, ignoring", resolved_rt, rt);
4530  }
4531  break;
4532  case 0x18: SetBit(rti->introduction_required_roadtypes, resolved_rt); break;
4533  case 0x19: SetBit(rti->introduces_roadtypes, resolved_rt); break;
4534  }
4535  }
4536  }
4537  break;
4538  }
4539 
4540  case 0x10: // Road Type flags
4541  rti->flags = (RoadTypeFlags)buf->ReadByte();
4542  break;
4543 
4544  case 0x13: // Construction cost factor
4545  rti->cost_multiplier = buf->ReadWord();
4546  break;
4547 
4548  case 0x14: // Speed limit
4549  rti->max_speed = buf->ReadWord();
4550  break;
4551 
4552  case 0x16: // Map colour
4553  rti->map_colour = buf->ReadByte();
4554  break;
4555 
4556  case 0x17: // Introduction date
4557  rti->introduction_date = buf->ReadDWord();
4558  break;
4559 
4560  case 0x1A: // Sort order
4561  rti->sorting_order = buf->ReadByte();
4562  break;
4563 
4564  case 0x1B: // Name of roadtype
4565  AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4566  break;
4567 
4568  case 0x1C: // Maintenance cost factor
4569  rti->maintenance_multiplier = buf->ReadWord();
4570  break;
4571 
4572  case 0x1D: // Alternate road type label list
4573  /* Skipped here as this is loaded during reservation stage. */
4574  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4575  break;
4576 
4577  default:
4578  ret = CIR_UNKNOWN;
4579  break;
4580  }
4581  }
4582 
4583  return ret;
4584 }
4585 
4586 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4587 {
4588  return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4589 }
4590 
4591 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4592 {
4593  return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4594 }
4595 
4596 
4597 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4598 {
4600 
4601  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4602  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4603 
4604  if (id + numinfo > ROADTYPE_END) {
4605  GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4606  return CIR_INVALID_ID;
4607  }
4608 
4609  for (int i = 0; i < numinfo; i++) {
4610  switch (prop) {
4611  case 0x08: { // Label of road type
4612  RoadTypeLabel rtl = buf->ReadDWord();
4613  rtl = BSWAP32(rtl);
4614 
4615  RoadType rt = GetRoadTypeByLabel(rtl, false);
4616  if (rt == INVALID_ROADTYPE) {
4617  /* Set up new road type */
4618  rt = AllocateRoadType(rtl, rtt);
4619  } else if (GetRoadTramType(rt) != rtt) {
4620  GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid type (road/tram), ignoring", id + numinfo);
4621  return CIR_INVALID_ID;
4622  }
4623 
4624  type_map[id + i] = rt;
4625  break;
4626  }
4627  case 0x09: // Toolbar caption of roadtype
4628  case 0x0A: // Menu text
4629  case 0x0B: // Build window caption
4630  case 0x0C: // Autoreplace text
4631  case 0x0D: // New loco
4632  case 0x13: // Construction cost
4633  case 0x14: // Speed limit
4634  case 0x1B: // Name of roadtype
4635  case 0x1C: // Maintenance cost factor
4636  buf->ReadWord();
4637  break;
4638 
4639  case 0x1D: // Alternate road type label list
4640  if (type_map[id + i] != INVALID_ROADTYPE) {
4641  int n = buf->ReadByte();
4642  for (int j = 0; j != n; j++) {
4643  _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4644  }
4645  break;
4646  }
4647  GrfMsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type {} because no label was set", id + i);
4648  /* FALL THROUGH */
4649 
4650  case 0x0F: // Powered roadtype list
4651  case 0x18: // Roadtype list required for date introduction
4652  case 0x19: // Introduced roadtype list
4653  for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4654  break;
4655 
4656  case 0x10: // Road Type flags
4657  case 0x16: // Map colour
4658  case 0x1A: // Sort order
4659  buf->ReadByte();
4660  break;
4661 
4662  case 0x17: // Introduction date
4663  buf->ReadDWord();
4664  break;
4665 
4666  default:
4667  ret = CIR_UNKNOWN;
4668  break;
4669  }
4670  }
4671 
4672  return ret;
4673 }
4674 
4675 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4676 {
4677  return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4678 }
4679 
4680 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4681 {
4682  return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4683 }
4684 
4685 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader *buf)
4686 {
4688 
4689  if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4690  GrfMsg(1, "AirportTileChangeInfo: Too many airport tiles loaded ({}), max ({}). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4691  return CIR_INVALID_ID;
4692  }
4693 
4694  /* Allocate airport tile specs if they haven't been allocated already. */
4695  if (_cur.grffile->airtspec.size() < airtid + numinfo) _cur.grffile->airtspec.resize(airtid + numinfo);
4696 
4697  for (int i = 0; i < numinfo; i++) {
4698  AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i].get();
4699 
4700  if (prop != 0x08 && tsp == nullptr) {
4701  GrfMsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile {}. Ignoring.", airtid + i);
4702  return CIR_INVALID_ID;
4703  }
4704 
4705  switch (prop) {
4706  case 0x08: { // Substitute airport tile type
4707  byte subs_id = buf->ReadByte();
4708  if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4709  /* The substitute id must be one of the original airport tiles. */
4710  GrfMsg(2, "AirportTileChangeInfo: Attempt to use new airport tile {} as substitute airport tile for {}. Ignoring.", subs_id, airtid + i);
4711  continue;
4712  }
4713 
4714  /* Allocate space for this airport tile. */
4715  if (tsp == nullptr) {
4716  _cur.grffile->airtspec[airtid + i] = std::make_unique<AirportTileSpec>(*AirportTileSpec::Get(subs_id));
4717  tsp = _cur.grffile->airtspec[airtid + i].get();
4718 
4719  tsp->enabled = true;
4720 
4722 
4723  tsp->grf_prop.local_id = airtid + i;
4724  tsp->grf_prop.subst_id = subs_id;
4725  tsp->grf_prop.grffile = _cur.grffile;
4726  _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4727  }
4728  break;
4729  }
4730 
4731  case 0x09: { // Airport tile override
4732  byte override = buf->ReadByte();
4733 
4734  /* The airport tile being overridden must be an original airport tile. */
4735  if (override >= NEW_AIRPORTTILE_OFFSET) {
4736  GrfMsg(2, "AirportTileChangeInfo: Attempt to override new airport tile {} with airport tile id {}. Ignoring.", override, airtid + i);
4737  continue;
4738  }
4739 
4740  _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4741  break;
4742  }
4743 
4744  case 0x0E: // Callback mask
4745  tsp->callback_mask = buf->ReadByte();
4746  break;
4747 
4748  case 0x0F: // Animation information
4749  tsp->animation.frames = buf->ReadByte();
4750  tsp->animation.status = buf->ReadByte();
4751  break;
4752 
4753  case 0x10: // Animation speed
4754  tsp->animation.speed = buf->ReadByte();
4755  break;
4756 
4757  case 0x11: // Animation triggers
4758  tsp->animation.triggers = buf->ReadByte();
4759  break;
4760 
4761  default:
4762  ret = CIR_UNKNOWN;
4763  break;
4764  }
4765  }
4766 
4767  return ret;
4768 }
4769 
4777 {
4779 
4780  switch (prop) {
4781  case 0x09:
4782  case 0x0C:
4783  case 0x0F:
4784  case 0x11:
4785  buf->ReadByte();
4786  break;
4787 
4788  case 0x0A:
4789  case 0x0B:
4790  case 0x0E:
4791  case 0x10:
4792  case 0x15:
4793  buf->ReadWord();
4794  break;
4795 
4796  case 0x08:
4797  case 0x0D:
4798  case 0x12:
4799  buf->ReadDWord();
4800  break;
4801 
4802  default:
4803  ret = CIR_UNKNOWN;
4804  break;
4805  }
4806 
4807  return ret;
4808 }
4809 
4810 static ChangeInfoResult RoadStopChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4811 {
4813 
4814  if (id + numinfo > NUM_ROADSTOPS_PER_GRF) {
4815  GrfMsg(1, "RoadStopChangeInfo: RoadStop {} is invalid, max {}, ignoring", id + numinfo, NUM_ROADSTOPS_PER_GRF);
4816  return CIR_INVALID_ID;
4817  }
4818 
4819  if (_cur.grffile->roadstops.size() < id + numinfo) _cur.grffile->roadstops.resize(id + numinfo);
4820 
4821  for (int i = 0; i < numinfo; i++) {
4822  RoadStopSpec *rs = _cur.grffile->roadstops[id + i].get();
4823 
4824  if (rs == nullptr && prop != 0x08) {
4825  GrfMsg(1, "RoadStopChangeInfo: Attempt to modify undefined road stop {}, ignoring", id + i);
4826  ChangeInfoResult cir = IgnoreRoadStopProperty(prop, buf);
4827  if (cir > ret) ret = cir;
4828  continue;
4829  }
4830 
4831  switch (prop) {
4832  case 0x08: { // Road Stop Class ID
4833  if (rs == nullptr) {
4834  _cur.grffile->roadstops[id + i] = std::make_unique<RoadStopSpec>();
4835  rs = _cur.grffile->roadstops[id + i].get();
4836  }
4837 
4838  uint32_t classid = buf->ReadDWord();
4839  rs->cls_id = RoadStopClass::Allocate(BSWAP32(classid));
4840  rs->spec_id = id + i;
4841  break;
4842  }
4843 
4844  case 0x09: // Road stop type
4845  rs->stop_type = (RoadStopAvailabilityType)buf->ReadByte();
4846  break;
4847 
4848  case 0x0A: // Road Stop Name
4849  AddStringForMapping(buf->ReadWord(), &rs->name);
4850  break;
4851 
4852  case 0x0B: // Road Stop Class name
4853  AddStringForMapping(buf->ReadWord(), &RoadStopClass::Get(rs->cls_id)->name);
4854  break;
4855 
4856  case 0x0C: // The draw mode
4857  rs->draw_mode = (RoadStopDrawMode)buf->ReadByte();
4858  break;
4859 
4860  case 0x0D: // Cargo types for random triggers
4861  rs->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
4862  break;
4863 
4864  case 0x0E: // Animation info
4865  rs->animation.frames = buf->ReadByte();
4866  rs->animation.status = buf->ReadByte();
4867  break;
4868 
4869  case 0x0F: // Animation speed
4870  rs->animation.speed = buf->ReadByte();
4871  break;
4872 
4873  case 0x10: // Animation triggers
4874  rs->animation.triggers = buf->ReadWord();
4875  break;
4876 
4877  case 0x11: // Callback mask
4878  rs->callback_mask = buf->ReadByte();
4879  break;
4880 
4881  case 0x12: // General flags
4882  rs->flags = (uint8_t)buf->ReadDWord(); // Future-proofing, size this as 4 bytes, but we only need one byte's worth of flags at present
4883  break;
4884 
4885  case 0x15: // Cost multipliers
4886  rs->build_cost_multiplier = buf->ReadByte();
4887  rs->clear_cost_multiplier = buf->ReadByte();
4888  break;
4889 
4890  default:
4891  ret = CIR_UNKNOWN;
4892  break;
4893  }
4894  }
4895 
4896  return ret;
4897 }
4898 
4899 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8_t feature, uint8_t property)
4900 {
4901  switch (cir) {
4902  default: NOT_REACHED();
4903 
4904  case CIR_DISABLED:
4905  /* Error has already been printed; just stop parsing */
4906  return true;
4907 
4908  case CIR_SUCCESS:
4909  return false;
4910 
4911  case CIR_UNHANDLED:
4912  GrfMsg(1, "{}: Ignoring property 0x{:02X} of feature 0x{:02X} (not implemented)", caller, property, feature);
4913  return false;
4914 
4915  case CIR_UNKNOWN:
4916  GrfMsg(0, "{}: Unknown property 0x{:02X} of feature 0x{:02X}, disabling", caller, property, feature);
4917  [[fallthrough]];
4918 
4919  case CIR_INVALID_ID: {
4920  /* No debug message for an invalid ID, as it has already been output */
4921  GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4922  if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4923  return true;
4924  }
4925  }
4926 }
4927 
4928 /* Action 0x00 */
4929 static void FeatureChangeInfo(ByteReader *buf)
4930 {
4931  /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4932  *
4933  * B feature
4934  * B num-props how many properties to change per vehicle/station
4935  * B num-info how many vehicles/stations to change
4936  * E id ID of first vehicle/station to change, if num-info is
4937  * greater than one, this one and the following
4938  * vehicles/stations will be changed
4939  * B property what property to change, depends on the feature
4940  * V new-info new bytes of info (variable size; depends on properties) */
4941 
4942  static const VCI_Handler handler[] = {
4943  /* GSF_TRAINS */ RailVehicleChangeInfo,
4944  /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4945  /* GSF_SHIPS */ ShipVehicleChangeInfo,
4946  /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4947  /* GSF_STATIONS */ StationChangeInfo,
4948  /* GSF_CANALS */ CanalChangeInfo,
4949  /* GSF_BRIDGES */ BridgeChangeInfo,
4950  /* GSF_HOUSES */ TownHouseChangeInfo,
4951  /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4952  /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4953  /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4954  /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4955  /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4956  /* GSF_AIRPORTS */ AirportChangeInfo,
4957  /* GSF_SIGNALS */ nullptr,
4958  /* GSF_OBJECTS */ ObjectChangeInfo,
4959  /* GSF_RAILTYPES */ RailTypeChangeInfo,
4960  /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4961  /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4962  /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4963  /* GSF_ROADSTOPS */ RoadStopChangeInfo,
4964  };
4965  static_assert(GSF_END == lengthof(handler));
4966 
4967  uint8_t feature = buf->ReadByte();
4968  uint8_t numprops = buf->ReadByte();
4969  uint numinfo = buf->ReadByte();
4970  uint engine = buf->ReadExtendedByte();
4971 
4972  if (feature >= GSF_END) {
4973  GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4974  return;
4975  }
4976 
4977  GrfMsg(6, "FeatureChangeInfo: Feature 0x{:02X}, {} properties, to apply to {}+{}",
4978  feature, numprops, engine, numinfo);
4979 
4980  if (handler[feature] == nullptr) {
4981  if (feature != GSF_CARGOES) GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4982  return;
4983  }
4984 
4985  /* Mark the feature as used by the grf */
4986  SetBit(_cur.grffile->grf_features, feature);
4987 
4988  while (numprops-- && buf->HasData()) {
4989  uint8_t prop = buf->ReadByte();
4990 
4991  ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4992  if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4993  }
4994 }
4995 
4996 /* Action 0x00 (GLS_SAFETYSCAN) */
4997 static void SafeChangeInfo(ByteReader *buf)
4998 {
4999  uint8_t feature = buf->ReadByte();
5000  uint8_t numprops = buf->ReadByte();
5001  uint numinfo = buf->ReadByte();
5002  buf->ReadExtendedByte(); // id
5003 
5004  if (feature == GSF_BRIDGES && numprops == 1) {
5005  uint8_t prop = buf->ReadByte();
5006  /* Bridge property 0x0D is redefinition of sprite layout tables, which
5007  * is considered safe. */
5008  if (prop == 0x0D) return;
5009  } else if (feature == GSF_GLOBALVAR && numprops == 1) {
5010  uint8_t prop = buf->ReadByte();
5011  /* Engine ID Mappings are safe, if the source is static */
5012  if (prop == 0x11) {
5013  bool is_safe = true;
5014  for (uint i = 0; i < numinfo; i++) {
5015  uint32_t s = buf->ReadDWord();
5016  buf->ReadDWord(); // dest
5017  const GRFConfig *grfconfig = GetGRFConfig(s);
5018  if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
5019  is_safe = false;
5020  break;
5021  }
5022  }
5023  if (is_safe) return;
5024  }
5025  }
5026 
5027  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
5028 
5029  /* Skip remainder of GRF */
5030  _cur.skip_sprites = -1;
5031 }
5032 
5033 /* Action 0x00 (GLS_RESERVE) */
5034 static void ReserveChangeInfo(ByteReader *buf)
5035 {
5036  uint8_t feature = buf->ReadByte();
5037 
5038  if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
5039 
5040  uint8_t numprops = buf->ReadByte();
5041  uint8_t numinfo = buf->ReadByte();
5042  uint8_t index = buf->ReadExtendedByte();
5043 
5044  while (numprops-- && buf->HasData()) {
5045  uint8_t prop = buf->ReadByte();
5047 
5048  switch (feature) {
5049  default: NOT_REACHED();
5050  case GSF_CARGOES:
5051  cir = CargoChangeInfo(index, numinfo, prop, buf);
5052  break;
5053 
5054  case GSF_GLOBALVAR:
5055  cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
5056  break;
5057 
5058  case GSF_RAILTYPES:
5059  cir = RailTypeReserveInfo(index, numinfo, prop, buf);
5060  break;
5061 
5062  case GSF_ROADTYPES:
5063  cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
5064  break;
5065 
5066  case GSF_TRAMTYPES:
5067  cir = TramTypeReserveInfo(index, numinfo, prop, buf);
5068  break;
5069  }
5070 
5071  if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
5072  }
5073 }
5074 
5075 /* Action 0x01 */
5076 static void NewSpriteSet(ByteReader *buf)
5077 {
5078  /* Basic format: <01> <feature> <num-sets> <num-ent>
5079  * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
5080  *
5081  * B feature feature to define sprites for
5082  * 0, 1, 2, 3: veh-type, 4: train stations
5083  * E first-set first sprite set to define
5084  * B num-sets number of sprite sets (extended byte in extended format)
5085  * E num-ent how many entries per sprite set
5086  * For vehicles, this is the number of different
5087  * vehicle directions in each sprite set
5088  * Set num-dirs=8, unless your sprites are symmetric.
5089  * In that case, use num-dirs=4.
5090  */
5091 
5092  uint8_t feature = buf->ReadByte();
5093  uint16_t num_sets = buf->ReadByte();
5094  uint16_t first_set = 0;
5095 
5096  if (num_sets == 0 && buf->HasData(3)) {
5097  /* Extended Action1 format.
5098  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5099  first_set = buf->ReadExtendedByte();
5100  num_sets = buf->ReadExtendedByte();
5101  }
5102  uint16_t num_ents = buf->ReadExtendedByte();
5103 
5104  if (feature >= GSF_END) {
5105  _cur.skip_sprites = num_sets * num_ents;
5106  GrfMsg(1, "NewSpriteSet: Unsupported feature 0x{:02X}, skipping {} sprites", feature, _cur.skip_sprites);
5107  return;
5108  }
5109 
5110  _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
5111 
5112  GrfMsg(7, "New sprite set at {} of feature 0x{:02X}, consisting of {} sets with {} views each (total {})",
5113  _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
5114  );
5115 
5116  for (int i = 0; i < num_sets * num_ents; i++) {
5117  _cur.nfo_line++;
5118  LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
5119  }
5120 }
5121 
5122 /* Action 0x01 (SKIP) */
5123 static void SkipAct1(ByteReader *buf)
5124 {
5125  buf->ReadByte();
5126  uint16_t num_sets = buf->ReadByte();
5127 
5128  if (num_sets == 0 && buf->HasData(3)) {
5129  /* Extended Action1 format.
5130  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5131  buf->ReadExtendedByte(); // first_set
5132  num_sets = buf->ReadExtendedByte();
5133  }
5134  uint16_t num_ents = buf->ReadExtendedByte();
5135 
5136  _cur.skip_sprites = num_sets * num_ents;
5137 
5138  GrfMsg(3, "SkipAct1: Skipping {} sprites", _cur.skip_sprites);
5139 }
5140 
5141 /* Helper function to either create a callback or link to a previously
5142  * defined spritegroup. */
5143 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16_t groupid)
5144 {
5145  if (HasBit(groupid, 15)) {
5147  return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
5148  }
5149 
5150  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5151  GrfMsg(1, "GetGroupFromGroupID(0x{:02X}:0x{:02X}): Groupid 0x{:04X} does not exist, leaving empty", setid, type, groupid);
5152  return nullptr;
5153  }
5154 
5155  return _cur.spritegroups[groupid];
5156 }
5157 
5166 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16_t spriteid)
5167 {
5168  if (HasBit(spriteid, 15)) {
5170  return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
5171  }
5172 
5173  if (!_cur.IsValidSpriteSet(feature, spriteid)) {
5174  GrfMsg(1, "CreateGroupFromGroupID(0x{:02X}:0x{:02X}): Sprite set {} invalid", setid, type, spriteid);
5175  return nullptr;
5176  }
5177 
5178  SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
5179  uint num_sprites = _cur.GetNumEnts(feature, spriteid);
5180 
5181  /* Ensure that the sprites are loeded */
5182  assert(spriteset_start + num_sprites <= _cur.spriteid);
5183 
5185  return new ResultSpriteGroup(spriteset_start, num_sprites);
5186 }
5187 
5188 /* Action 0x02 */
5189 static void NewSpriteGroup(ByteReader *buf)
5190 {
5191  /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5192  *
5193  * B feature see action 1
5194  * B set-id ID of this particular definition
5195  * B type/num-entries
5196  * if 80 or greater, this is a randomized or variational
5197  * list definition, see below
5198  * otherwise it specifies a number of entries, the exact
5199  * meaning depends on the feature
5200  * V feature-specific-data (huge mess, don't even look it up --pasky) */
5201  const SpriteGroup *act_group = nullptr;
5202 
5203  uint8_t feature = buf->ReadByte();
5204  if (feature >= GSF_END) {
5205  GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5206  return;
5207  }
5208 
5209  uint8_t setid = buf->ReadByte();
5210  uint8_t type = buf->ReadByte();
5211 
5212  /* Sprite Groups are created here but they are allocated from a pool, so
5213  * we do not need to delete anything if there is an exception from the
5214  * ByteReader. */
5215 
5216  switch (type) {
5217  /* Deterministic Sprite Group */
5218  case 0x81: // Self scope, byte
5219  case 0x82: // Parent scope, byte
5220  case 0x85: // Self scope, word
5221  case 0x86: // Parent scope, word
5222  case 0x89: // Self scope, dword
5223  case 0x8A: // Parent scope, dword
5224  {
5225  byte varadjust;
5226  byte varsize;
5227 
5230  group->nfo_line = _cur.nfo_line;
5231  act_group = group;
5232  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5233 
5234  switch (GB(type, 2, 2)) {
5235  default: NOT_REACHED();
5236  case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5237  case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5238  case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5239  }
5240 
5241  /* Loop through the var adjusts. Unfortunately we don't know how many we have
5242  * from the outset, so we shall have to keep reallocing. */
5243  do {
5244  DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5245 
5246  /* The first var adjust doesn't have an operation specified, so we set it to add. */
5247  adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
5248  adjust.variable = buf->ReadByte();
5249  if (adjust.variable == 0x7E) {
5250  /* Link subroutine group */
5251  adjust.subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
5252  } else {
5253  adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf->ReadByte() : 0;
5254  }
5255 
5256  varadjust = buf->ReadByte();
5257  adjust.shift_num = GB(varadjust, 0, 5);
5258  adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5259  adjust.and_mask = buf->ReadVarSize(varsize);
5260 
5261  if (adjust.type != DSGA_TYPE_NONE) {
5262  adjust.add_val = buf->ReadVarSize(varsize);
5263  adjust.divmod_val = buf->ReadVarSize(varsize);
5264  } else {
5265  adjust.add_val = 0;
5266  adjust.divmod_val = 0;
5267  }
5268 
5269  /* Continue reading var adjusts while bit 5 is set. */
5270  } while (HasBit(varadjust, 5));
5271 
5272  std::vector<DeterministicSpriteGroupRange> ranges;
5273  ranges.resize(buf->ReadByte());
5274  for (uint i = 0; i < ranges.size(); i++) {
5275  ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5276  ranges[i].low = buf->ReadVarSize(varsize);
5277  ranges[i].high = buf->ReadVarSize(varsize);
5278  }
5279 
5280  group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5281  group->error_group = ranges.empty() ? group->default_group : ranges[0].group;
5282  /* nvar == 0 is a special case -- we turn our value into a callback result */
5283  group->calculated_result = ranges.empty();
5284 
5285  /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5286  std::vector<uint32_t> bounds;
5287  for (uint i = 0; i < ranges.size(); i++) {
5288  bounds.push_back(ranges[i].low);
5289  if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
5290  }
5291  std::sort(bounds.begin(), bounds.end());
5292  bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5293 
5294  std::vector<const SpriteGroup *> target;
5295  for (uint j = 0; j < bounds.size(); ++j) {
5296  uint32_t v = bounds[j];
5297  const SpriteGroup *t = group->default_group;
5298  for (uint i = 0; i < ranges.size(); i++) {
5299  if (ranges[i].low <= v && v <= ranges[i].high) {
5300  t = ranges[i].group;
5301  break;
5302  }
5303  }
5304  target.push_back(t);
5305  }
5306  assert(target.size() == bounds.size());
5307 
5308  for (uint j = 0; j < bounds.size(); ) {
5309  if (target[j] != group->default_group) {
5310  DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5311  r.group = target[j];
5312  r.low = bounds[j];
5313  while (j < bounds.size() && target[j] == r.group) {
5314  j++;
5315  }
5316  r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5317  } else {
5318  j++;
5319  }
5320  }
5321 
5322  break;
5323  }
5324 
5325  /* Randomized Sprite Group */
5326  case 0x80: // Self scope
5327  case 0x83: // Parent scope
5328  case 0x84: // Relative scope
5329  {
5332  group->nfo_line = _cur.nfo_line;
5333  act_group = group;
5334  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5335 
5336  if (HasBit(type, 2)) {
5337  if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5338  group->count = buf->ReadByte();
5339  }
5340 
5341  uint8_t triggers = buf->ReadByte();
5342  group->triggers = GB(triggers, 0, 7);
5343  group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5344  group->lowest_randbit = buf->ReadByte();
5345 
5346  byte num_groups = buf->ReadByte();
5347  if (!HasExactlyOneBit(num_groups)) {
5348  GrfMsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5349  }
5350 
5351  for (uint i = 0; i < num_groups; i++) {
5352  group->groups.push_back(GetGroupFromGroupID(setid, type, buf->ReadWord()));
5353  }
5354 
5355  break;
5356  }
5357 
5358  /* Neither a variable or randomized sprite group... must be a real group */
5359  default:
5360  {
5361  switch (feature) {
5362  case GSF_TRAINS:
5363  case GSF_ROADVEHICLES:
5364  case GSF_SHIPS:
5365  case GSF_AIRCRAFT:
5366  case GSF_STATIONS:
5367  case GSF_CANALS:
5368  case GSF_CARGOES:
5369  case GSF_AIRPORTS:
5370  case GSF_RAILTYPES:
5371  case GSF_ROADTYPES:
5372  case GSF_TRAMTYPES:
5373  {
5374  byte num_loaded = type;
5375  byte num_loading = buf->ReadByte();
5376 
5377  if (!_cur.HasValidSpriteSets(feature)) {
5378  GrfMsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5379  return;
5380  }
5381 
5382  GrfMsg(6, "NewSpriteGroup: New SpriteGroup 0x{:02X}, {} loaded, {} loading",
5383  setid, num_loaded, num_loading);
5384 
5385  if (num_loaded + num_loading == 0) {
5386  GrfMsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5387  break;
5388  }
5389 
5390  if (num_loaded + num_loading == 1) {
5391  /* Avoid creating 'Real' sprite group if only one option. */
5392  uint16_t spriteid = buf->ReadWord();
5393  act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5394  GrfMsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset {}", spriteid);
5395  break;
5396  }
5397 
5398  std::vector<uint16_t> loaded;
5399  std::vector<uint16_t> loading;
5400 
5401  for (uint i = 0; i < num_loaded; i++) {
5402  loaded.push_back(buf->ReadWord());
5403  GrfMsg(8, "NewSpriteGroup: + rg->loaded[{}] = subset {}", i, loaded[i]);
5404  }
5405 
5406  for (uint i = 0; i < num_loading; i++) {
5407  loading.push_back(buf->ReadWord());
5408  GrfMsg(8, "NewSpriteGroup: + rg->loading[{}] = subset {}", i, loading[i]);
5409  }
5410 
5411  if (std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end() &&
5412  std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end() &&
5413  loaded[0] == loading[0])
5414  {
5415  /* Both lists only contain the same value, so don't create 'Real' sprite group */
5416  act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5417  GrfMsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset {}", loaded[0]);
5418  break;
5419  }
5420 
5422  RealSpriteGroup *group = new RealSpriteGroup();
5423  group->nfo_line = _cur.nfo_line;
5424  act_group = group;
5425 
5426  for (uint16_t spriteid : loaded) {
5427  const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5428  group->loaded.push_back(t);
5429  }
5430 
5431  for (uint16_t spriteid : loading) {
5432  const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5433  group->loading.push_back(t);
5434  }
5435 
5436  break;
5437  }
5438 
5439  case GSF_HOUSES:
5440  case GSF_AIRPORTTILES:
5441  case GSF_OBJECTS:
5442  case GSF_INDUSTRYTILES:
5443  case GSF_ROADSTOPS: {
5444  byte num_building_sprites = std::max((uint8_t)1, type);
5445 
5448  group->nfo_line = _cur.nfo_line;
5449  act_group = group;
5450 
5451  /* On error, bail out immediately. Temporary GRF data was already freed */
5452  if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5453  break;
5454  }
5455 
5456  case GSF_INDUSTRIES: {
5457  if (type > 2) {
5458  GrfMsg(1, "NewSpriteGroup: Unsupported industry production version {}, skipping", type);
5459  break;
5460  }
5461 
5464  group->nfo_line = _cur.nfo_line;
5465  act_group = group;
5466  group->version = type;
5467  if (type == 0) {
5468  group->num_input = 3;
5469  for (uint i = 0; i < 3; i++) {
5470  group->subtract_input[i] = (int16_t)buf->ReadWord(); // signed
5471  }
5472  group->num_output = 2;
5473  for (uint i = 0; i < 2; i++) {
5474  group->add_output[i] = buf->ReadWord(); // unsigned
5475  }
5476  group->again = buf->ReadByte();
5477  } else if (type == 1) {
5478  group->num_input = 3;
5479  for (uint i = 0; i < 3; i++) {
5480  group->subtract_input[i] = buf->ReadByte();
5481  }
5482  group->num_output = 2;
5483  for (uint i = 0; i < 2; i++) {
5484  group->add_output[i] = buf->ReadByte();
5485  }
5486  group->again = buf->ReadByte();
5487  } else if (type == 2) {
5488  group->num_input = buf->ReadByte();
5489  if (group->num_input > lengthof(group->subtract_input)) {
5490  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5491  error->data = "too many inputs (max 16)";
5492  return;
5493  }
5494  for (uint i = 0; i < group->num_input; i++) {
5495  byte rawcargo = buf->ReadByte();
5496  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5497  if (!IsValidCargoID(cargo)) {
5498  /* The mapped cargo is invalid. This is permitted at this point,
5499  * as long as the result is not used. Mark it invalid so this
5500  * can be tested later. */
5501  group->version = 0xFF;
5502  } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5503  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5504  error->data = "duplicate input cargo";
5505  return;
5506  }
5507  group->cargo_input[i] = cargo;
5508  group->subtract_input[i] = buf->ReadByte();
5509  }
5510  group->num_output = buf->ReadByte();
5511  if (group->num_output > lengthof(group->add_output)) {
5512  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5513  error->data = "too many outputs (max 16)";
5514  return;
5515  }
5516  for (uint i = 0; i < group->num_output; i++) {
5517  byte rawcargo = buf->ReadByte();
5518  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5519  if (!IsValidCargoID(cargo)) {
5520  /* Mark this result as invalid to use */
5521  group->version = 0xFF;
5522  } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5523  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5524  error->data = "duplicate output cargo";
5525  return;
5526  }
5527  group->cargo_output[i] = cargo;
5528  group->add_output[i] = buf->ReadByte();
5529  }
5530  group->again = buf->ReadByte();
5531  } else {
5532  NOT_REACHED();
5533  }
5534  break;
5535  }
5536 
5537  /* Loading of Tile Layout and Production Callback groups would happen here */
5538  default: GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5539  }
5540  }
5541  }
5542 
5543  _cur.spritegroups[setid] = act_group;
5544 }
5545 
5546 static CargoID TranslateCargo(uint8_t feature, uint8_t ctype)
5547 {
5548  /* Special cargo types for purchase list and stations */
5549  if ((feature == GSF_STATIONS || feature == GSF_ROADSTOPS) && ctype == 0xFE) return SpriteGroupCargo::SG_DEFAULT_NA;
5550  if (ctype == 0xFF) return SpriteGroupCargo::SG_PURCHASE;
5551 
5552  if (_cur.grffile->cargo_list.empty()) {
5553  /* No cargo table, so use bitnum values */
5554  if (ctype >= 32) {
5555  GrfMsg(1, "TranslateCargo: Cargo bitnum {} out of range (max 31), skipping.", ctype);
5556  return INVALID_CARGO;
5557  }
5558 
5559  for (const CargoSpec *cs : CargoSpec::Iterate()) {
5560  if (cs->bitnum == ctype) {
5561  GrfMsg(6, "TranslateCargo: Cargo bitnum {} mapped to cargo type {}.", ctype, cs->Index());
5562  return cs->Index();
5563  }
5564  }
5565 
5566  GrfMsg(5, "TranslateCargo: Cargo bitnum {} not available in this climate, skipping.", ctype);
5567  return INVALID_CARGO;
5568  }
5569 
5570  /* Check if the cargo type is out of bounds of the cargo translation table */
5571  if (ctype >= _cur.grffile->cargo_list.size()) {
5572  GrfMsg(1, "TranslateCargo: Cargo type {} out of range (max {}), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5573  return INVALID_CARGO;
5574  }
5575 
5576  /* Look up the cargo label from the translation table */
5577  CargoLabel cl = _cur.grffile->cargo_list[ctype];
5578  if (cl == CT_INVALID) {
5579  GrfMsg(5, "TranslateCargo: Cargo type {} not available in this climate, skipping.", ctype);
5580  return INVALID_CARGO;
5581  }
5582 
5583  CargoID cid = GetCargoIDByLabel(cl);
5584  if (!IsValidCargoID(cid)) {
5585  GrfMsg(5, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' unsupported, skipping.", GB(cl.base(), 24, 8), GB(cl.base(), 16, 8), GB(cl.base(), 8, 8), GB(cl.base(), 0, 8));
5586  return INVALID_CARGO;
5587  }
5588 
5589  GrfMsg(6, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' mapped to cargo type {}.", GB(cl.base(), 24, 8), GB(cl.base(), 16, 8), GB(cl.base(), 8, 8), GB(cl.base(), 0, 8), cid);
5590  return cid;
5591 }
5592 
5593 
5594 static bool IsValidGroupID(uint16_t groupid, const char *function)
5595 {
5596  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5597  GrfMsg(1, "{}: Spritegroup 0x{:04X} out of range or empty, skipping.", function, groupid);
5598  return false;
5599  }
5600 
5601  return true;
5602 }
5603 
5604 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8_t idcount)
5605 {
5606  static EngineID *last_engines;
5607  static uint last_engines_count;
5608  bool wagover = false;
5609 
5610  /* Test for 'wagon override' flag */
5611  if (HasBit(idcount, 7)) {
5612  wagover = true;
5613  /* Strip off the flag */
5614  idcount = GB(idcount, 0, 7);
5615 
5616  if (last_engines_count == 0) {
5617  GrfMsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5618  return;
5619  }
5620 
5621  GrfMsg(6, "VehicleMapSpriteGroup: WagonOverride: {} engines, {} wagons",
5622  last_engines_count, idcount);
5623  } else {
5624  if (last_engines_count != idcount) {
5625  last_engines = ReallocT(last_engines, idcount);
5626  last_engines_count = idcount;
5627  }
5628  }
5629 
5630  std::vector<EngineID> engines;
5631  for (uint i = 0; i < idcount; i++) {
5632  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5633  if (e == nullptr) {
5634  /* No engine could be allocated?!? Deal with it. Okay,
5635  * this might look bad. Also make sure this NewGRF
5636  * gets disabled, as a half loaded one is bad. */
5637  HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5638  return;
5639  }
5640 
5641  engines.push_back(e->index);
5642  if (!wagover) last_engines[i] = engines[i];
5643  }
5644 
5645  uint8_t cidcount = buf->ReadByte();
5646  for (uint c = 0; c < cidcount; c++) {
5647  uint8_t ctype = buf->ReadByte();
5648  uint16_t groupid = buf->ReadWord();
5649  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5650 
5651  GrfMsg(8, "VehicleMapSpriteGroup: * [{}] Cargo type 0x{:X}, group id 0x{:02X}", c, ctype, groupid);
5652 
5653  CargoID cid = TranslateCargo(feature, ctype);
5654  if (!IsValidCargoID(cid)) continue;
5655 
5656  for (uint i = 0; i < idcount; i++) {
5657  EngineID engine = engines[i];
5658 
5659  GrfMsg(7, "VehicleMapSpriteGroup: [{}] Engine {}...", i, engine);
5660 
5661  if (wagover) {
5662  SetWagonOverrideSprites(engine, cid, _cur.spritegroups[groupid], last_engines, last_engines_count);
5663  } else {
5664  SetCustomEngineSprites(engine, cid, _cur.spritegroups[groupid]);
5665  }
5666  }
5667  }
5668 
5669  uint16_t groupid = buf->ReadWord();
5670  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5671 
5672  GrfMsg(8, "-- Default group id 0x{:04X}", groupid);
5673 
5674  for (uint i = 0; i < idcount; i++) {
5675  EngineID engine = engines[i];
5676 
5677  if (wagover) {
5678  SetWagonOverrideSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5679  } else {
5680  SetCustomEngineSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid]);
5681  SetEngineGRF(engine, _cur.grffile);
5682  }
5683  }
5684 }
5685 
5686 
5687 static void CanalMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5688 {
5689  std::vector<uint16_t> cfs;
5690  cfs.reserve(idcount);
5691  for (uint i = 0; i < idcount; i++) {
5692  cfs.push_back(buf->ReadExtendedByte());
5693  }
5694 
5695  uint8_t cidcount = buf->ReadByte();
5696  buf->Skip(cidcount * 3);
5697 
5698  uint16_t groupid = buf->ReadWord();
5699  if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5700 
5701  for (auto &cf : cfs) {
5702  if (cf >= CF_END) {
5703  GrfMsg(1, "CanalMapSpriteGroup: Canal subset {} out of range, skipping", cf);
5704  continue;
5705  }
5706 
5707  _water_feature[cf].grffile = _cur.grffile;
5708  _water_feature[cf].group = _cur.spritegroups[groupid];
5709  }
5710 }
5711 
5712 
5713 static void StationMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5714 {
5715  if (_cur.grffile->stations.empty()) {
5716  GrfMsg(1, "StationMapSpriteGroup: No stations defined, skipping");
5717  return;
5718  }
5719 
5720  std::vector<uint16_t> stations;
5721  stations.reserve(idcount);
5722  for (uint i = 0; i < idcount; i++) {
5723  stations.push_back(buf->ReadExtendedByte());
5724  }
5725 
5726  uint8_t cidcount = buf->ReadByte();
5727  for (uint c = 0; c < cidcount; c++) {
5728  uint8_t ctype = buf->ReadByte();
5729  uint16_t groupid = buf->ReadWord();
5730  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5731 
5732  ctype = TranslateCargo(GSF_STATIONS, ctype);
5733  if (!IsValidCargoID(ctype)) continue;
5734 
5735  for (auto &station : stations) {
5736  StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5737 
5738  if (statspec == nullptr) {
5739  GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5740  continue;
5741  }
5742 
5743  statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5744  }
5745  }
5746 
5747  uint16_t groupid = buf->ReadWord();
5748  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5749 
5750  for (auto &station : stations) {
5751  StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5752 
5753  if (statspec == nullptr) {
5754  GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5755  continue;
5756  }
5757 
5758  if (statspec->grf_prop.grffile != nullptr) {
5759  GrfMsg(1, "StationMapSpriteGroup: Station {} mapped multiple times, skipping", station);
5760  continue;
5761  }
5762 
5763  statspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
5764  statspec->grf_prop.grffile = _cur.grffile;
5765  statspec->grf_prop.local_id = station;
5766  StationClass::Assign(statspec);
5767  }
5768 }
5769 
5770 
5771 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5772 {
5773  if (_cur.grffile->housespec.empty()) {
5774  GrfMsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5775  return;
5776  }
5777 
5778  std::vector<uint16_t> houses;
5779  houses.reserve(idcount);
5780  for (uint i = 0; i < idcount; i++) {
5781  houses.push_back(buf->ReadExtendedByte());
5782  }
5783 
5784  /* Skip the cargo type section, we only care about the default group */
5785  uint8_t cidcount = buf->ReadByte();
5786  buf->Skip(cidcount * 3);
5787 
5788  uint16_t groupid = buf->ReadWord();
5789  if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5790 
5791  for (auto &house : houses) {
5792  HouseSpec *hs = house >= _cur.grffile->housespec.size() ? nullptr : _cur.grffile->housespec[house].get();
5793 
5794  if (hs == nullptr) {
5795  GrfMsg(1, "TownHouseMapSpriteGroup: House {} undefined, skipping.", house);
5796  continue;
5797  }
5798 
5799  hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5800  }
5801 }
5802 
5803 static void IndustryMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5804 {
5805  if (_cur.grffile->industryspec.empty()) {
5806  GrfMsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5807  return;
5808  }
5809 
5810  std::vector<uint16_t> industries;
5811  industries.reserve(idcount);
5812  for (uint i = 0; i < idcount; i++) {
5813  industries.push_back(buf->ReadExtendedByte());
5814  }
5815 
5816  /* Skip the cargo type section, we only care about the default group */
5817  uint8_t cidcount = buf->ReadByte();
5818  buf->Skip(cidcount * 3);
5819 
5820  uint16_t groupid = buf->ReadWord();
5821  if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5822 
5823  for (auto &industry : industries) {
5824  IndustrySpec *indsp = industry >= _cur.grffile->industryspec.size() ? nullptr : _cur.grffile->industryspec[industry].get();
5825 
5826  if (indsp == nullptr) {
5827  GrfMsg(1, "IndustryMapSpriteGroup: Industry {} undefined, skipping", industry);
5828  continue;
5829  }
5830 
5831  indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5832  }
5833 }
5834 
5835 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5836 {
5837  if (_cur.grffile->indtspec.empty()) {
5838  GrfMsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5839  return;
5840  }
5841 
5842  std::vector<uint16_t> indtiles;
5843  indtiles.reserve(idcount);
5844  for (uint i = 0; i < idcount; i++) {
5845  indtiles.push_back(buf->ReadExtendedByte());
5846  }
5847 
5848  /* Skip the cargo type section, we only care about the default group */
5849  uint8_t cidcount = buf->ReadByte();
5850  buf->Skip(cidcount * 3);
5851 
5852  uint16_t groupid = buf->ReadWord();
5853  if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5854 
5855  for (auto &indtile : indtiles) {
5856  IndustryTileSpec *indtsp = indtile >= _cur.grffile->indtspec.size() ? nullptr : _cur.grffile->indtspec[indtile].get();
5857 
5858  if (indtsp == nullptr) {
5859  GrfMsg(1, "IndustrytileMapSpriteGroup: Industry tile {} undefined, skipping", indtile);
5860  continue;
5861  }
5862 
5863  indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5864  }
5865 }
5866 
5867 static void CargoMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5868 {
5869  std::vector<uint16_t> cargoes;
5870  cargoes.reserve(idcount);
5871  for (uint i = 0; i < idcount; i++) {
5872  cargoes.push_back(buf->ReadExtendedByte());
5873  }
5874 
5875  /* Skip the cargo type section, we only care about the default group */
5876  uint8_t cidcount = buf->ReadByte();
5877  buf->Skip(cidcount * 3);
5878 
5879  uint16_t groupid = buf->ReadWord();
5880  if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5881 
5882  for (auto &cid : cargoes) {
5883  if (cid >= NUM_CARGO) {
5884  GrfMsg(1, "CargoMapSpriteGroup: Cargo ID {} out of range, skipping", cid);
5885  continue;
5886  }
5887 
5888  CargoSpec *cs = CargoSpec::Get(cid);
5889  cs->grffile = _cur.grffile;
5890  cs->group = _cur.spritegroups[groupid];
5891  }
5892 }
5893 
5894 static void ObjectMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5895 {
5896  if (_cur.grffile->objectspec.empty()) {
5897  GrfMsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5898  return;
5899  }
5900 
5901  std::vector<uint16_t> objects;
5902  objects.reserve(idcount);
5903  for (uint i = 0; i < idcount; i++) {
5904  objects.push_back(buf->ReadExtendedByte());
5905  }
5906 
5907  uint8_t cidcount = buf->ReadByte();
5908  for (uint c = 0; c < cidcount; c++) {
5909  uint8_t ctype = buf->ReadByte();
5910  uint16_t groupid = buf->ReadWord();
5911  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5912 
5913  /* The only valid option here is purchase list sprite groups. */
5914  if (ctype != 0xFF) {
5915  GrfMsg(1, "ObjectMapSpriteGroup: Invalid cargo bitnum {} for objects, skipping.", ctype);
5916  continue;
5917  }
5918 
5919  for (auto &object : objects) {
5920  ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5921 
5922  if (spec == nullptr) {
5923  GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5924  continue;
5925  }
5926 
5927  spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_PURCHASE] = _cur.spritegroups[groupid];
5928  }
5929  }
5930 
5931  uint16_t groupid = buf->ReadWord();
5932  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5933 
5934  for (auto &object : objects) {
5935  ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5936 
5937  if (spec == nullptr) {
5938  GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5939  continue;
5940  }
5941 
5942  if (spec->grf_prop.grffile != nullptr) {
5943  GrfMsg(1, "ObjectMapSpriteGroup: Object {} mapped multiple times, skipping", object);
5944  continue;
5945  }
5946 
5947  spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_DEFAULT] = _cur.spritegroups[groupid];
5948  spec->grf_prop.grffile = _cur.grffile;
5949  spec->grf_prop.local_id = object;
5950  }
5951 }
5952 
5953 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8_t idcount)
5954 {
5955  std::vector<uint8_t> railtypes;
5956  railtypes.reserve(idcount);
5957  for (uint i = 0; i < idcount; i++) {
5958  uint16_t id = buf->ReadExtendedByte();
5959  railtypes.push_back(id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE);
5960  }
5961 
5962  uint8_t cidcount = buf->ReadByte();
5963  for (uint c = 0; c < cidcount; c++) {
5964  uint8_t ctype = buf->ReadByte();
5965  uint16_t groupid = buf->ReadWord();
5966  if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5967 
5968  if (ctype >= RTSG_END) continue;
5969 
5970  extern RailTypeInfo _railtypes[RAILTYPE_END];
5971  for (auto &railtype : railtypes) {
5972  if (railtype != INVALID_RAILTYPE) {
5973  RailTypeInfo *rti = &_railtypes[railtype];
5974 
5975  rti->grffile[ctype] = _cur.grffile;
5976  rti->group[ctype] = _cur.spritegroups[groupid];
5977  }
5978  }
5979  }
5980 
5981  /* Railtypes do not use the default group. */
5982  buf->ReadWord();
5983 }
5984 
5985 static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8_t idcount, RoadTramType rtt)
5986 {
5987  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5988 
5989  std::vector<uint8_t> roadtypes;
5990  roadtypes.reserve(idcount);
5991  for (uint i = 0; i < idcount; i++) {
5992  uint16_t id = buf->ReadExtendedByte();
5993  roadtypes.push_back(id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE);
5994  }
5995 
5996  uint8_t cidcount = buf->ReadByte();
5997  for (uint c = 0; c < cidcount; c++) {
5998  uint8_t ctype = buf->ReadByte();
5999  uint16_t groupid = buf->ReadWord();
6000  if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
6001 
6002  if (ctype >= ROTSG_END) continue;
6003 
6004  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
6005  for (auto &roadtype : roadtypes) {
6006  if (roadtype != INVALID_ROADTYPE) {
6007  RoadTypeInfo *rti = &_roadtypes[roadtype];
6008 
6009  rti->grffile[ctype] = _cur.grffile;
6010  rti->group[ctype] = _cur.spritegroups[groupid];
6011  }
6012  }
6013  }
6014 
6015  /* Roadtypes do not use the default group. */
6016  buf->ReadWord();
6017 }
6018 
6019 static void AirportMapSpriteGroup(ByteReader *buf, uint8_t idcount)
6020 {
6021  if (_cur.grffile->airportspec.empty()) {
6022  GrfMsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
6023  return;
6024  }
6025 
6026  std::vector<uint16_t> airports;
6027  airports.reserve(idcount);
6028  for (uint i = 0; i < idcount; i++) {
6029  airports.push_back(buf->ReadExtendedByte());
6030  }
6031 
6032  /* Skip the cargo type section, we only care about the default group */
6033  uint8_t cidcount = buf->ReadByte();
6034  buf->Skip(cidcount * 3);
6035 
6036  uint16_t groupid = buf->ReadWord();
6037  if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
6038 
6039  for (auto &airport : airports) {
6040  AirportSpec *as = airport >= _cur.grffile->airportspec.size() ? nullptr : _cur.grffile->airportspec[airport].get();
6041 
6042  if (as == nullptr) {
6043  GrfMsg(1, "AirportMapSpriteGroup: Airport {} undefined, skipping", airport);
6044  continue;
6045  }
6046 
6047  as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6048  }
6049 }
6050 
6051 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8_t idcount)
6052 {
6053  if (_cur.grffile->airtspec.empty()) {
6054  GrfMsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
6055  return;
6056  }
6057 
6058  std::vector<uint16_t> airptiles;
6059  airptiles.reserve(idcount);
6060  for (uint i = 0; i < idcount; i++) {
6061  airptiles.push_back(buf->ReadExtendedByte());
6062  }
6063 
6064  /* Skip the cargo type section, we only care about the default group */
6065  uint8_t cidcount = buf->ReadByte();
6066  buf->Skip(cidcount * 3);
6067 
6068  uint16_t groupid = buf->ReadWord();
6069  if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
6070 
6071  for (auto &airptile : airptiles) {
6072  AirportTileSpec *airtsp = airptile >= _cur.grffile->airtspec.size() ? nullptr : _cur.grffile->airtspec[airptile].get();
6073 
6074  if (airtsp == nullptr) {
6075  GrfMsg(1, "AirportTileMapSpriteGroup: Airport tile {} undefined, skipping", airptile);
6076  continue;
6077  }
6078 
6079  airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6080  }
6081 }
6082 
6083 static void RoadStopMapSpriteGroup(ByteReader *buf, uint8_t idcount)
6084 {
6085  if (_cur.grffile->roadstops.empty()) {
6086  GrfMsg(1, "RoadStopMapSpriteGroup: No roadstops defined, skipping");
6087  return;
6088  }
6089 
6090  std::vector<uint16_t> roadstops;
6091  roadstops.reserve(idcount);
6092  for (uint i = 0; i < idcount; i++) {
6093  roadstops.push_back(buf->ReadExtendedByte());
6094  }
6095 
6096  uint8_t cidcount = buf->ReadByte();
6097  for (uint c = 0; c < cidcount; c++) {
6098  uint8_t ctype = buf->ReadByte();
6099  uint16_t groupid = buf->ReadWord();
6100  if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) continue;
6101 
6102  ctype = TranslateCargo(GSF_ROADSTOPS, ctype);
6103  if (!IsValidCargoID(ctype)) continue;
6104 
6105  for (auto &roadstop : roadstops) {
6106  RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6107 
6108  if (roadstopspec == nullptr) {
6109  GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping", roadstop);
6110  continue;
6111  }
6112 
6113  roadstopspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
6114  }
6115  }
6116 
6117  uint16_t groupid = buf->ReadWord();
6118  if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) return;
6119 
6120  for (auto &roadstop : roadstops) {
6121  RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6122 
6123  if (roadstopspec == nullptr) {
6124  GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping.", roadstop);
6125  continue;
6126  }
6127 
6128  if (roadstopspec->grf_prop.grffile != nullptr) {
6129  GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} mapped multiple times, skipping", roadstop);
6130  continue;
6131  }
6132 
6133  roadstopspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
6134  roadstopspec->grf_prop.grffile = _cur.grffile;
6135  roadstopspec->grf_prop.local_id = roadstop;
6136  RoadStopClass::Assign(roadstopspec);
6137  }
6138 }
6139 
6140 /* Action 0x03 */
6141 static void FeatureMapSpriteGroup(ByteReader *buf)
6142 {
6143  /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
6144  * id-list := [<id>] [id-list]
6145  * cargo-list := <cargo-type> <cid> [cargo-list]
6146  *
6147  * B feature see action 0
6148  * B n-id bits 0-6: how many IDs this definition applies to
6149  * bit 7: if set, this is a wagon override definition (see below)
6150  * E ids the IDs for which this definition applies
6151  * B num-cid number of cargo IDs (sprite group IDs) in this definition
6152  * can be zero, in that case the def-cid is used always
6153  * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
6154  * W cid cargo ID (sprite group ID) for this type of cargo
6155  * W def-cid default cargo ID (sprite group ID) */
6156 
6157  uint8_t feature = buf->ReadByte();
6158  uint8_t idcount = buf->ReadByte();
6159 
6160  if (feature >= GSF_END) {
6161  GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6162  return;
6163  }
6164 
6165  /* If idcount is zero, this is a feature callback */
6166  if (idcount == 0) {
6167  /* Skip number of cargo ids? */
6168  buf->ReadByte();
6169  uint16_t groupid = buf->ReadWord();
6170  if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
6171 
6172  GrfMsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x{:02X}", feature);
6173 
6174  AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
6175  return;
6176  }
6177 
6178  /* Mark the feature as used by the grf (generic callbacks do not count) */
6179  SetBit(_cur.grffile->grf_features, feature);
6180 
6181  GrfMsg(6, "FeatureMapSpriteGroup: Feature 0x{:02X}, {} ids", feature, idcount);
6182 
6183  switch (feature) {
6184  case GSF_TRAINS:
6185  case GSF_ROADVEHICLES:
6186  case GSF_SHIPS:
6187  case GSF_AIRCRAFT:
6188  VehicleMapSpriteGroup(buf, feature, idcount);
6189  return;
6190 
6191  case GSF_CANALS:
6192  CanalMapSpriteGroup(buf, idcount);
6193  return;
6194 
6195  case GSF_STATIONS:
6196  StationMapSpriteGroup(buf, idcount);
6197  return;
6198 
6199  case GSF_HOUSES:
6200  TownHouseMapSpriteGroup(buf, idcount);
6201  return;
6202 
6203  case GSF_INDUSTRIES:
6204  IndustryMapSpriteGroup(buf, idcount);
6205  return;
6206 
6207  case GSF_INDUSTRYTILES:
6208  IndustrytileMapSpriteGroup(buf, idcount);
6209  return;
6210 
6211  case GSF_CARGOES:
6212  CargoMapSpriteGroup(buf, idcount);
6213  return;
6214 
6215  case GSF_AIRPORTS:
6216  AirportMapSpriteGroup(buf, idcount);
6217  return;
6218 
6219  case GSF_OBJECTS:
6220  ObjectMapSpriteGroup(buf, idcount);
6221  break;
6222 
6223  case GSF_RAILTYPES:
6224  RailTypeMapSpriteGroup(buf, idcount);
6225  break;
6226 
6227  case GSF_ROADTYPES:
6228  RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
6229  break;
6230 
6231  case GSF_TRAMTYPES:
6232  RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
6233  break;
6234 
6235  case GSF_AIRPORTTILES:
6236  AirportTileMapSpriteGroup(buf, idcount);
6237  return;
6238 
6239  case GSF_ROADSTOPS:
6240  RoadStopMapSpriteGroup(buf, idcount);
6241  return;
6242 
6243  default:
6244  GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6245  return;
6246  }
6247 }
6248 
6249 /* Action 0x04 */
6250 static void FeatureNewName(ByteReader *buf)
6251 {
6252  /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
6253  *
6254  * B veh-type see action 0 (as 00..07, + 0A
6255  * But IF veh-type = 48, then generic text
6256  * B language-id If bit 6 is set, This is the extended language scheme,
6257  * with up to 64 language.
6258  * Otherwise, it is a mapping where set bits have meaning
6259  * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6260  * Bit 7 set means this is a generic text, not a vehicle one (or else)
6261  * B num-veh number of vehicles which are getting a new name
6262  * B/W offset number of the first vehicle that gets a new name
6263  * Byte : ID of vehicle to change
6264  * Word : ID of string to change/add
6265  * S data new texts, each of them zero-terminated, after
6266  * which the next name begins. */
6267 
6268  bool new_scheme = _cur.grffile->grf_version >= 7;
6269 
6270  uint8_t feature = buf->ReadByte();
6271  if (feature >= GSF_END && feature != 0x48) {
6272  GrfMsg(1, "FeatureNewName: Unsupported feature 0x{:02X}, skipping", feature);
6273  return;
6274  }
6275 
6276  uint8_t lang = buf->ReadByte();
6277  uint8_t num = buf->ReadByte();
6278  bool generic = HasBit(lang, 7);
6279  uint16_t id;
6280  if (generic) {
6281  id = buf->ReadWord();
6282  } else if (feature <= GSF_AIRCRAFT) {
6283  id = buf->ReadExtendedByte();
6284  } else {
6285  id = buf->ReadByte();
6286  }
6287 
6288  ClrBit(lang, 7);
6289 
6290  uint16_t endid = id + num;
6291 
6292  GrfMsg(6, "FeatureNewName: About to rename engines {}..{} (feature 0x{:02X}) in language 0x{:02X}",
6293  id, endid, feature, lang);
6294 
6295  for (; id < endid && buf->HasData(); id++) {
6296  const char *name = buf->ReadString();
6297  GrfMsg(8, "FeatureNewName: 0x{:04X} <- {}", id, name);
6298 
6299  switch (feature) {
6300  case GSF_TRAINS:
6301  case GSF_ROADVEHICLES:
6302  case GSF_SHIPS:
6303  case GSF_AIRCRAFT:
6304  if (!generic) {
6305  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6306  if (e == nullptr) break;
6307  StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6308  e->info.string_id = string;
6309  } else {
6310  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6311  }
6312  break;
6313 
6314  default:
6315  if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0x10000)) {
6316  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6317  break;
6318  }
6319 
6320  switch (GB(id, 8, 8)) {
6321  case 0xC4: // Station class name
6322  if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6323  GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6324  } else {
6325  StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
6326  StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6327  }
6328  break;
6329 
6330  case 0xC5: // Station name
6331  if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6332  GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6333  } else {
6334  _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6335  }
6336  break;
6337 
6338  case 0xC7: // Airporttile name
6339  if (GB(id, 0, 8) >= _cur.grffile->airtspec.size() || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6340  GrfMsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x{:X}, ignoring", GB(id, 0, 8));
6341  } else {
6342  _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6343  }
6344  break;
6345 
6346  case 0xC9: // House name
6347  if (GB(id, 0, 8) >= _cur.grffile->housespec.size() || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6348  GrfMsg(1, "FeatureNewName: Attempt to name undefined house 0x{:X}, ignoring.", GB(id, 0, 8));
6349  } else {
6350  _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6351  }
6352  break;
6353 
6354  default:
6355  GrfMsg(7, "FeatureNewName: Unsupported ID (0x{:04X})", id);
6356  break;
6357  }
6358  break;
6359  }
6360  }
6361 }
6362 
6371 static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const char *name)
6372 {
6373 
6374  if (offset >= max_sprites) {
6375  GrfMsg(1, "GraphicsNew: {} sprite offset must be less than {}, skipping", name, max_sprites);
6376  uint orig_num = num;
6377  num = 0;
6378  return orig_num;
6379  }
6380 
6381  if (offset + num > max_sprites) {
6382  GrfMsg(4, "GraphicsNew: {} sprite overflow, truncating...", name);
6383  uint orig_num = num;
6384  num = std::max(max_sprites - offset, 0);
6385  return orig_num - num;
6386  }
6387 
6388  return 0;
6389 }
6390 
6391 
6397 };
6399 struct Action5Type {
6402  uint16_t min_sprites;
6403  uint16_t max_sprites;
6404  const char *name;
6405 };
6406 
6408 static const Action5Type _action5_types[] = {
6409  /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6410  /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6411  /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6412  /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6413  /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6414  /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6415  /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6416  /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6417  /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6418  /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6419  /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6420  /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6421  /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6422  /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6423  /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6424  /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6425  /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6426  /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6427  /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6428  /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6429  /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6430  /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6431  /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6432  /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6433  /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6434  /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6435 };
6436 
6437 /* Action 0x05 */
6438 static void GraphicsNew(ByteReader *buf)
6439 {
6440  /* <05> <graphics-type> <num-sprites> <other data...>
6441  *
6442  * B graphics-type What set of graphics the sprites define.
6443  * E num-sprites How many sprites are in this set?
6444  * V other data Graphics type specific data. Currently unused. */
6445 
6446  uint8_t type = buf->ReadByte();
6447  uint16_t num = buf->ReadExtendedByte();
6448  uint16_t offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
6449  ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6450 
6451  if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6452  /* Special not-TTDP-compatible case used in openttd.grf
6453  * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6454  GrfMsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6455  LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6456  LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6457  LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6458  LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6459  LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6460  LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6461  LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6462  LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6463  LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6464  LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6466  return;
6467  }
6468 
6469  /* Supported type? */
6470  if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6471  GrfMsg(2, "GraphicsNew: Custom graphics (type 0x{:02X}) sprite block of length {} (unimplemented, ignoring)", type, num);
6472  _cur.skip_sprites = num;
6473  return;
6474  }
6475 
6476  const Action5Type *action5_type = &_action5_types[type];
6477 
6478  /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6479  * except for the long version of the shore type:
6480  * Ignore offset if not allowed */
6481  if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6482  GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6483  offset = 0;
6484  }
6485 
6486  /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6487  * This does not make sense, if <offset> is allowed */
6488  if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6489  GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) count must be at least {}. Only {} were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num);
6490  _cur.skip_sprites = num;
6491  return;
6492  }
6493 
6494  /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6495  uint16_t skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6496  SpriteID replace = action5_type->sprite_base + offset;
6497 
6498  /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6499  GrfMsg(2, "GraphicsNew: Replacing sprites {} to {} of {} (type 0x{:02X}) at SpriteID 0x{:04X}", offset, offset + num - 1, action5_type->name, type, replace);
6500 
6502 
6503  if (type == 0x0B) {
6504  static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6505  static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6506  if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6507  if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6508  }
6509 
6510  /* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */
6511  bool dup_oneway_sprites = ((type == 0x09) && (offset + num <= SPR_ONEWAY_SLOPE_N_OFFSET));
6512 
6513  for (; num > 0; num--) {
6514  _cur.nfo_line++;
6515  int load_index = (replace == 0 ? _cur.spriteid++ : replace++);
6516  LoadNextSprite(load_index, *_cur.file, _cur.nfo_line);
6517  if (dup_oneway_sprites) {
6518  DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_N_OFFSET);
6519  DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_S_OFFSET);
6520  }
6521  }
6522 
6523  _cur.skip_sprites = skip_num;
6524 }
6525 
6526 /* Action 0x05 (SKIP) */
6527 static void SkipAct5(ByteReader *buf)
6528 {
6529  /* Ignore type byte */
6530  buf->ReadByte();
6531 
6532  /* Skip the sprites of this action */
6533  _cur.skip_sprites = buf->ReadExtendedByte();
6534 
6535  GrfMsg(3, "SkipAct5: Skipping {} sprites", _cur.skip_sprites);
6536 }
6537 
6549 bool GetGlobalVariable(byte param, uint32_t *value, const GRFFile *grffile)
6550 {
6551  switch (param) {
6552  case 0x00: // current date
6553  *value = std::max(TimerGameCalendar::date - CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR, TimerGameCalendar::Date(0)).base();
6554  return true;
6555 
6556  case 0x01: // current year
6558  return true;
6559 
6560  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)
6561  TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date);
6562  TimerGameCalendar::Date start_of_year = TimerGameCalendar::ConvertYMDToDate(ymd.year, 0, 1);
6563  *value = ymd.month | (ymd.day - 1) << 8 | (TimerGameCalendar::IsLeapYear(ymd.year) ? 1 << 15 : 0) | (TimerGameCalendar::date - start_of_year).base() << 16;
6564  return true;
6565  }
6566 
6567  case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6569  return true;
6570 
6571  case 0x06: // road traffic side, bit 4 clear=left, set=right
6572  *value = _settings_game.vehicle.road_side << 4;
6573  return true;
6574 
6575  case 0x09: // date fraction
6576  *value = TimerGameCalendar::date_fract * 885;
6577  return true;
6578 
6579  case 0x0A: // animation counter
6580  *value = GB(TimerGameTick::counter, 0, 16);
6581  return true;
6582 
6583  case 0x0B: { // TTDPatch version
6584  uint major = 2;
6585  uint minor = 6;
6586  uint revision = 1; // special case: 2.0.1 is 2.0.10
6587  uint build = 1382;
6588  *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6589  return true;
6590  }
6591 
6592  case 0x0D: // TTD Version, 00=DOS, 01=Windows
6593  *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6594  return true;
6595 
6596  case 0x0E: // Y-offset for train sprites
6597  *value = _cur.grffile->traininfo_vehicle_pitch;
6598  return true;
6599 
6600  case 0x0F: // Rail track type cost factors
6601  *value = 0;
6602  SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6604  /* skip elrail multiplier - disabled */
6605  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6606  } else {
6607  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6608  /* Skip monorail multiplier - no space in result */
6609  }
6610  SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6611  return true;
6612 
6613  case 0x11: // current rail tool type
6614  *value = 0; // constant fake value to avoid desync
6615  return true;
6616 
6617  case 0x12: // Game mode
6618  *value = _game_mode;
6619  return true;
6620 
6621  /* case 0x13: // Tile refresh offset to left not implemented */
6622  /* case 0x14: // Tile refresh offset to right not implemented */
6623  /* case 0x15: // Tile refresh offset upwards not implemented */
6624  /* case 0x16: // Tile refresh offset downwards not implemented */
6625  /* case 0x17: // temperate snow line not implemented */
6626 
6627  case 0x1A: // Always -1
6628  *value = UINT_MAX;
6629  return true;
6630 
6631  case 0x1B: // Display options
6632  *value = 0x3F; // constant fake value to avoid desync
6633  return true;
6634 
6635  case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6636  *value = 1;
6637  return true;
6638 
6639  case 0x1E: // Miscellaneous GRF features
6640  *value = _misc_grf_features;
6641 
6642  /* Add the local flags */
6643  assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6644  if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6645  return true;
6646 
6647  /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6648 
6649  case 0x20: { // snow line height
6650  byte snowline = GetSnowLine();
6652  *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6653  } else {
6654  /* No snow */
6655  *value = 0xFF;
6656  }
6657  return true;
6658  }
6659 
6660  case 0x21: // OpenTTD version
6661  *value = _openttd_newgrf_version;
6662  return true;
6663 
6664  case 0x22: // difficulty level
6665  *value = SP_CUSTOM;
6666  return true;
6667 
6668  case 0x23: // long format date
6669  *value = TimerGameCalendar::date.base();
6670  return true;
6671 
6672  case 0x24: // long format year
6673  *value = TimerGameCalendar::year.base();
6674  return true;
6675 
6676  default: return false;
6677  }
6678 }
6679 
6680 static uint32_t GetParamVal(byte param, uint32_t *cond_val)
6681 {
6682  /* First handle variable common with VarAction2 */
6683  uint32_t value;
6684  if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6685 
6686 
6687  /* Non-common variable */
6688  switch (param) {
6689  case 0x84: { // GRF loading stage
6690  uint32_t res = 0;
6691 
6692  if (_cur.stage > GLS_INIT) SetBit(res, 0);
6693  if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6694  if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6695  return res;
6696  }
6697 
6698  case 0x85: // TTDPatch flags, only for bit tests
6699  if (cond_val == nullptr) {
6700  /* Supported in Action 0x07 and 0x09, not 0x0D */
6701  return 0;
6702  } else {
6703  uint32_t index = *cond_val / 0x20;
6704  uint32_t param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6705  *cond_val %= 0x20;
6706  return param_val;
6707  }
6708 
6709  case 0x88: // GRF ID check
6710  return 0;
6711 
6712  /* case 0x99: Global ID offset not implemented */
6713 
6714  default:
6715  /* GRF Parameter */
6716  if (param < 0x80) return _cur.grffile->GetParam(param);
6717 
6718  /* In-game variable. */
6719  GrfMsg(1, "Unsupported in-game variable 0x{:02X}", param);
6720  return UINT_MAX;
6721  }
6722 }
6723 
6724 /* Action 0x06 */
6725 static void CfgApply(ByteReader *buf)
6726 {
6727  /* <06> <param-num> <param-size> <offset> ... <FF>
6728  *
6729  * B param-num Number of parameter to substitute (First = "zero")
6730  * Ignored if that parameter was not specified in newgrf.cfg
6731  * B param-size How many bytes to replace. If larger than 4, the
6732  * bytes of the following parameter are used. In that
6733  * case, nothing is applied unless *all* parameters
6734  * were specified.
6735  * B offset Offset into data from beginning of next sprite
6736  * to place where parameter is to be stored. */
6737 
6738  /* Preload the next sprite */
6739  SpriteFile &file = *_cur.file;
6740  size_t pos = file.GetPos();
6741  uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6742  uint8_t type = file.ReadByte();
6743 
6744  /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6745  if (type != 0xFF) {
6746  GrfMsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6747 
6748  /* Reset the file position to the start of the next sprite */
6749  file.SeekTo(pos, SEEK_SET);
6750  return;
6751  }
6752 
6753  /* Get (or create) the override for the next sprite. */
6754  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6755  std::vector<byte> &preload_sprite = _grf_line_to_action6_sprite_override[location];
6756 
6757  /* Load new sprite data if it hasn't already been loaded. */
6758  if (preload_sprite.empty()) {
6759  preload_sprite.resize(num);
6760  file.ReadBlock(preload_sprite.data(), num);
6761  }
6762 
6763  /* Reset the file position to the start of the next sprite */
6764  file.SeekTo(pos, SEEK_SET);
6765 
6766  /* Now perform the Action 0x06 on our data. */
6767  for (;;) {
6768  uint i;
6769  uint param_num;
6770  uint param_size;
6771  uint offset;
6772  bool add_value;
6773 
6774  /* Read the parameter to apply. 0xFF indicates no more data to change. */
6775  param_num = buf->ReadByte();
6776  if (param_num == 0xFF) break;
6777 
6778  /* Get the size of the parameter to use. If the size covers multiple
6779  * double words, sequential parameter values are used. */
6780  param_size = buf->ReadByte();
6781 
6782  /* Bit 7 of param_size indicates we should add to the original value
6783  * instead of replacing it. */
6784  add_value = HasBit(param_size, 7);
6785  param_size = GB(param_size, 0, 7);
6786 
6787  /* Where to apply the data to within the pseudo sprite data. */
6788  offset = buf->ReadExtendedByte();
6789 
6790  /* If the parameter is a GRF parameter (not an internal variable) check
6791  * if it (and all further sequential parameters) has been defined. */
6792  if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6793  GrfMsg(2, "CfgApply: Ignoring (param {} not set)", (param_num + (param_size - 1) / 4));
6794  break;
6795  }
6796 
6797  GrfMsg(8, "CfgApply: Applying {} bytes from parameter 0x{:02X} at offset 0x{:04X}", param_size, param_num, offset);
6798 
6799  bool carry = false;
6800  for (i = 0; i < param_size && offset + i < num; i++) {
6801  uint32_t value = GetParamVal(param_num + i / 4, nullptr);
6802  /* Reset carry flag for each iteration of the variable (only really
6803  * matters if param_size is greater than 4) */
6804  if (i % 4 == 0) carry = false;
6805 
6806  if (add_value) {
6807  uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6808  preload_sprite[offset + i] = GB(new_value, 0, 8);
6809  /* Check if the addition overflowed */
6810  carry = new_value >= 256;
6811  } else {
6812  preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6813  }
6814  }
6815  }
6816 }
6817 
6828 {
6829  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6830  error->data = _cur.grfconfig->GetName();
6831 }
6832 
6833 /* Action 0x07
6834  * Action 0x09 */
6835 static void SkipIf(ByteReader *buf)
6836 {
6837  /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6838  *
6839  * B param-num
6840  * B param-size
6841  * B condition-type
6842  * V value
6843  * B num-sprites */
6844  uint32_t cond_val = 0;
6845  uint32_t mask = 0;
6846  bool result;
6847 
6848  uint8_t param = buf->ReadByte();
6849  uint8_t paramsize = buf->ReadByte();
6850  uint8_t condtype = buf->ReadByte();
6851 
6852  if (condtype < 2) {
6853  /* Always 1 for bit tests, the given value should be ignored. */
6854  paramsize = 1;
6855  }
6856 
6857  switch (paramsize) {
6858  case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6859  case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6860  case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6861  case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6862  default: break;
6863  }
6864 
6865  if (param < 0x80 && _cur.grffile->param_end <= param) {
6866  GrfMsg(7, "SkipIf: Param {} undefined, skipping test", param);
6867  return;
6868  }
6869 
6870  GrfMsg(7, "SkipIf: Test condtype {}, param 0x{:02X}, condval 0x{:08X}", condtype, param, cond_val);
6871 
6872  /* condtypes that do not use 'param' are always valid.
6873  * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6874  */
6875  if (condtype >= 0x0B) {
6876  /* Tests that ignore 'param' */
6877  switch (condtype) {
6878  case 0x0B: result = !IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
6879  break;
6880  case 0x0C: result = IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
6881  break;
6882  case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6883  break;
6884  case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6885  break;
6886  case 0x0F: {
6887  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6888  result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6889  break;
6890  }
6891  case 0x10: {
6892  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6893  result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6894  break;
6895  }
6896  case 0x11: {
6897  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6898  result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6899  break;
6900  }
6901  case 0x12: {
6902  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6903  result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6904  break;
6905  }
6906  default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6907  }
6908  } else if (param == 0x88) {
6909  /* GRF ID checks */
6910 
6911  GRFConfig *c = GetGRFConfig(cond_val, mask);
6912 
6913  if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6915  c = nullptr;
6916  }
6917 
6918  if (condtype != 10 && c == nullptr) {
6919  GrfMsg(7, "SkipIf: GRFID 0x{:08X} unknown, skipping test", BSWAP32(cond_val));
6920  return;
6921  }
6922 
6923  switch (condtype) {
6924  /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6925  case 0x06: // Is GRFID active?
6926  result = c->status == GCS_ACTIVATED;
6927  break;
6928 
6929  case 0x07: // Is GRFID non-active?
6930  result = c->status != GCS_ACTIVATED;
6931  break;
6932 
6933  case 0x08: // GRFID is not but will be active?
6934  result = c->status == GCS_INITIALISED;
6935  break;
6936 
6937  case 0x09: // GRFID is or will be active?
6938  result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6939  break;
6940 
6941  case 0x0A: // GRFID is not nor will be active
6942  /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6943  result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6944  break;
6945 
6946  default: GrfMsg(1, "SkipIf: Unsupported GRF condition type {:02X}. Ignoring", condtype); return;
6947  }
6948  } else {
6949  /* Tests that use 'param' and are not GRF ID checks. */
6950  uint32_t param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6951  switch (condtype) {
6952  case 0x00: result = !!(param_val & (1 << cond_val));
6953  break;
6954  case 0x01: result = !(param_val & (1 << cond_val));
6955  break;
6956  case 0x02: result = (param_val & mask) == cond_val;
6957  break;
6958  case 0x03: result = (param_val & mask) != cond_val;
6959  break;
6960  case 0x04: result = (param_val & mask) < cond_val;
6961  break;
6962  case 0x05: result = (param_val & mask) > cond_val;
6963  break;
6964  default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6965  }
6966  }
6967 
6968  if (!result) {
6969  GrfMsg(2, "SkipIf: Not skipping sprites, test was false");
6970  return;
6971  }
6972 
6973  uint8_t numsprites = buf->ReadByte();
6974 
6975  /* numsprites can be a GOTO label if it has been defined in the GRF
6976  * file. The jump will always be the first matching label that follows
6977  * the current nfo_line. If no matching label is found, the first matching
6978  * label in the file is used. */
6979  const GRFLabel *choice = nullptr;
6980  for (const auto &label : _cur.grffile->labels) {
6981  if (label.label != numsprites) continue;
6982 
6983  /* Remember a goto before the current line */
6984  if (choice == nullptr) choice = &label;
6985  /* If we find a label here, this is definitely good */
6986  if (label.nfo_line > _cur.nfo_line) {
6987  choice = &label;
6988  break;
6989  }
6990  }
6991 
6992  if (choice != nullptr) {
6993  GrfMsg(2, "SkipIf: Jumping to label 0x{:X} at line {}, test was true", choice->label, choice->nfo_line);
6994  _cur.file->SeekTo(choice->pos, SEEK_SET);
6995  _cur.nfo_line = choice->nfo_line;
6996  return;
6997  }
6998 
6999  GrfMsg(2, "SkipIf: Skipping {} sprites, test was true", numsprites);
7000  _cur.skip_sprites = numsprites;
7001  if (_cur.skip_sprites == 0) {
7002  /* Zero means there are no sprites to skip, so
7003  * we use -1 to indicate that all further
7004  * sprites should be skipped. */
7005  _cur.skip_sprites = -1;
7006 
7007  /* If an action 8 hasn't been encountered yet, disable the grf. */
7008  if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
7009  DisableGrf();
7010  }
7011  }
7012 }
7013 
7014 
7015 /* Action 0x08 (GLS_FILESCAN) */
7016 static void ScanInfo(ByteReader *buf)
7017 {
7018  uint8_t grf_version = buf->ReadByte();
7019  uint32_t grfid = buf->ReadDWord();
7020  const char *name = buf->ReadString();
7021 
7022  _cur.grfconfig->ident.grfid = grfid;
7023 
7024  if (grf_version < 2 || grf_version > 8) {
7026  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);
7027  }
7028 
7029  /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
7030  if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
7031 
7032  AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
7033 
7034  if (buf->HasData()) {
7035  const char *info = buf->ReadString();
7036  AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
7037  }
7038 
7039  /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
7040  _cur.skip_sprites = -1;
7041 }
7042 
7043 /* Action 0x08 */
7044 static void GRFInfo(ByteReader *buf)
7045 {
7046  /* <08> <version> <grf-id> <name> <info>
7047  *
7048  * B version newgrf version, currently 06
7049  * 4*B grf-id globally unique ID of this .grf file
7050  * S name name of this .grf set
7051  * S info string describing the set, and e.g. author and copyright */
7052 
7053  uint8_t version = buf->ReadByte();
7054  uint32_t grfid = buf->ReadDWord();
7055  const char *name = buf->ReadString();
7056 
7057  if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
7058  DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
7059  return;
7060  }
7061 
7062  if (_cur.grffile->grfid != grfid) {
7063  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));
7064  _cur.grffile->grfid = grfid;
7065  }
7066 
7067  _cur.grffile->grf_version = version;
7068  _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
7069 
7070  /* Do swap the GRFID for displaying purposes since people expect that */
7071  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);
7072 }
7073 
7074 /* Action 0x0A */
7075 static void SpriteReplace(ByteReader *buf)
7076 {
7077  /* <0A> <num-sets> <set1> [<set2> ...]
7078  * <set>: <num-sprites> <first-sprite>
7079  *
7080  * B num-sets How many sets of sprites to replace.
7081  * Each set:
7082  * B num-sprites How many sprites are in this set
7083  * W first-sprite First sprite number to replace */
7084 
7085  uint8_t num_sets = buf->ReadByte();
7086 
7087  for (uint i = 0; i < num_sets; i++) {
7088  uint8_t num_sprites = buf->ReadByte();
7089  uint16_t first_sprite = buf->ReadWord();
7090 
7091  GrfMsg(2, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}",
7092  i, num_sprites, first_sprite
7093  );
7094 
7095  for (uint j = 0; j < num_sprites; j++) {
7096  int load_index = first_sprite + j;
7097  _cur.nfo_line++;
7098  LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
7099 
7100  /* Shore sprites now located at different addresses.
7101  * So detect when the old ones get replaced. */
7102  if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
7104  }
7105  }
7106  }
7107 }
7108 
7109 /* Action 0x0A (SKIP) */
7110 static void SkipActA(ByteReader *buf)
7111 {
7112  uint8_t num_sets = buf->ReadByte();
7113 
7114  for (uint i = 0; i < num_sets; i++) {
7115  /* Skip the sprites this replaces */
7116  _cur.skip_sprites += buf->ReadByte();
7117  /* But ignore where they go */
7118  buf->ReadWord();
7119  }
7120 
7121  GrfMsg(3, "SkipActA: Skipping {} sprites", _cur.skip_sprites);
7122 }
7123 
7124 /* Action 0x0B */
7125 static void GRFLoadError(ByteReader *buf)
7126 {
7127  /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
7128  *
7129  * B severity 00: notice, continue loading grf file
7130  * 01: warning, continue loading grf file
7131  * 02: error, but continue loading grf file, and attempt
7132  * loading grf again when loading or starting next game
7133  * 03: error, abort loading and prevent loading again in
7134  * the future (only when restarting the patch)
7135  * B language-id see action 4, use 1F for built-in error messages
7136  * B message-id message to show, see below
7137  * S message for custom messages (message-id FF), text of the message
7138  * not present for built-in messages.
7139  * V data additional data for built-in (or custom) messages
7140  * B parnum parameter numbers to be shown in the message (maximum of 2) */
7141 
7142  static const StringID msgstr[] = {
7143  STR_NEWGRF_ERROR_VERSION_NUMBER,
7144  STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
7145  STR_NEWGRF_ERROR_UNSET_SWITCH,
7146  STR_NEWGRF_ERROR_INVALID_PARAMETER,
7147  STR_NEWGRF_ERROR_LOAD_BEFORE,
7148  STR_NEWGRF_ERROR_LOAD_AFTER,
7149  STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
7150  };
7151 
7152  static const StringID sevstr[] = {
7153  STR_NEWGRF_ERROR_MSG_INFO,
7154  STR_NEWGRF_ERROR_MSG_WARNING,
7155  STR_NEWGRF_ERROR_MSG_ERROR,
7156  STR_NEWGRF_ERROR_MSG_FATAL
7157  };
7158 
7159  byte severity = buf->ReadByte();
7160  byte lang = buf->ReadByte();
7161  byte message_id = buf->ReadByte();
7162 
7163  /* Skip the error if it isn't valid for the current language. */
7164  if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
7165 
7166  /* Skip the error until the activation stage unless bit 7 of the severity
7167  * is set. */
7168  if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
7169  GrfMsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage {}", _cur.stage);
7170  return;
7171  }
7172  ClrBit(severity, 7);
7173 
7174  if (severity >= lengthof(sevstr)) {
7175  GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity);
7176  severity = 2;
7177  } else if (severity == 3) {
7178  /* This is a fatal error, so make sure the GRF is deactivated and no
7179  * more of it gets loaded. */
7180  DisableGrf();
7181 
7182  /* Make sure we show fatal errors, instead of silly infos from before */
7183  _cur.grfconfig->error.reset();
7184  }
7185 
7186  if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
7187  GrfMsg(7, "GRFLoadError: Invalid message id.");
7188  return;
7189  }
7190 
7191  if (buf->Remaining() <= 1) {
7192  GrfMsg(7, "GRFLoadError: No message data supplied.");
7193  return;
7194  }
7195 
7196  /* For now we can only show one message per newgrf file. */
7197  if (_cur.grfconfig->error.has_value()) return;
7198 
7199  _cur.grfconfig->error = {sevstr[severity]};
7200  GRFError *error = &_cur.grfconfig->error.value();
7201 
7202  if (message_id == 0xFF) {
7203  /* This is a custom error message. */
7204  if (buf->HasData()) {
7205  const char *message = buf->ReadString();
7206 
7207  error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
7208  } else {
7209  GrfMsg(7, "GRFLoadError: No custom message supplied.");
7210  error->custom_message.clear();
7211  }
7212  } else {
7213  error->message = msgstr[message_id];
7214  }
7215 
7216  if (buf->HasData()) {
7217  const char *data = buf->ReadString();
7218 
7219  error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
7220  } else {
7221  GrfMsg(7, "GRFLoadError: No message data supplied.");
7222  error->data.clear();
7223  }
7224 
7225  /* Only two parameter numbers can be used in the string. */
7226  for (uint i = 0; i < error->param_value.size() && buf->HasData(); i++) {
7227  uint param_number = buf->ReadByte();
7228  error->param_value[i] = _cur.grffile->GetParam(param_number);
7229  }
7230 }
7231 
7232 /* Action 0x0C */
7233 static void GRFComment(ByteReader *buf)
7234 {
7235  /* <0C> [<ignored...>]
7236  *
7237  * V ignored Anything following the 0C is ignored */
7238 
7239  if (!buf->HasData()) return;
7240 
7241  const char *text = buf->ReadString();
7242  GrfMsg(2, "GRFComment: {}", text);
7243 }
7244 
7245 /* Action 0x0D (GLS_SAFETYSCAN) */
7246 static void SafeParamSet(ByteReader *buf)
7247 {
7248  uint8_t target = buf->ReadByte();
7249 
7250  /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
7251  if (target < 0x80 || target == 0x9E) return;
7252 
7253  /* GRM could be unsafe, but as here it can only happen after other GRFs
7254  * are loaded, it should be okay. If the GRF tried to use the slots it
7255  * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
7256  * sprites is considered safe. */
7257 
7258  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7259 
7260  /* Skip remainder of GRF */
7261  _cur.skip_sprites = -1;
7262 }
7263 
7264 
7265 static uint32_t GetPatchVariable(uint8_t param)
7266 {
7267  switch (param) {
7268  /* start year - 1920 */
7270 
7271  /* freight trains weight factor */
7272  case 0x0E: return _settings_game.vehicle.freight_trains;
7273 
7274  /* empty wagon speed increase */
7275  case 0x0F: return 0;
7276 
7277  /* plane speed factor; our patch option is reversed from TTDPatch's,
7278  * the following is good for 1x, 2x and 4x (most common?) and...
7279  * well not really for 3x. */
7280  case 0x10:
7282  default:
7283  case 4: return 1;
7284  case 3: return 2;
7285  case 2: return 2;
7286  case 1: return 4;
7287  }
7288 
7289 
7290  /* 2CC colourmap base sprite */
7291  case 0x11: return SPR_2CCMAP_BASE;
7292 
7293  /* map size: format = -MABXYSS
7294  * M : the type of map
7295  * bit 0 : set : squared map. Bit 1 is now not relevant
7296  * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7297  * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7298  * clear : X is the bigger edge.
7299  * A : minimum edge(log2) of the map
7300  * B : maximum edge(log2) of the map
7301  * XY : edges(log2) of each side of the map.
7302  * SS : combination of both X and Y, thus giving the size(log2) of the map
7303  */
7304  case 0x13: {
7305  byte map_bits = 0;
7306  byte log_X = Map::LogX() - 6; // subtraction is required to make the minimal size (64) zero based
7307  byte log_Y = Map::LogY() - 6;
7308  byte max_edge = std::max(log_X, log_Y);
7309 
7310  if (log_X == log_Y) { // we have a squared map, since both edges are identical
7311  SetBit(map_bits, 0);
7312  } else {
7313  if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7314  }
7315 
7316  return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7317  (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7318  }
7319 
7320  /* The maximum height of the map. */
7321  case 0x14:
7323 
7324  /* Extra foundations base sprite */
7325  case 0x15:
7326  return SPR_SLOPES_BASE;
7327 
7328  /* Shore base sprite */
7329  case 0x16:
7330  return SPR_SHORE_BASE;
7331 
7332  /* Game map seed */
7333  case 0x17:
7335 
7336  default:
7337  GrfMsg(2, "ParamSet: Unknown Patch variable 0x{:02X}.", param);
7338  return 0;
7339  }
7340 }
7341 
7342 
7343 static uint32_t PerformGRM(uint32_t *grm, uint16_t num_ids, uint16_t count, uint8_t op, uint8_t target, const char *type)
7344 {
7345  uint start = 0;
7346  uint size = 0;
7347 
7348  if (op == 6) {
7349  /* Return GRFID of set that reserved ID */
7350  return grm[_cur.grffile->GetParam(target)];
7351  }
7352 
7353  /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7354  if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7355 
7356  for (uint i = start; i < num_ids; i++) {
7357  if (grm[i] == 0) {
7358  size++;
7359  } else {
7360  if (op == 2 || op == 3) break;
7361  start = i + 1;
7362  size = 0;
7363  }
7364 
7365  if (size == count) break;
7366  }
7367 
7368  if (size == count) {
7369  /* Got the slot... */
7370  if (op == 0 || op == 3) {
7371  GrfMsg(2, "ParamSet: GRM: Reserving {} {} at {}", count, type, start);
7372  for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7373  }
7374  return start;
7375  }
7376 
7377  /* Unable to allocate */
7378  if (op != 4 && op != 5) {
7379  /* Deactivate GRF */
7380  GrfMsg(0, "ParamSet: GRM: Unable to allocate {} {}, deactivating", count, type);
7381  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7382  return UINT_MAX;
7383  }
7384 
7385  GrfMsg(1, "ParamSet: GRM: Unable to allocate {} {}", count, type);
7386  return UINT_MAX;
7387 }
7388 
7389 
7391 static void ParamSet(ByteReader *buf)
7392 {
7393  /* <0D> <target> <operation> <source1> <source2> [<data>]
7394  *
7395  * B target parameter number where result is stored
7396  * B operation operation to perform, see below
7397  * B source1 first source operand
7398  * B source2 second source operand
7399  * D data data to use in the calculation, not necessary
7400  * if both source1 and source2 refer to actual parameters
7401  *
7402  * Operations
7403  * 00 Set parameter equal to source1
7404  * 01 Addition, source1 + source2
7405  * 02 Subtraction, source1 - source2
7406  * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7407  * 04 Signed multiplication, source1 * source2 (both signed)
7408  * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7409  * signed quantity; left shift if positive and right shift if
7410  * negative, source1 is unsigned)
7411  * 06 Signed bit shift, source1 by source2
7412  * (source2 like in 05, and source1 as well)
7413  */
7414 
7415  uint8_t target = buf->ReadByte();
7416  uint8_t oper = buf->ReadByte();
7417  uint32_t src1 = buf->ReadByte();
7418  uint32_t src2 = buf->ReadByte();
7419 
7420  uint32_t data = 0;
7421  if (buf->Remaining() >= 4) data = buf->ReadDWord();
7422 
7423  /* You can add 80 to the operation to make it apply only if the target
7424  * is not defined yet. In this respect, a parameter is taken to be
7425  * defined if any of the following applies:
7426  * - it has been set to any value in the newgrf(w).cfg parameter list
7427  * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7428  * an earlier action D */
7429  if (HasBit(oper, 7)) {
7430  if (target < 0x80 && target < _cur.grffile->param_end) {
7431  GrfMsg(7, "ParamSet: Param {} already defined, skipping", target);
7432  return;
7433  }
7434 
7435  oper = GB(oper, 0, 7);
7436  }
7437 
7438  if (src2 == 0xFE) {
7439  if (GB(data, 0, 8) == 0xFF) {
7440  if (data == 0x0000FFFF) {
7441  /* Patch variables */
7442  src1 = GetPatchVariable(src1);
7443  } else {
7444  /* GRF Resource Management */
7445  uint8_t op = src1;
7446  uint8_t feature = GB(data, 8, 8);
7447  uint16_t count = GB(data, 16, 16);
7448 
7449  if (_cur.stage == GLS_RESERVE) {
7450  if (feature == 0x08) {
7451  /* General sprites */
7452  if (op == 0) {
7453  /* Check if the allocated sprites will fit below the original sprite limit */
7454  if (_cur.spriteid + count >= 16384) {
7455  GrfMsg(0, "ParamSet: GRM: Unable to allocate {} sprites; try changing NewGRF order", count);
7456  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7457  return;
7458  }
7459 
7460  /* Reserve space at the current sprite ID */
7461  GrfMsg(4, "ParamSet: GRM: Allocated {} sprites at {}", count, _cur.spriteid);
7462  _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
7463  _cur.spriteid += count;
7464  }
7465  }
7466  /* Ignore GRM result during reservation */
7467  src1 = 0;
7468  } else if (_cur.stage == GLS_ACTIVATION) {
7469  switch (feature) {
7470  case 0x00: // Trains
7471  case 0x01: // Road Vehicles
7472  case 0x02: // Ships
7473  case 0x03: // Aircraft
7475  src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7476  if (_cur.skip_sprites == -1) return;
7477  } else {
7478  /* GRM does not apply for dynamic engine allocation. */
7479  switch (op) {
7480  case 2:
7481  case 3:
7482  src1 = _cur.grffile->GetParam(target);
7483  break;
7484 
7485  default:
7486  src1 = 0;
7487  break;
7488  }
7489  }
7490  break;
7491 
7492  case 0x08: // General sprites
7493  switch (op) {
7494  case 0:
7495  /* Return space reserved during reservation stage */
7496  src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
7497  GrfMsg(4, "ParamSet: GRM: Using pre-allocated sprites at {}", src1);
7498  break;
7499 
7500  case 1:
7501  src1 = _cur.spriteid;
7502  break;
7503 
7504  default:
7505  GrfMsg(1, "ParamSet: GRM: Unsupported operation {} for general sprites", op);
7506  return;
7507  }
7508  break;
7509 
7510  case 0x0B: // Cargo
7511  /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7512  src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7513  if (_cur.skip_sprites == -1) return;
7514  break;
7515 
7516  default: GrfMsg(1, "ParamSet: GRM: Unsupported feature 0x{:X}", feature); return;
7517  }
7518  } else {
7519  /* Ignore GRM during initialization */
7520  src1 = 0;
7521  }
7522  }
7523  } else {
7524  /* Read another GRF File's parameter */
7525  const GRFFile *file = GetFileByGRFID(data);
7526  GRFConfig *c = GetGRFConfig(data);
7527  if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7528  /* Disable the read GRF if it is a static NewGRF. */
7530  src1 = 0;
7531  } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7532  src1 = 0;
7533  } else if (src1 == 0xFE) {
7534  src1 = c->version;
7535  } else {
7536  src1 = file->GetParam(src1);
7537  }
7538  }
7539  } else {
7540  /* The source1 and source2 operands refer to the grf parameter number
7541  * like in action 6 and 7. In addition, they can refer to the special
7542  * variables available in action 7, or they can be FF to use the value
7543  * of <data>. If referring to parameters that are undefined, a value
7544  * of 0 is used instead. */
7545  src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7546  src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7547  }
7548 
7549  uint32_t res;
7550  switch (oper) {
7551  case 0x00:
7552  res = src1;
7553  break;
7554 
7555  case 0x01:
7556  res = src1 + src2;
7557  break;
7558 
7559  case 0x02:
7560  res = src1 - src2;
7561  break;
7562 
7563  case 0x03:
7564  res = src1 * src2;
7565  break;
7566 
7567  case 0x04:
7568  res = (int32_t)src1 * (int32_t)src2;
7569  break;
7570 
7571  case 0x05:
7572  if ((int32_t)src2 < 0) {
7573  res = src1 >> -(int32_t)src2;
7574  } else {
7575  res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7576  }
7577  break;
7578 
7579  case 0x06:
7580  if ((int32_t)src2 < 0) {
7581  res = (int32_t)src1 >> -(int32_t)src2;
7582  } else {
7583  res = (int32_t)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7584  }
7585  break;
7586 
7587  case 0x07: // Bitwise AND
7588  res = src1 & src2;
7589  break;
7590 
7591  case 0x08: // Bitwise OR
7592  res = src1 | src2;
7593  break;
7594 
7595  case 0x09: // Unsigned division
7596  if (src2 == 0) {
7597  res = src1;
7598  } else {
7599  res = src1 / src2;
7600  }
7601  break;
7602 
7603  case 0x0A: // Signed division
7604  if (src2 == 0) {
7605  res = src1;
7606  } else {
7607  res = (int32_t)src1 / (int32_t)src2;
7608  }
7609  break;
7610 
7611  case 0x0B: // Unsigned modulo
7612  if (src2 == 0) {
7613  res = src1;
7614  } else {
7615  res = src1 % src2;
7616  }
7617  break;
7618 
7619  case 0x0C: // Signed modulo
7620  if (src2 == 0) {
7621  res = src1;
7622  } else {
7623  res = (int32_t)src1 % (int32_t)src2;
7624  }
7625  break;
7626 
7627  default: GrfMsg(0, "ParamSet: Unknown operation {}, skipping", oper); return;
7628  }
7629 
7630  switch (target) {
7631  case 0x8E: // Y-Offset for train sprites
7632  _cur.grffile->traininfo_vehicle_pitch = res;
7633  break;
7634 
7635  case 0x8F: { // Rail track type cost factors
7636  extern RailTypeInfo _railtypes[RAILTYPE_END];
7637  _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7639  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7640  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7641  } else {
7642  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7643  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7644  }
7645  _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7646  break;
7647  }
7648 
7649  /* not implemented */
7650  case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7651  case 0x94: // Tile refresh offset to right
7652  case 0x95: // Tile refresh offset upwards
7653  case 0x96: // Tile refresh offset downwards
7654  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
7655  case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7656  GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7657  break;
7658 
7659  case 0x9E: // Miscellaneous GRF features
7660  /* Set train list engine width */
7661  _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7662  /* Remove the local flags from the global flags */
7664 
7665  /* Only copy safe bits for static grfs */
7666  if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7667  uint32_t safe_bits = 0;
7668  SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7669 
7670  _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7671  } else {
7672  _misc_grf_features = res;
7673  }
7674  break;
7675 
7676  case 0x9F: // locale-dependent settings
7677  GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7678  break;
7679 
7680  default:
7681  if (target < 0x80) {
7682  _cur.grffile->param[target] = res;
7683  /* param is zeroed by default */
7684  if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7685  } else {
7686  GrfMsg(7, "ParamSet: Skipping unknown target 0x{:02X}", target);
7687  }
7688  break;
7689  }
7690 }
7691 
7692 /* Action 0x0E (GLS_SAFETYSCAN) */
7693 static void SafeGRFInhibit(ByteReader *buf)
7694 {
7695  /* <0E> <num> <grfids...>
7696  *
7697  * B num Number of GRFIDs that follow
7698  * D grfids GRFIDs of the files to deactivate */
7699 
7700  uint8_t num = buf->ReadByte();
7701 
7702  for (uint i = 0; i < num; i++) {
7703  uint32_t grfid = buf->ReadDWord();
7704 
7705  /* GRF is unsafe it if tries to deactivate other GRFs */
7706  if (grfid != _cur.grfconfig->ident.grfid) {
7707  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7708 
7709  /* Skip remainder of GRF */
7710  _cur.skip_sprites = -1;
7711 
7712  return;
7713  }
7714  }
7715 }
7716 
7717 /* Action 0x0E */
7718 static void GRFInhibit(ByteReader *buf)
7719 {
7720  /* <0E> <num> <grfids...>
7721  *
7722  * B num Number of GRFIDs that follow
7723  * D grfids GRFIDs of the files to deactivate */
7724 
7725  uint8_t num = buf->ReadByte();
7726 
7727  for (uint i = 0; i < num; i++) {
7728  uint32_t grfid = buf->ReadDWord();
7729  GRFConfig *file = GetGRFConfig(grfid);
7730 
7731  /* Unset activation flag */
7732  if (file != nullptr && file != _cur.grfconfig) {
7733  GrfMsg(2, "GRFInhibit: Deactivating file '{}'", file->filename);
7734  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7735  error->data = _cur.grfconfig->GetName();
7736  }
7737  }
7738 }
7739 
7741 static void FeatureTownName(ByteReader *buf)
7742 {
7743  /* <0F> <id> <style-name> <num-parts> <parts>
7744  *
7745  * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7746  * V style-name Name of the style (only for final definition)
7747  * B num-parts Number of parts in this definition
7748  * V parts The parts */
7749 
7750  uint32_t grfid = _cur.grffile->grfid;
7751 
7752  GRFTownName *townname = AddGRFTownName(grfid);
7753 
7754  byte id = buf->ReadByte();
7755  GrfMsg(6, "FeatureTownName: definition 0x{:02X}", id & 0x7F);
7756 
7757  if (HasBit(id, 7)) {
7758  /* Final definition */
7759  ClrBit(id, 7);
7760  bool new_scheme = _cur.grffile->grf_version >= 7;
7761 
7762  byte lang = buf->ReadByte();
7763  StringID style = STR_UNDEFINED;
7764 
7765  do {
7766  ClrBit(lang, 7);
7767 
7768  const char *name = buf->ReadString();
7769 
7770  std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7771  GrfMsg(6, "FeatureTownName: lang 0x{:X} -> '{}'", lang, lang_name);
7772 
7773  style = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7774 
7775  lang = buf->ReadByte();
7776  } while (lang != 0);
7777  townname->styles.emplace_back(style, id);
7778  }
7779 
7780  uint8_t parts = buf->ReadByte();
7781  GrfMsg(6, "FeatureTownName: {} parts", parts);
7782 
7783  townname->partlists[id].reserve(parts);
7784  for (uint partnum = 0; partnum < parts; partnum++) {
7785  NamePartList &partlist = townname->partlists[id].emplace_back();
7786  uint8_t texts = buf->ReadByte();
7787  partlist.bitstart = buf->ReadByte();
7788  partlist.bitcount = buf->ReadByte();
7789  partlist.maxprob = 0;
7790  GrfMsg(6, "FeatureTownName: part {} contains {} texts and will use GB(seed, {}, {})", partnum, texts, partlist.bitstart, partlist.bitcount);
7791 
7792  partlist.parts.reserve(texts);
7793  for (uint textnum = 0; textnum < texts; textnum++) {
7794  NamePart &part = partlist.parts.emplace_back();
7795  part.prob = buf->ReadByte();
7796 
7797  if (HasBit(part.prob, 7)) {
7798  byte ref_id = buf->ReadByte();
7799  if (ref_id >= GRFTownName::MAX_LISTS || townname->partlists[ref_id].empty()) {
7800  GrfMsg(0, "FeatureTownName: definition 0x{:02X} doesn't exist, deactivating", ref_id);
7801  DelGRFTownName(grfid);
7802  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7803  return;
7804  }
7805  part.id = ref_id;
7806  GrfMsg(6, "FeatureTownName: part {}, text {}, uses intermediate definition 0x{:02X} (with probability {})", partnum, textnum, ref_id, part.prob & 0x7F);
7807  } else {
7808  const char *text = buf->ReadString();
7809  part.text = TranslateTTDPatchCodes(grfid, 0, false, text);
7810  GrfMsg(6, "FeatureTownName: part {}, text {}, '{}' (with probability {})", partnum, textnum, part.text, part.prob);
7811  }
7812  partlist.maxprob += GB(part.prob, 0, 7);
7813  }
7814  GrfMsg(6, "FeatureTownName: part {}, total probability {}", partnum, partlist.maxprob);
7815  }
7816 }
7817 
7819 static void DefineGotoLabel(ByteReader *buf)
7820 {
7821  /* <10> <label> [<comment>]
7822  *
7823  * B label The label to define
7824  * V comment Optional comment - ignored */
7825 
7826  byte nfo_label = buf->ReadByte();
7827 
7828  _cur.grffile->labels.emplace_back(nfo_label, _cur.nfo_line, _cur.file->GetPos());
7829 
7830  GrfMsg(2, "DefineGotoLabel: GOTO target with label 0x{:02X}", nfo_label);
7831 }
7832 
7837 static void ImportGRFSound(SoundEntry *sound)
7838 {
7839  const GRFFile *file;
7840  uint32_t grfid = _cur.file->ReadDword();
7841  SoundID sound_id = _cur.file->ReadWord();
7842 
7843  file = GetFileByGRFID(grfid);
7844  if (file == nullptr || file->sound_offset == 0) {
7845  GrfMsg(1, "ImportGRFSound: Source file not available");
7846  return;
7847  }
7848 
7849  if (sound_id >= file->num_sounds) {
7850  GrfMsg(1, "ImportGRFSound: Sound effect {} is invalid", sound_id);
7851  return;
7852  }
7853 
7854  GrfMsg(2, "ImportGRFSound: Copying sound {} ({}) from file {:x}", sound_id, file->sound_offset + sound_id, grfid);
7855 
7856  *sound = *GetSound(file->sound_offset + sound_id);
7857 
7858  /* Reset volume and priority, which TTDPatch doesn't copy */
7859  sound->volume = 128;
7860  sound->priority = 0;
7861 }
7862 
7868 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7869 {
7870  /* Set default volume and priority */
7871  sound->volume = 0x80;
7872  sound->priority = 0;
7873 
7874  if (offs != SIZE_MAX) {
7875  /* Sound is present in the NewGRF. */
7876  sound->file = _cur.file;
7877  sound->file_offset = offs;
7878  sound->grf_container_ver = _cur.file->GetContainerVersion();
7879  }
7880 }
7881 
7882 /* Action 0x11 */
7883 static void GRFSound(ByteReader *buf)
7884 {
7885  /* <11> <num>
7886  *
7887  * W num Number of sound files that follow */
7888 
7889  uint16_t num = buf->ReadWord();
7890  if (num == 0) return;
7891 
7892  SoundEntry *sound;
7893  if (_cur.grffile->sound_offset == 0) {
7894  _cur.grffile->sound_offset = GetNumSounds();
7895  _cur.grffile->num_sounds = num;
7896  sound = AllocateSound(num);
7897  } else {
7898  sound = GetSound(_cur.grffile->sound_offset);
7899  }
7900 
7901  SpriteFile &file = *_cur.file;
7902  byte grf_container_version = file.GetContainerVersion();
7903  for (int i = 0; i < num; i++) {
7904  _cur.nfo_line++;
7905 
7906  /* Check whether the index is in range. This might happen if multiple action 11 are present.
7907  * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7908  bool invalid = i >= _cur.grffile->num_sounds;
7909 
7910  size_t offs = file.GetPos();
7911 
7912  uint32_t len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7913  byte type = file.ReadByte();
7914 
7915  if (grf_container_version >= 2 && type == 0xFD) {
7916  /* Reference to sprite section. */
7917  if (invalid) {
7918  GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7919  file.SkipBytes(len);
7920  } else if (len != 4) {
7921  GrfMsg(1, "GRFSound: Invalid sprite section import");
7922  file.SkipBytes(len);
7923  } else {
7924  uint32_t id = file.ReadDword();
7925  if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7926  }
7927  continue;
7928  }
7929 
7930  if (type != 0xFF) {
7931  GrfMsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7932  file.SkipBytes(7);
7933  SkipSpriteData(*_cur.file, type, len - 8);
7934  continue;
7935  }
7936 
7937  if (invalid) {
7938  GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7939  file.SkipBytes(len);
7940  }
7941 
7942  byte action = file.ReadByte();
7943  switch (action) {
7944  case 0xFF:
7945  /* Allocate sound only in init stage. */
7946  if (_cur.stage == GLS_INIT) {
7947  if (grf_container_version >= 2) {
7948  GrfMsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7949  } else {
7950  LoadGRFSound(offs, sound + i);
7951  }
7952  }
7953  file.SkipBytes(len - 1); // already read <action>
7954  break;
7955 
7956  case 0xFE:
7957  if (_cur.stage == GLS_ACTIVATION) {
7958  /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7959  * importing sounds, so this is probably all wrong... */
7960  if (file.ReadByte() != 0) GrfMsg(1, "GRFSound: Import type mismatch");
7961  ImportGRFSound(sound + i);
7962  } else {
7963  file.SkipBytes(len - 1); // already read <action>
7964  }
7965  break;
7966 
7967  default:
7968  GrfMsg(1, "GRFSound: Unexpected Action {:x} found, skipping", action);
7969  file.SkipBytes(len - 1); // already read <action>
7970  break;
7971  }
7972  }
7973 }
7974 
7975 /* Action 0x11 (SKIP) */
7976 static void SkipAct11(ByteReader *buf)
7977 {
7978  /* <11> <num>
7979  *
7980  * W num Number of sound files that follow */
7981 
7982  _cur.skip_sprites = buf->ReadWord();
7983 
7984  GrfMsg(3, "SkipAct11: Skipping {} sprites", _cur.skip_sprites);
7985 }
7986 
7988 static void LoadFontGlyph(ByteReader *buf)
7989 {
7990  /* <12> <num_def> <font_size> <num_char> <base_char>
7991  *
7992  * B num_def Number of definitions
7993  * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7994  * B num_char Number of consecutive glyphs
7995  * W base_char First character index */
7996 
7997  uint8_t num_def = buf->ReadByte();
7998 
7999  for (uint i = 0; i < num_def; i++) {
8000  FontSize size = (FontSize)buf->ReadByte();
8001  uint8_t num_char = buf->ReadByte();
8002  uint16_t base_char = buf->ReadWord();
8003 
8004  if (size >= FS_END) {
8005  GrfMsg(1, "LoadFontGlyph: Size {} is not supported, ignoring", size);
8006  }
8007 
8008  GrfMsg(7, "LoadFontGlyph: Loading {} glyph(s) at 0x{:04X} for size {}", num_char, base_char, size);
8009 
8010  for (uint c = 0; c < num_char; c++) {
8011  if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
8012  _cur.nfo_line++;
8013  LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
8014  }
8015  }
8016 }
8017 
8019 static void SkipAct12(ByteReader *buf)
8020 {
8021  /* <12> <num_def> <font_size> <num_char> <base_char>
8022  *
8023  * B num_def Number of definitions
8024  * B font_size Size of font (0 = normal, 1 = small, 2 = large)
8025  * B num_char Number of consecutive glyphs
8026  * W base_char First character index */
8027 
8028  uint8_t num_def = buf->ReadByte();
8029 
8030  for (uint i = 0; i < num_def; i++) {
8031  /* Ignore 'size' byte */
8032  buf->ReadByte();
8033 
8034  /* Sum up number of characters */
8035  _cur.skip_sprites += buf->ReadByte();
8036 
8037  /* Ignore 'base_char' word */
8038  buf->ReadWord();
8039  }
8040 
8041  GrfMsg(3, "SkipAct12: Skipping {} sprites", _cur.skip_sprites);
8042 }
8043 
8046 {
8047  /* <13> <grfid> <num-ent> <offset> <text...>
8048  *
8049  * 4*B grfid The GRFID of the file whose texts are to be translated
8050  * B num-ent Number of strings
8051  * W offset First text ID
8052  * S text... Zero-terminated strings */
8053 
8054  uint32_t grfid = buf->ReadDWord();
8055  const GRFConfig *c = GetGRFConfig(grfid);
8056  if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
8057  GrfMsg(7, "TranslateGRFStrings: GRFID 0x{:08X} unknown, skipping action 13", BSWAP32(grfid));
8058  return;
8059  }
8060 
8061  if (c->status == GCS_INITIALISED) {
8062  /* If the file is not active but will be activated later, give an error
8063  * and disable this file. */
8064  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
8065 
8066  error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
8067 
8068  return;
8069  }
8070 
8071  /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
8072  * to be added as a generic string, thus the language id of 0x7F. For this to work
8073  * new_scheme has to be true as well, which will also be implicitly the case for version 8
8074  * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
8075  * not change anything if a string has been provided specifically for this language. */
8076  byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
8077  byte num_strings = buf->ReadByte();
8078  uint16_t first_id = buf->ReadWord();
8079 
8080  if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
8081  GrfMsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x{:04X}, number: 0x{:02X})", first_id, num_strings);
8082  return;
8083  }
8084 
8085  for (uint i = 0; i < num_strings && buf->HasData(); i++) {
8086  const char *string = buf->ReadString();
8087 
8088  if (StrEmpty(string)) {
8089  GrfMsg(7, "TranslateGRFString: Ignoring empty string.");
8090  continue;
8091  }
8092 
8093  AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
8094  }
8095 }
8096 
8098 static bool ChangeGRFName(byte langid, const char *str)
8099 {
8100  AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
8101  return true;
8102 }
8103 
8105 static bool ChangeGRFDescription(byte langid, const char *str)
8106 {
8107  AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
8108  return true;
8109 }
8110 
8112 static bool ChangeGRFURL(byte langid, const char *str)
8113 {
8114  AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
8115  return true;
8116 }
8117 
8119 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
8120 {
8121  if (len != 1) {
8122  GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got {}, ignoring this field", len);
8123  buf->Skip(len);
8124  } else {
8125  _cur.grfconfig->num_valid_params = std::min(buf->ReadByte(), ClampTo<uint8_t>(_cur.grfconfig->param.size()));
8126  }
8127  return true;
8128 }
8129 
8131 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
8132 {
8133  if (len != 1) {
8134  GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got {}, ignoring this field", len);
8135  buf->Skip(len);
8136  } else {
8137  char data = buf->ReadByte();
8138  GRFPalette pal = GRFP_GRF_UNSET;
8139  switch (data) {
8140  case '*':
8141  case 'A': pal = GRFP_GRF_ANY; break;
8142  case 'W': pal = GRFP_GRF_WINDOWS; break;
8143  case 'D': pal = GRFP_GRF_DOS; break;
8144  default:
8145  GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'PALS', ignoring this field", data);
8146  break;
8147  }
8148  if (pal != GRFP_GRF_UNSET) {
8149  _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
8150  _cur.grfconfig->palette |= pal;
8151  }
8152  }
8153  return true;
8154 }
8155 
8157 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
8158 {
8159  if (len != 1) {
8160  GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got {}, ignoring this field", len);
8161  buf->Skip(len);
8162  } else {
8163  char data = buf->ReadByte();
8164  GRFPalette pal = GRFP_BLT_UNSET;
8165  switch (data) {
8166  case '8': pal = GRFP_BLT_UNSET; break;
8167  case '3': pal = GRFP_BLT_32BPP; break;
8168  default:
8169  GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'BLTR', ignoring this field", data);
8170  return true;
8171  }
8172  _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
8173  _cur.grfconfig->palette |= pal;
8174  }
8175  return true;
8176 }
8177 
8179 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
8180 {
8181  if (len != 4) {
8182  GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got {}, ignoring this field", len);
8183  buf->Skip(len);
8184  } else {
8185  /* Set min_loadable_version as well (default to minimal compatibility) */
8186  _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
8187  }
8188  return true;
8189 }
8190 
8192 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
8193 {
8194  if (len != 4) {
8195  GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got {}, ignoring this field", len);
8196  buf->Skip(len);
8197  } else {
8198  _cur.grfconfig->min_loadable_version = buf->ReadDWord();
8199  if (_cur.grfconfig->version == 0) {
8200  GrfMsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
8201  _cur.grfconfig->min_loadable_version = 0;
8202  }
8203  if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
8204  GrfMsg(2, "StaticGRFInfo: 'MINV' defined as {}, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
8206  }
8207  }
8208  return true;
8209 }
8210 
8212 
8214 static bool ChangeGRFParamName(byte langid, const char *str)
8215 {
8216  AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
8217  return true;
8218 }
8219 
8221 static bool ChangeGRFParamDescription(byte langid, const char *str)
8222 {
8223  AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
8224  return true;
8225 }
8226 
8228 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
8229 {
8230  if (len != 1) {
8231  GrfMsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got {}, ignoring this field", len);
8232  buf->Skip(len);
8233  } else {
8234  GRFParameterType type = (GRFParameterType)buf->ReadByte();
8235  if (type < PTYPE_END) {
8236  _cur_parameter->type = type;
8237  } else {
8238  GrfMsg(3, "StaticGRFInfo: unknown parameter type {}, ignoring this field", type);
8239  }
8240  }
8241  return true;
8242 }
8243 
8245 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
8246 {
8248  GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8249  buf->Skip(len);
8250  } else if (len != 8) {
8251  GrfMsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got {}, ignoring this field", len);
8252  buf->Skip(len);
8253  } else {
8254  uint32_t min_value = buf->ReadDWord();
8255  uint32_t max_value = buf->ReadDWord();
8256  if (min_value <= max_value) {
8257  _cur_parameter->min_value = min_value;
8258  _cur_parameter->max_value = max_value;
8259  } else {
8260  GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8261  }
8262  }
8263  return true;
8264 }
8265 
8267 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
8268 {
8269  if (len < 1 || len > 3) {
8270  GrfMsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got {}, ignoring this field", len);
8271  buf->Skip(len);
8272  } else {
8273  byte param_nr = buf->ReadByte();
8274  if (param_nr >= _cur.grfconfig->param.size()) {
8275  GrfMsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param {}, ignoring this field", param_nr);
8276  buf->Skip(len - 1);
8277  } else {
8278  _cur_parameter->param_nr = param_nr;
8279  if (len >= 2) _cur_parameter->first_bit = std::min<byte>(buf->ReadByte(), 31);
8280  if (len >= 3) _cur_parameter->num_bit = std::min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
8281  }
8282  }
8283 
8284  return true;
8285 }
8286 
8288 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
8289 {
8290  if (len != 4) {
8291  GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got {}, ignoring this field", len);
8292  buf->Skip(len);
8293  } else {
8294  _cur_parameter->def_value = buf->ReadDWord();
8295  }
8296  _cur.grfconfig->has_param_defaults = true;
8297  return true;
8298 }
8299 
8300 typedef bool (*DataHandler)(size_t, ByteReader *);
8301 typedef bool (*TextHandler)(byte, const char *str);
8302 typedef bool (*BranchHandler)(ByteReader *);
8303 
8314  id(0),
8315  type(0)
8316  {}
8317 
8323  AllowedSubtags(uint32_t id, DataHandler handler) :
8324  id(id),
8325  type('B')
8326  {
8327  this->handler.data = handler;
8328  }
8329 
8335  AllowedSubtags(uint32_t id, TextHandler handler) :
8336  id(id),
8337  type('T')
8338  {
8339  this->handler.text = handler;
8340  }
8341 
8347  AllowedSubtags(uint32_t id, BranchHandler handler) :
8348  id(id),
8349  type('C')
8350  {
8351  this->handler.call_handler = true;
8352  this->handler.u.branch = handler;
8353  }
8354 
8361  id(id),
8362  type('C')
8363  {
8364  this->handler.call_handler = false;
8365  this->handler.u.subtags = subtags;
8366  }
8367 
8368  uint32_t id;
8369  byte type;
8370  union {
8373  struct {
8374  union {
8377  } u;
8379  };
8380  } handler;
8381 };
8382 
8383 static bool SkipUnknownInfo(ByteReader *buf, byte type);
8384 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
8385 
8393 {
8394  byte type = buf->ReadByte();
8395  while (type != 0) {
8396  uint32_t id = buf->ReadDWord();
8397  if (type != 'T' || id > _cur_parameter->max_value) {
8398  GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8399  if (!SkipUnknownInfo(buf, type)) return false;
8400  type = buf->ReadByte();
8401  continue;
8402  }
8403 
8404  byte langid = buf->ReadByte();
8405  const char *name_string = buf->ReadString();
8406 
8407  auto val_name = _cur_parameter->value_names.find(id);
8408  if (val_name != _cur_parameter->value_names.end()) {
8409  AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8410  } else {
8411  GRFTextList list;
8412  AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8413  _cur_parameter->value_names[id] = list;
8414  }
8415 
8416  type = buf->ReadByte();
8417  }
8418  return true;
8419 }
8420 
8430  AllowedSubtags()
8431 };
8432 
8440 {
8441  byte type = buf->ReadByte();
8442  while (type != 0) {
8443  uint32_t id = buf->ReadDWord();
8444  if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8445  GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8446  if (!SkipUnknownInfo(buf, type)) return false;
8447  type = buf->ReadByte();
8448  continue;
8449  }
8450 
8451  if (id >= _cur.grfconfig->param_info.size()) {
8452  _cur.grfconfig->param_info.resize(id + 1);
8453  }
8454  if (!_cur.grfconfig->param_info[id].has_value()) {
8455  _cur.grfconfig->param_info[id] = GRFParameterInfo(id);
8456  }
8457  _cur_parameter = &_cur.grfconfig->param_info[id].value();
8458  /* Read all parameter-data and process each node. */
8459  if (!HandleNodes(buf, _tags_parameters)) return false;
8460  type = buf->ReadByte();
8461  }
8462  return true;
8463 }
8464 
8467  AllowedSubtags('NAME', ChangeGRFName),
8469  AllowedSubtags('URL_', ChangeGRFURL),
8476  AllowedSubtags()
8477 };
8478 
8481  AllowedSubtags('INFO', _tags_info),
8482  AllowedSubtags()
8483 };
8484 
8485 
8492 static bool SkipUnknownInfo(ByteReader *buf, byte type)
8493 {
8494  /* type and id are already read */
8495  switch (type) {
8496  case 'C': {
8497  byte new_type = buf->ReadByte();
8498  while (new_type != 0) {
8499  buf->ReadDWord(); // skip the id
8500  if (!SkipUnknownInfo(buf, new_type)) return false;
8501  new_type = buf->ReadByte();
8502  }
8503  break;
8504  }
8505 
8506  case 'T':
8507  buf->ReadByte(); // lang
8508  buf->ReadString(); // actual text
8509  break;
8510 
8511  case 'B': {
8512  uint16_t size = buf->ReadWord();
8513  buf->Skip(size);
8514  break;
8515  }
8516 
8517  default:
8518  return false;
8519  }
8520 
8521  return true;
8522 }
8523 
8532 static bool HandleNode(byte type, uint32_t id, ByteReader *buf, AllowedSubtags subtags[])
8533 {
8534  uint i = 0;
8535  AllowedSubtags *tag;
8536  while ((tag = &subtags[i++])->type != 0) {
8537  if (tag->id != BSWAP32(id) || tag->type != type) continue;
8538  switch (type) {
8539  default: NOT_REACHED();
8540 
8541  case 'T': {
8542  byte langid = buf->ReadByte();
8543  return tag->handler.text(langid, buf->ReadString());
8544  }
8545 
8546  case 'B': {
8547  size_t len = buf->ReadWord();
8548  if (buf->Remaining() < len) return false;
8549  return tag->handler.data(len, buf);
8550  }
8551 
8552  case 'C': {
8553  if (tag->handler.call_handler) {
8554  return tag->handler.u.branch(buf);
8555  }
8556  return HandleNodes(buf, tag->handler.u.subtags);
8557  }
8558  }
8559  }
8560  GrfMsg(2, "StaticGRFInfo: unknown type/id combination found, type={:c}, id={:x}", type, id);
8561  return SkipUnknownInfo(buf, type);
8562 }
8563 
8570 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
8571 {
8572  byte type = buf->ReadByte();
8573  while (type != 0) {
8574  uint32_t id = buf->ReadDWord();
8575  if (!HandleNode(type, id, buf, subtags)) return false;
8576  type = buf->ReadByte();
8577  }
8578  return true;
8579 }
8580 
8585 static void StaticGRFInfo(ByteReader *buf)
8586 {
8587  /* <14> <type> <id> <text/data...> */
8588  HandleNodes(buf, _tags_root);
8589 }
8590 
8595 static void GRFUnsafe(ByteReader *)
8596 {
8597  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8598 
8599  /* Skip remainder of GRF */
8600  _cur.skip_sprites = -1;
8601 }
8602 
8603 
8606 {
8607  _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1U : 0U) << 0x0C) // keepsmallairport
8608  | (1U << 0x0D) // newairports
8609  | (1U << 0x0E) // largestations
8610  | ((_settings_game.construction.max_bridge_length > 16 ? 1U : 0U) << 0x0F) // longbridges
8611  | (0U << 0x10) // loadtime
8612  | (1U << 0x12) // presignals
8613  | (1U << 0x13) // extpresignals
8614  | ((_settings_game.vehicle.never_expire_vehicles ? 1U : 0U) << 0x16) // enginespersist
8615  | (1U << 0x1B) // multihead
8616  | (1U << 0x1D) // lowmemory
8617  | (1U << 0x1E); // generalfixes
8618 
8619  _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1U : 0U) << 0x07) // moreairports - based on units of noise
8620  | (1U << 0x08) // mammothtrains
8621  | (1U << 0x09) // trainrefit
8622  | (0U << 0x0B) // subsidiaries
8623  | ((_settings_game.order.gradual_loading ? 1U : 0U) << 0x0C) // gradualloading
8624  | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8625  | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8626  | (1U << 0x14) // bridgespeedlimits
8627  | (1U << 0x16) // eternalgame
8628  | (1U << 0x17) // newtrains
8629  | (1U << 0x18) // newrvs
8630  | (1U << 0x19) // newships
8631  | (1U << 0x1A) // newplanes
8632  | ((_settings_game.construction.train_signal_side == 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8633  | ((_settings_game.vehicle.disable_elrails ? 0U : 1U) << 0x1C); // electrifiedrailway
8634 
8635  _ttdpatch_flags[2] = (1U << 0x01) // loadallgraphics - obsolote
8636  | (1U << 0x03) // semaphores
8637  | (1U << 0x0A) // newobjects
8638  | (0U << 0x0B) // enhancedgui
8639  | (0U << 0x0C) // newagerating
8640  | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x0D) // buildonslopes
8641  | (1U << 0x0E) // fullloadany
8642  | (1U << 0x0F) // planespeed
8643  | (0U << 0x10) // moreindustriesperclimate - obsolete
8644  | (0U << 0x11) // moretoylandfeatures
8645  | (1U << 0x12) // newstations
8646  | (1U << 0x13) // tracktypecostdiff
8647  | (1U << 0x14) // manualconvert
8648  | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x15) // buildoncoasts
8649  | (1U << 0x16) // canals
8650  | (1U << 0x17) // newstartyear
8651  | ((_settings_game.vehicle.freight_trains > 1 ? 1U : 0U) << 0x18) // freighttrains
8652  | (1U << 0x19) // newhouses
8653  | (1U << 0x1A) // newbridges
8654  | (1U << 0x1B) // newtownnames
8655  | (1U << 0x1C) // moreanimation
8656  | ((_settings_game.vehicle.wagon_speed_limits ? 1U : 0U) << 0x1D) // wagonspeedlimits
8657  | (1U << 0x1E) // newshistory
8658  | (0U << 0x1F); // custombridgeheads
8659 
8660  _ttdpatch_flags[3] = (0U << 0x00) // newcargodistribution
8661  | (1U << 0x01) // windowsnap
8662  | ((_settings_game.economy.allow_town_roads || _generating_world ? 0U : 1U) << 0x02) // townbuildnoroad
8663  | (1U << 0x03) // pathbasedsignalling
8664  | (0U << 0x04) // aichoosechance
8665  | (1U << 0x05) // resolutionwidth
8666  | (1U << 0x06) // resolutionheight
8667  | (1U << 0x07) // newindustries
8668  | ((_settings_game.order.improved_load ? 1U : 0U) << 0x08) // fifoloading
8669  | (0U << 0x09) // townroadbranchprob
8670  | (0U << 0x0A) // tempsnowline
8671  | (1U << 0x0B) // newcargo
8672  | (1U << 0x0C) // enhancemultiplayer
8673  | (1U << 0x0D) // onewayroads
8674  | (1U << 0x0E) // irregularstations
8675  | (1U << 0x0F) // statistics
8676  | (1U << 0x10) // newsounds
8677  | (1U << 0x11) // autoreplace
8678  | (1U << 0x12) // autoslope
8679  | (0U << 0x13) // followvehicle
8680  | (1U << 0x14) // trams
8681  | (0U << 0x15) // enhancetunnels
8682  | (1U << 0x16) // shortrvs
8683  | (1U << 0x17) // articulatedrvs
8684  | ((_settings_game.vehicle.dynamic_engines ? 1U : 0U) << 0x18) // dynamic engines
8685  | (1U << 0x1E) // variablerunningcosts
8686  | (1U << 0x1F); // any switch is on
8687 
8688  _ttdpatch_flags[4] = (1U << 0x00) // larger persistent storage
8689  | ((_settings_game.economy.inflation ? 1U : 0U) << 0x01) // inflation is on
8690  | (1U << 0x02); // extended string range
8691 }
8692 
8694 static void ResetCustomStations()
8695 {
8696  for (GRFFile * const file : _grf_files) {
8697  file->stations.clear();
8698  }
8699 }
8700 
8702 static void ResetCustomHouses()
8703 {
8704  for (GRFFile * const file : _grf_files) {
8705  file->housespec.clear();
8706  }
8707 }
8708 
8710 static void ResetCustomAirports()
8711 {
8712  for (GRFFile * const file : _grf_files) {
8713  for (auto &as : file->airportspec) {
8714  if (as != nullptr) {
8715  /* We need to remove the tiles layouts */
8716  for (int j = 0; j < as->num_table; j++) {
8717  /* remove the individual layouts */
8718  free(as->table[j]);
8719  }
8720  free(as->table);
8721  free(as->depot_table);
8722  free(as->rotation);
8723  }
8724  }
8725  file->airportspec.clear();
8726  file->airtspec.clear();
8727  }
8728 }
8729 
8732 {
8733  for (GRFFile * const file : _grf_files) {
8734  file->industryspec.clear();
8735  file->indtspec.clear();
8736  }
8737 }
8738 
8740 static void ResetCustomObjects()
8741 {
8742  for (GRFFile * const file : _grf_files) {
8743  file->objectspec.clear();
8744  }
8745 }
8746 
8747 static void ResetCustomRoadStops()
8748 {
8749  for (auto file : _grf_files) {
8750  file->roadstops.clear();
8751  }
8752 }
8753 
8755 static void ResetNewGRF()
8756 {
8757  for (GRFFile * const file : _grf_files) {
8758  delete file;
8759  }
8760 
8761  _grf_files.clear();
8762  _cur.grffile = nullptr;
8763 }
8764 
8766 static void ResetNewGRFErrors()
8767 {
8768  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8769  c->error.reset();
8770  }
8771 }
8772 
8777 {
8778  CleanUpStrings();
8779  CleanUpGRFTownNames();
8780 
8781  /* Copy/reset original engine info data */
8782  SetupEngines();
8783 
8784  /* Copy/reset original bridge info data */
8785  ResetBridges();
8786 
8787  /* Reset rail type information */
8788  ResetRailTypes();
8789 
8790  /* Copy/reset original road type info data */
8791  ResetRoadTypes();
8792 
8793  /* Allocate temporary refit/cargo class data */
8794  _gted.resize(Engine::GetPoolSize());
8795 
8796  /* Fill rail type label temporary data for default trains */
8797  for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8798  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8799  }
8800 
8801  /* Reset GRM reservations */
8802  memset(&_grm_engines, 0, sizeof(_grm_engines));
8803  memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8804 
8805  /* Reset generic feature callback lists */
8807 
8808  /* Reset price base data */
8810 
8811  /* Reset the curencies array */
8812  ResetCurrencies();
8813 
8814  /* Reset the house array */
8816  ResetHouses();
8817 
8818  /* Reset the industries structures*/
8820  ResetIndustries();
8821 
8822  /* Reset the objects. */
8823  ObjectClass::Reset();
8825  ResetObjects();
8826 
8827  /* Reset station classes */
8828  StationClass::Reset();
8830 
8831  /* Reset airport-related structures */
8832  AirportClass::Reset();
8836 
8837  /* Reset road stop classes */
8838  RoadStopClass::Reset();
8839  ResetCustomRoadStops();
8840 
8841  /* Reset canal sprite groups and flags */
8842  memset(_water_feature, 0, sizeof(_water_feature));
8843 
8844  /* Reset the snowline table. */
8845  ClearSnowLine();
8846 
8847  /* Reset NewGRF files */
8848  ResetNewGRF();
8849 
8850  /* Reset NewGRF errors. */
8852 
8853  /* Set up the default cargo types */
8855 
8856  /* Reset misc GRF features and train list display variables */
8857  _misc_grf_features = 0;
8858 
8860  _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8863 
8864  /* Clear all GRF overrides */
8865  _grf_id_overrides.clear();
8866 
8867  InitializeSoundPool();
8868  _spritegroup_pool.CleanPool();
8869 }
8870 
8875 {
8876  /* Reset override managers */
8877  _engine_mngr.ResetToDefaultMapping();
8878  _house_mngr.ResetMapping();
8879  _industry_mngr.ResetMapping();
8880  _industile_mngr.ResetMapping();
8881  _airport_mngr.ResetMapping();
8882  _airporttile_mngr.ResetMapping();
8883 }
8884 
8890 {
8891  _cur.grffile->cargo_map.fill(UINT8_MAX);
8892 
8893  for (const CargoSpec *cs : CargoSpec::Iterate()) {
8894  if (!cs->IsValid()) continue;
8895 
8896  if (_cur.grffile->cargo_list.empty()) {
8897  /* Default translation table, so just a straight mapping to bitnum */
8898  _cur.grffile->cargo_map[cs->Index()] = cs->bitnum;
8899  } else {
8900  /* Check the translation table for this cargo's label */
8901  int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8902  if (idx >= 0) _cur.grffile->cargo_map[cs->Index()] = idx;
8903  }
8904  }
8905 }
8906 
8911 static void InitNewGRFFile(const GRFConfig *config)
8912 {
8913  GRFFile *newfile = GetFileByFilename(config->filename);
8914  if (newfile != nullptr) {
8915  /* We already loaded it once. */
8916  _cur.grffile = newfile;
8917  return;
8918  }
8919 
8920  newfile = new GRFFile(config);
8921  _grf_files.push_back(_cur.grffile = newfile);
8922 }
8923 
8929 {
8930  this->filename = config->filename;
8931  this->grfid = config->ident.grfid;
8932 
8933  /* Initialise local settings to defaults */
8934  this->traininfo_vehicle_pitch = 0;
8935  this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8936 
8937  /* Mark price_base_multipliers as 'not set' */
8938  for (Price i = PR_BEGIN; i < PR_END; i++) {
8939  this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8940  }
8941 
8942  /* Initialise rail type map with default rail types */
8943  std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8944  this->railtype_map[0] = RAILTYPE_RAIL;
8945  this->railtype_map[1] = RAILTYPE_ELECTRIC;
8946  this->railtype_map[2] = RAILTYPE_MONO;
8947  this->railtype_map[3] = RAILTYPE_MAGLEV;
8948 
8949  /* Initialise road type map with default road types */
8950  std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8951  this->roadtype_map[0] = ROADTYPE_ROAD;
8952 
8953  /* Initialise tram type map with default tram types */
8954  std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8955  this->tramtype_map[0] = ROADTYPE_TRAM;
8956 
8957  /* Copy the initial parameter list
8958  * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8959  this->param = config->param;
8960  this->param_end = config->num_params;
8961 }
8962 
8963 GRFFile::~GRFFile()
8964 {
8965  delete[] this->language_map;
8966 }
8967 
8973 static CargoLabel GetActiveCargoLabel(const std::initializer_list<CargoLabel> &labels)
8974 {
8975  for (const CargoLabel &label : labels) {
8976  CargoID cid = GetCargoIDByLabel(label);
8977  if (cid != INVALID_CARGO) return label;
8978  }
8979  return CT_INVALID;
8980 }
8981 
8987 static CargoLabel GetActiveCargoLabel(const std::variant<CargoLabel, MixedCargoType> &label)
8988 {
8989  if (std::holds_alternative<CargoLabel>(label)) return std::get<CargoLabel>(label);
8990  if (std::holds_alternative<MixedCargoType>(label)) {
8991  switch (std::get<MixedCargoType>(label)) {
8992  case MCT_LIVESTOCK_FRUIT: return GetActiveCargoLabel({CT_LIVESTOCK, CT_FRUIT});
8993  case MCT_GRAIN_WHEAT_MAIZE: return GetActiveCargoLabel({CT_GRAIN, CT_WHEAT, CT_MAIZE});
8994  case MCT_VALUABLES_GOLD_DIAMONDS: return GetActiveCargoLabel({CT_VALUABLES, CT_GOLD, CT_DIAMONDS});
8995  default: NOT_REACHED();
8996  }
8997  }
8998  NOT_REACHED();
8999 }
9000 
9004 static void CalculateRefitMasks()
9005 {
9006  CargoTypes original_known_cargoes = 0;
9007  for (CargoID cid = 0; cid != NUM_CARGO; ++cid) {
9008  if (IsDefaultCargo(cid)) SetBit(original_known_cargoes, cid);
9009  }
9010 
9011  for (Engine *e : Engine::Iterate()) {
9012  EngineID engine = e->index;
9013  EngineInfo *ei = &e->info;
9014  bool only_defaultcargo;
9015 
9016  /* Apply default cargo translation map if cargo type hasn't been set, either explicitly or by aircraft cargo handling. */
9017  if (!IsValidCargoID(e->info.cargo_type)) {
9018  e->info.cargo_type = GetCargoIDByLabel(GetActiveCargoLabel(e->info.cargo_label));
9019  }
9020 
9021  /* If the NewGRF did not set any cargo properties, we apply default values. */
9022  if (_gted[engine].defaultcargo_grf == nullptr) {
9023  /* If the vehicle has any capacity, apply the default refit masks */
9024  if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
9025  static constexpr byte T = 1 << LT_TEMPERATE;
9026  static constexpr byte A = 1 << LT_ARCTIC;
9027  static constexpr byte S = 1 << LT_TROPIC;
9028  static constexpr byte Y = 1 << LT_TOYLAND;
9029  static const struct DefaultRefitMasks {
9030  byte climate;
9031  CargoLabel cargo_label;
9032  CargoTypes cargo_allowed;
9033  CargoTypes cargo_disallowed;
9034  } _default_refit_masks[] = {
9035  {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
9036  {T | A | S , CT_MAIL, CC_MAIL, 0},
9037  {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
9038  { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
9039  {T | A , CT_COAL, CC_BULK, 0},
9040  { S , CT_COPPER_ORE, CC_BULK, 0},
9041  { Y, CT_SUGAR, CC_BULK, 0},
9042  {T | A | S , CT_OIL, CC_LIQUID, 0},
9043  { Y, CT_COLA, CC_LIQUID, 0},
9044  {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
9045  { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
9046  { A | S , CT_FOOD, CC_REFRIGERATED, 0},
9047  { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
9048  };
9049 
9050  if (e->type == VEH_AIRCRAFT) {
9051  /* Aircraft default to "light" cargoes */
9052  _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
9053  _gted[engine].cargo_disallowed = CC_LIQUID;
9054  } else if (e->type == VEH_SHIP) {
9055  CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
9056  switch (label.base()) {
9057  case CT_PASSENGERS.base():
9058  /* Ferries */
9059  _gted[engine].cargo_allowed = CC_PASSENGERS;
9060  _gted[engine].cargo_disallowed = 0;
9061  break;
9062  case CT_OIL.base():
9063  /* Tankers */
9064  _gted[engine].cargo_allowed = CC_LIQUID;
9065  _gted[engine].cargo_disallowed = 0;
9066  break;
9067  default:
9068  /* Cargo ships */
9069  if (_settings_game.game_creation.landscape == LT_TOYLAND) {
9070  /* No tanker in toyland :( */
9071  _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9072  _gted[engine].cargo_disallowed = CC_PASSENGERS;
9073  } else {
9074  _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
9075  _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
9076  }
9077  break;
9078  }
9079  e->u.ship.old_refittable = true;
9080  } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
9081  /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
9082  * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
9083  _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9084  _gted[engine].cargo_disallowed = 0;
9085  } else {
9086  /* Train wagons and road vehicles are classified by their default cargo type */
9087  CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
9088  for (const auto &drm : _default_refit_masks) {
9089  if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
9090  if (drm.cargo_label != label) continue;
9091 
9092  _gted[engine].cargo_allowed = drm.cargo_allowed;
9093  _gted[engine].cargo_disallowed = drm.cargo_disallowed;
9094  break;
9095  }
9096 
9097  /* All original cargoes have specialised vehicles, so exclude them */
9098  _gted[engine].ctt_exclude_mask = original_known_cargoes;
9099  }
9100  }
9101  _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
9102 
9103  if (IsValidCargoID(ei->cargo_type)) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
9104  }
9105 
9106  /* Compute refittability */
9107  {
9108  CargoTypes mask = 0;
9109  CargoTypes not_mask = 0;
9110  CargoTypes xor_mask = ei->refit_mask;
9111 
9112  /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
9113  * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
9114  only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
9115 
9116  if (_gted[engine].cargo_allowed != 0) {
9117  /* Build up the list of cargo types from the set cargo classes. */
9118  for (const CargoSpec *cs : CargoSpec::Iterate()) {
9119  if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
9120  if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
9121  }
9122  }
9123 
9124  ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
9125 
9126  /* Apply explicit refit includes/excludes. */
9127  ei->refit_mask |= _gted[engine].ctt_include_mask;
9128  ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
9129  }
9130 
9131  /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
9132  if (IsValidCargoID(ei->cargo_type) && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = INVALID_CARGO;
9133 
9134  /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
9135  * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
9136  if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && IsValidCargoID(ei->cargo_type) && !HasBit(ei->refit_mask, ei->cargo_type)) {
9137  ei->cargo_type = INVALID_CARGO;
9138  }
9139 
9140  /* Check if this engine's cargo type is valid. If not, set to the first refittable
9141  * cargo type. Finally disable the vehicle, if there is still no cargo. */
9142  if (!IsValidCargoID(ei->cargo_type) && ei->refit_mask != 0) {
9143  /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
9144  const GRFFile *file = _gted[engine].defaultcargo_grf;
9145  if (file == nullptr) file = e->GetGRF();
9146  if (file != nullptr && file->grf_version >= 8 && !file->cargo_list.empty()) {
9147  /* Use first refittable cargo from cargo translation table */
9148  byte best_local_slot = UINT8_MAX;
9149  for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
9150  byte local_slot = file->cargo_map[cargo_type];
9151  if (local_slot < best_local_slot) {
9152  best_local_slot = local_slot;
9153  ei->cargo_type = cargo_type;
9154  }
9155  }
9156  }
9157 
9158  if (!IsValidCargoID(ei->cargo_type)) {
9159  /* Use first refittable cargo slot */
9160  ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
9161  }
9162  }
9163  if (!IsValidCargoID(ei->cargo_type)) ei->climates = 0;
9164 
9165  /* Clear refit_mask for not refittable ships */
9166  if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
9167  ei->refit_mask = 0;
9168  }
9169  }
9170 }
9171 
9173 static void FinaliseCanals()
9174 {
9175  for (uint i = 0; i < CF_END; i++) {
9176  if (_water_feature[i].grffile != nullptr) {
9179  }
9180  }
9181 }
9182 
9184 static void FinaliseEngineArray()
9185 {
9186  for (Engine *e : Engine::Iterate()) {
9187  if (e->GetGRF() == nullptr) {
9188  const EngineIDMapping &eid = _engine_mngr[e->index];
9189  if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
9190  e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
9191  }
9192  }
9193 
9194  /* Do final mapping on variant engine ID. */
9195  if (e->info.variant_id != INVALID_ENGINE) {
9196  e->info.variant_id = GetNewEngineID(e->grf_prop.grffile, e->type, e->info.variant_id);
9197  }
9198 
9199  if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
9200 
9201  /* Skip wagons, there livery is defined via the engine */
9202  if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
9205  /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9206 
9207  if (e->type == VEH_TRAIN) {
9208  SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
9209  switch (ls) {
9210  case LS_STEAM:
9211  case LS_DIESEL:
9212  case LS_ELECTRIC:
9213  case LS_MONORAIL:
9214  case LS_MAGLEV:
9215  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
9216  break;
9217 
9218  case LS_DMU:
9219  case LS_EMU:
9220  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
9221  break;
9222 
9223  default: NOT_REACHED();
9224  }
9225  }
9226  }
9227  }
9228 
9229  /* Check engine variants don't point back on themselves (either directly or via a loop) then set appropriate flags
9230  * on variant engine. This is performed separately as all variant engines need to have been resolved. */
9231  for (Engine *e : Engine::Iterate()) {
9232  EngineID parent = e->info.variant_id;
9233  while (parent != INVALID_ENGINE) {
9234  parent = Engine::Get(parent)->info.variant_id;
9235  if (parent != e->index) continue;
9236 
9237  /* Engine looped back on itself, so clear the variant. */
9238  e->info.variant_id = INVALID_ENGINE;
9239 
9240  GrfMsg(1, "FinaliseEngineArray: Variant of engine {:x} in '{}' loops back on itself", _engine_mngr[e->index].internal_id, e->GetGRF()->filename);
9241  break;
9242  }
9243 
9244  if (e->info.variant_id != INVALID_ENGINE) {
9246  }
9247  }
9248 }
9249 
9252 {
9253  for (CargoSpec &cs : CargoSpec::array) {
9254  if (cs.town_production_effect == INVALID_TPE) {
9255  /* Set default town production effect by cargo label. */
9256  switch (cs.label.base()) {
9257  case CT_PASSENGERS.base(): cs.town_production_effect = TPE_PASSENGERS; break;
9258  case CT_MAIL.base(): cs.town_production_effect = TPE_MAIL; break;
9259  default: cs.town_production_effect = TPE_NONE; break;
9260  }
9261  }
9262  if (!cs.IsValid()) {
9263  cs.name = cs.name_single = cs.units_volume = STR_NEWGRF_INVALID_CARGO;
9264  cs.quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9265  cs.abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9266  }
9267  }
9268 }
9269 
9281 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const std::string &filename)
9282 {
9283  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9284  (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9285  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9286  (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9287  next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9288  hs->enabled = false;
9289  if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9290  return false;
9291  }
9292 
9293  /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9294  * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9295  * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9296  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9297  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9298  hs->enabled = false;
9299  if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines multitile house {} with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
9300  return false;
9301  }
9302 
9303  /* Substitute type is also used for override, and having an override with a different size causes crashes.
9304  * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9305  if (!filename.empty() && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9306  hs->enabled = false;
9307  Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9308  return false;
9309  }
9310 
9311  /* Make sure that additional parts of multitile houses are not available. */
9312  if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9313  hs->enabled = false;
9314  if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
9315  return false;
9316  }
9317 
9318  return true;
9319 }
9320 
9327 static void EnsureEarlyHouse(HouseZones bitmask)
9328 {
9330 
9331  for (int i = 0; i < NUM_HOUSES; i++) {
9332  HouseSpec *hs = HouseSpec::Get(i);
9333  if (hs == nullptr || !hs->enabled) continue;
9334  if ((hs->building_availability & bitmask) != bitmask) continue;
9335  if (hs->min_year < min_year) min_year = hs->min_year;
9336  }
9337 
9338  if (min_year == 0) return;
9339 
9340  for (int i = 0; i < NUM_HOUSES; i++) {
9341  HouseSpec *hs = HouseSpec::Get(i);
9342  if (hs == nullptr || !hs->enabled) continue;
9343  if ((hs->building_availability & bitmask) != bitmask) continue;
9344  if (hs->min_year == min_year) hs->min_year = 0;
9345  }
9346 }
9347 
9354 static void FinaliseHouseArray()
9355 {
9356  /* If there are no houses with start dates before 1930, then all houses
9357  * with start dates of 1930 have them reset to 0. This is in order to be
9358  * compatible with TTDPatch, where if no houses have start dates before
9359  * 1930 and the date is before 1930, the game pretends that this is 1930.
9360  * If there have been any houses defined with start dates before 1930 then
9361  * the dates are left alone.
9362  * On the other hand, why 1930? Just 'fix' the houses with the lowest
9363  * minimum introduction date to 0.
9364  */
9365  for (GRFFile * const file : _grf_files) {
9366  if (file->housespec.empty()) continue;
9367 
9368  size_t num_houses = file->housespec.size();
9369  for (size_t i = 0; i < num_houses; i++) {
9370  HouseSpec *hs = file->housespec[i].get();
9371 
9372  if (hs == nullptr) continue;
9373 
9374  const HouseSpec *next1 = (i + 1 < num_houses ? file->housespec[i + 1].get() : nullptr);
9375  const HouseSpec *next2 = (i + 2 < num_houses ? file->housespec[i + 2].get() : nullptr);
9376  const HouseSpec *next3 = (i + 3 < num_houses ? file->housespec[i + 3].get() : nullptr);
9377 
9378  if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9379 
9380  _house_mngr.SetEntitySpec(hs);
9381  }
9382  }
9383 
9384  for (size_t i = 0; i < NUM_HOUSES; i++) {
9385  HouseSpec *hs = HouseSpec::Get(i);
9386  const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9387  const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9388  const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9389 
9390  /* We need to check all houses again to we are sure that multitile houses
9391  * did get consecutive IDs and none of the parts are missing. */
9392  if (!IsHouseSpecValid(hs, next1, next2, next3, std::string{})) {
9393  /* GetHouseNorthPart checks 3 houses that are directly before
9394  * it in the house pool. If any of those houses have multi-tile
9395  * flags set it assumes it's part of a multitile house. Since
9396  * we can have invalid houses in the pool marked as disabled, we
9397  * don't want to have them influencing valid tiles. As such set
9398  * building_flags to zero here to make sure any house following
9399  * this one in the pool is properly handled as 1x1 house. */
9400  hs->building_flags = TILE_NO_FLAG;
9401  }
9402 
9403  /* Apply default cargo translation map for unset cargo slots */
9404  for (uint i = 0; i < lengthof(hs->accepts_cargo); ++i) {
9405  if (!IsValidCargoID(hs->accepts_cargo[i])) hs->accepts_cargo[i] = GetCargoIDByLabel(hs->accepts_cargo_label[i]);
9406  /* Disable acceptance if cargo type is invalid. */
9407  if (!IsValidCargoID(hs->accepts_cargo[i])) hs->cargo_acceptance[i] = 0;
9408  }
9409  }
9410 
9411  HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9412  EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9413  EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9414  EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9415  EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9416  EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9417 
9418  if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9424  }
9425 }
9426 
9433 {
9434  for (GRFFile * const file : _grf_files) {
9435  for (const auto &indsp : file->industryspec) {
9436  if (indsp == nullptr || !indsp->enabled) continue;
9437 
9438  StringID strid;
9439  /* process the conversion of text at the end, so to be sure everything will be fine
9440  * and available. Check if it does not return undefind marker, which is a very good sign of a
9441  * substitute industry who has not changed the string been examined, thus using it as such */
9442  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9443  if (strid != STR_UNDEFINED) indsp->name = strid;
9444 
9445  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9446  if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9447 
9448  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9449  if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9450 
9451  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9452  if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9453 
9454  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9455  if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9456 
9457  if (indsp->station_name != STR_NULL) {
9458  /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9459  * station's name. Don't want to lose the value, therefore, do not process. */
9460  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9461  if (strid != STR_UNDEFINED) indsp->station_name = strid;
9462  }
9463 
9464  _industry_mngr.SetEntitySpec(indsp.get());
9465  }
9466 
9467  for (const auto &indtsp : file->indtspec) {
9468  if (indtsp != nullptr) {
9469  _industile_mngr.SetEntitySpec(indtsp.get());
9470  }
9471  }
9472  }
9473 
9474  for (auto &indsp : _industry_specs) {
9475  if (indsp.enabled && indsp.grf_prop.grffile != nullptr) {
9476  for (auto &conflicting : indsp.conflicting) {
9477  conflicting = MapNewGRFIndustryType(conflicting, indsp.grf_prop.grffile->grfid);
9478  }
9479  }
9480  if (!indsp.enabled) {
9481  indsp.name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9482  }
9483 
9484  /* Apply default cargo translation map for unset cargo slots */
9485  for (uint i = 0; i < lengthof(indsp.produced_cargo); ++i) {
9486  if (!IsValidCargoID(indsp.produced_cargo[i])) indsp.produced_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.produced_cargo_label[i]));
9487  }
9488  for (uint i = 0; i < lengthof(indsp.accepts_cargo); ++i) {
9489  if (!IsValidCargoID(indsp.accepts_cargo[i])) indsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.accepts_cargo_label[i]));
9490  }
9491  }
9492 
9493  for (auto &indtsp : _industry_tile_specs) {
9494  /* Apply default cargo translation map for unset cargo slots */
9495  for (uint i = 0; i < lengthof(indtsp.accepts_cargo); ++i) {
9496  if (!IsValidCargoID(indtsp.accepts_cargo[i])) indtsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indtsp.accepts_cargo_label[i]));
9497  }
9498  }
9499 }
9500 
9507 {
9508  for (GRFFile * const file : _grf_files) {
9509  for (auto &objectspec : file->objectspec) {
9510  if (objectspec != nullptr && objectspec->grf_prop.grffile != nullptr && objectspec->IsEnabled()) {
9511  _object_mngr.SetEntitySpec(objectspec.get());
9512  }
9513  }
9514  }
9515 
9517 }
9518 
9525 {
9526  for (GRFFile * const file : _grf_files) {
9527  for (auto &as : file->airportspec) {
9528  if (as != nullptr && as->enabled) {
9529  _airport_mngr.SetEntitySpec(as.get());
9530  }
9531  }
9532 
9533  for (auto &ats : file->airtspec) {
9534  if (ats != nullptr && ats->enabled) {
9535  _airporttile_mngr.SetEntitySpec(ats.get());
9536  }
9537  }
9538  }
9539 }
9540 
9541 /* Here we perform initial decoding of some special sprites (as are they
9542  * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9543  * partial implementation yet).
9544  * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9545  * a crafted invalid GRF file. We should tell that to the user somehow, or
9546  * better make this more robust in the future. */
9547 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
9548 {
9549  /* XXX: There is a difference between staged loading in TTDPatch and
9550  * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9551  * during stage 1, whilst action 3 is carried out during stage 2 (to
9552  * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9553  * IDs are valid only within a given set (action 1) block, and may be
9554  * overwritten after action 3 associates them. But overwriting happens
9555  * in an earlier stage than associating, so... We just process actions
9556  * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9557  * --pasky
9558  * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9559  * is not in memory and scanning the file every time would be too expensive.
9560  * In other stages we skip action 0x10 since it's already dealt with. */
9561  static const SpecialSpriteHandler handlers[][GLS_END] = {
9562  /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9563  /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9564  /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9565  /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9566  /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9567  /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9568  /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9569  /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9570  /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9571  /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9572  /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9573  /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9574  /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9575  /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9576  /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9577  /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9578  /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9579  /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9581  /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9582  /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9583  };
9584 
9585  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9586 
9587  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9588  if (it == _grf_line_to_action6_sprite_override.end()) {
9589  /* No preloaded sprite to work with; read the
9590  * pseudo sprite content. */
9591  _cur.file->ReadBlock(buf, num);
9592  } else {
9593  /* Use the preloaded sprite data. */
9594  buf = _grf_line_to_action6_sprite_override[location].data();
9595  GrfMsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9596 
9597  /* Skip the real (original) content of this action. */
9598  _cur.file->SeekTo(num, SEEK_CUR);
9599  }
9600 
9601  ByteReader br(buf, buf + num);
9602  ByteReader *bufp = &br;
9603 
9604  try {
9605  byte action = bufp->ReadByte();
9606 
9607  if (action == 0xFF) {
9608  GrfMsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9609  } else if (action == 0xFE) {
9610  GrfMsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9611  } else if (action >= lengthof(handlers)) {
9612  GrfMsg(7, "DecodeSpecialSprite: Skipping unknown action 0x{:02X}", action);
9613  } else if (handlers[action][stage] == nullptr) {
9614  GrfMsg(7, "DecodeSpecialSprite: Skipping action 0x{:02X} in stage {}", action, stage);
9615  } else {
9616  GrfMsg(7, "DecodeSpecialSprite: Handling action 0x{:02X} in stage {}", action, stage);
9617  handlers[action][stage](bufp);
9618  }
9619  } catch (...) {
9620  GrfMsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9621  DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9622  }
9623 }
9624 
9631 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9632 {
9633  _cur.file = &file;
9634  _cur.grfconfig = config;
9635 
9636  Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9637 
9638  byte grf_container_version = file.GetContainerVersion();
9639  if (grf_container_version == 0) {
9640  Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9641  return;
9642  }
9643 
9644  if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9645  /* We need the sprite offsets in the init stage for NewGRF sounds
9646  * and in the activation stage for real sprites. */
9647  ReadGRFSpriteOffsets(file);
9648  } else {
9649  /* Skip sprite section offset if present. */
9650  if (grf_container_version >= 2) file.ReadDword();
9651  }
9652 
9653  if (grf_container_version >= 2) {
9654  /* Read compression value. */
9655  byte compression = file.ReadByte();
9656  if (compression != 0) {
9657  Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9658  return;
9659  }
9660  }
9661 
9662  /* Skip the first sprite; we don't care about how many sprites this
9663  * does contain; newest TTDPatches and George's longvehicles don't
9664  * neither, apparently. */
9665  uint32_t num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9666  if (num == 4 && file.ReadByte() == 0xFF) {
9667  file.ReadDword();
9668  } else {
9669  Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9670  return;
9671  }
9672 
9673  _cur.ClearDataForNextFile();
9674 
9676 
9677  while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9678  byte type = file.ReadByte();
9679  _cur.nfo_line++;
9680 
9681  if (type == 0xFF) {
9682  if (_cur.skip_sprites == 0) {
9683  DecodeSpecialSprite(buf.Allocate(num), num, stage);
9684 
9685  /* Stop all processing if we are to skip the remaining sprites */
9686  if (_cur.skip_sprites == -1) break;
9687 
9688  continue;
9689  } else {
9690  file.SkipBytes(num);
9691  }
9692  } else {
9693  if (_cur.skip_sprites == 0) {
9694  GrfMsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9695  DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9696  break;
9697  }
9698 
9699  if (grf_container_version >= 2 && type == 0xFD) {
9700  /* Reference to data section. Container version >= 2 only. */
9701  file.SkipBytes(num);
9702  } else {
9703  file.SkipBytes(7);
9704  SkipSpriteData(file, type, num - 8);
9705  }
9706  }
9707 
9708  if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9709  }
9710 }
9711 
9720 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9721 {
9722  const std::string &filename = config->filename;
9723 
9724  /* A .grf file is activated only if it was active when the game was
9725  * started. If a game is loaded, only its active .grfs will be
9726  * reactivated, unless "loadallgraphics on" is used. A .grf file is
9727  * considered active if its action 8 has been processed, i.e. its
9728  * action 8 hasn't been skipped using an action 7.
9729  *
9730  * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9731  * carried out. All others are ignored, because they only need to be
9732  * processed once at initialization. */
9733  if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9734  _cur.grffile = GetFileByFilename(filename);
9735  if (_cur.grffile == nullptr) UserError("File '{}' lost in cache.\n", filename);
9736  if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9737  if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9738  }
9739 
9740  bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9741  if (temporary) {
9742  SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9743  LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9744  } else {
9745  LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9746  }
9747 }
9748 
9756 static void ActivateOldShore()
9757 {
9758  /* Use default graphics, if no shore sprites were loaded.
9759  * Should not happen, as the base set's extra grf should include some. */
9761 
9763  DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9764  DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9765  DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9766  DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9767  DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9768  DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9769  DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9770  DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9771  }
9772 
9774  DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9775  DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9776  DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9777  DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9778  DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9779  DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9780  DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9781  DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9782 
9783  /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9784  * If they would be used somewhen, then these grass tiles will most like not look as needed */
9785  DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9786  DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9787  }
9788 }
9789 
9794 {
9796  DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9797  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9798  DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9799  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9800  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9801  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9802  }
9803 }
9804 
9809 {
9810  extern const PriceBaseSpec _price_base_specs[];
9812  static const uint32_t override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9813 
9814  /* Evaluate grf overrides */
9815  int num_grfs = (uint)_grf_files.size();
9816  std::vector<int> grf_overrides(num_grfs, -1);
9817  for (int i = 0; i < num_grfs; i++) {
9818  GRFFile *source = _grf_files[i];
9819  uint32_t override = _grf_id_overrides[source->grfid];
9820  if (override == 0) continue;
9821 
9822  GRFFile *dest = GetFileByGRFID(override);
9823  if (dest == nullptr) continue;
9824 
9825  grf_overrides[i] = find_index(_grf_files, dest);
9826  assert(grf_overrides[i] >= 0);
9827  }
9828 
9829  /* Override features and price base multipliers of earlier loaded grfs */
9830  for (int i = 0; i < num_grfs; i++) {
9831  if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9832  GRFFile *source = _grf_files[i];
9833  GRFFile *dest = _grf_files[grf_overrides[i]];
9834 
9835  uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9836  source->grf_features |= features;
9837  dest->grf_features |= features;
9838 
9839  for (Price p = PR_BEGIN; p < PR_END; p++) {
9840  /* No price defined -> nothing to do */
9841  if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9842  Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9843  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9844  }
9845  }
9846 
9847  /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9848  for (int i = num_grfs - 1; i >= 0; i--) {
9849  if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9850  GRFFile *source = _grf_files[i];
9851  GRFFile *dest = _grf_files[grf_overrides[i]];
9852 
9853  uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9854  source->grf_features |= features;
9855  dest->grf_features |= features;
9856 
9857  for (Price p = PR_BEGIN; p < PR_END; p++) {
9858  /* Already a price defined -> nothing to do */
9859  if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9860  Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9861  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9862  }
9863  }
9864 
9865  /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9866  for (int i = 0; i < num_grfs; i++) {
9867  if (grf_overrides[i] < 0) continue;
9868  GRFFile *source = _grf_files[i];
9869  GRFFile *dest = _grf_files[grf_overrides[i]];
9870 
9871  uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9872  source->grf_features |= features;
9873  dest->grf_features |= features;
9874 
9875  for (Price p = PR_BEGIN; p < PR_END; p++) {
9876  if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9877  if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9878  Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9879  }
9880  source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9881  }
9882  }
9883 
9884  /* Apply fallback prices for grf version < 8 */
9885  for (GRFFile * const file : _grf_files) {
9886  if (file->grf_version >= 8) continue;
9887  PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9888  for (Price p = PR_BEGIN; p < PR_END; p++) {
9889  Price fallback_price = _price_base_specs[p].fallback_price;
9890  if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9891  /* No price multiplier has been set.
9892  * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9893  price_base_multipliers[p] = price_base_multipliers[fallback_price];
9894  }
9895  }
9896  }
9897 
9898  /* Decide local/global scope of price base multipliers */
9899  for (GRFFile * const file : _grf_files) {
9900  PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9901  for (Price p = PR_BEGIN; p < PR_END; p++) {
9902  if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9903  /* No multiplier was set; set it to a neutral value */
9904  price_base_multipliers[p] = 0;
9905  } else {
9906  if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9907  /* The grf does not define any objects of the feature,
9908  * so it must be a difficulty setting. Apply it globally */
9909  Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9910  SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9911  price_base_multipliers[p] = 0;
9912  } else {
9913  Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9914  }
9915  }
9916  }
9917  }
9918 }
9919 
9920 extern void InitGRFTownGeneratorNames();
9921 
9923 static void AfterLoadGRFs()
9924 {
9925  for (StringIDMapping &it : _string_to_grf_mapping) {
9926  *it.target = MapGRFStringID(it.grfid, it.source);
9927  }
9928  _string_to_grf_mapping.clear();
9929 
9930  /* Clear the action 6 override sprites. */
9931  _grf_line_to_action6_sprite_override.clear();
9932 
9933  /* Polish cargoes */
9935 
9936  /* Pre-calculate all refit masks after loading GRF files. */
9938 
9939  /* Polish engines */
9941 
9942  /* Set the actually used Canal properties */
9943  FinaliseCanals();
9944 
9945  /* Add all new houses to the house array. */
9947 
9948  /* Add all new industries to the industry array. */
9950 
9951  /* Add all new objects to the object array. */
9953 
9955 
9956  /* Sort the list of industry types. */
9958 
9959  /* Create dynamic list of industry legends for smallmap_gui.cpp */
9961 
9962  /* Build the routemap legend, based on the available cargos */
9964 
9965  /* Add all new airports to the airports array. */
9967  BindAirportSpecs();
9968 
9969  /* Update the townname generators list */
9971 
9972  /* Run all queued vehicle list order changes */
9974 
9975  /* Load old shore sprites in new position, if they were replaced by ActionA */
9976  ActivateOldShore();
9977 
9978  /* Load old tram depot sprites in new position, if no new ones are present */
9980 
9981  /* Set up custom rail types */
9982  InitRailTypes();
9983  InitRoadTypes();
9984 
9985  for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9986  if (_gted[e->index].rv_max_speed != 0) {
9987  /* Set RV maximum speed from the mph/0.8 unit value */
9988  e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9989  }
9990 
9991  RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9992 
9993  const GRFFile *file = e->GetGRF();
9994  if (file == nullptr || _gted[e->index].roadtramtype == 0) {
9995  e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
9996  continue;
9997  }
9998 
9999  /* Remove +1 offset. */
10000  _gted[e->index].roadtramtype--;
10001 
10002  const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
10003  if (_gted[e->index].roadtramtype < list->size())
10004  {
10005  RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
10006  RoadType rt = GetRoadTypeByLabel(rtl);
10007  if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
10008  e->u.road.roadtype = rt;
10009  continue;
10010  }
10011  }
10012 
10013  /* Road type is not available, so disable this engine */
10014  e->info.climates = 0;
10015  }
10016 
10017  for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
10018  RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
10019  if (railtype == INVALID_RAILTYPE) {
10020  /* Rail type is not available, so disable this engine */
10021  e->info.climates = 0;
10022  } else {
10023  e->u.rail.railtype = railtype;
10024  e->u.rail.intended_railtype = railtype;
10025  }
10026  }
10027 
10029 
10031 
10032  /* Deallocate temporary loading data */
10033  _gted.clear();
10034  _grm_sprites.clear();
10035 }
10036 
10042 void LoadNewGRF(uint load_index, uint num_baseset)
10043 {
10044  /* In case of networking we need to "sync" the start values
10045  * so all NewGRFs are loaded equally. For this we use the
10046  * start date of the game and we set the counters, etc. to
10047  * 0 so they're the same too. */
10048  TimerGameCalendar::Date date = TimerGameCalendar::date;
10051 
10052  TimerGameEconomy::Date economy_date = TimerGameEconomy::date;
10053  TimerGameEconomy::Year economy_year = TimerGameEconomy::year;
10055 
10056  uint64_t tick_counter = TimerGameTick::counter;
10057  byte display_opt = _display_opt;
10058 
10059  if (_networking) {
10063 
10067 
10069  _display_opt = 0;
10070  }
10071 
10073 
10074  ResetNewGRFData();
10075 
10076  /*
10077  * Reset the status of all files, so we can 'retry' to load them.
10078  * This is needed when one for example rearranges the NewGRFs in-game
10079  * and a previously disabled NewGRF becomes usable. If it would not
10080  * be reset, the NewGRF would remain disabled even though it should
10081  * have been enabled.
10082  */
10083  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10084  if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
10085  }
10086 
10087  _cur.spriteid = load_index;
10088 
10089  /* Load newgrf sprites
10090  * in each loading stage, (try to) open each file specified in the config
10091  * and load information from it. */
10092  for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
10093  /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
10094  * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
10095  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10096  if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
10097  }
10098 
10099  if (stage == GLS_RESERVE) {
10100  static const uint32_t overrides[][2] = {
10101  { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
10102  { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
10103  { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
10104  };
10105  for (size_t i = 0; i < lengthof(overrides); i++) {
10106  SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
10107  }
10108  }
10109 
10110  uint num_grfs = 0;
10111  uint num_non_static = 0;
10112 
10113  _cur.stage = stage;
10114  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10115  if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
10116  if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
10117 
10118  Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
10119  if (!FioCheckFileExists(c->filename, subdir)) {
10120  Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
10121  c->status = GCS_NOT_FOUND;
10122  continue;
10123  }
10124 
10125  if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
10126 
10127  if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
10128  if (num_non_static == NETWORK_MAX_GRF_COUNT) {
10129  Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
10130  c->status = GCS_DISABLED;
10131  c->error = {STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED};
10132  continue;
10133  }
10134  num_non_static++;
10135  }
10136 
10137  num_grfs++;
10138 
10139  LoadNewGRFFile(c, stage, subdir, false);
10140  if (stage == GLS_RESERVE) {
10141  SetBit(c->flags, GCF_RESERVED);
10142  } else if (stage == GLS_ACTIVATION) {
10143  ClrBit(c->flags, GCF_RESERVED);
10144  assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
10147  Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
10148  } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
10149  /* We're not going to activate this, so free whatever data we allocated */
10151  }
10152  }
10153  }
10154 
10155  /* Pseudo sprite processing is finished; free temporary stuff */
10156  _cur.ClearDataForNextFile();
10157 
10158  /* Call any functions that should be run after GRFs have been loaded. */
10159  AfterLoadGRFs();
10160 
10161  /* Now revert back to the original situation */
10162  TimerGameCalendar::year = year;
10163  TimerGameCalendar::date = date;
10164  TimerGameCalendar::date_fract = date_fract;
10165 
10166  TimerGameEconomy::year = economy_year;
10167  TimerGameEconomy::date = economy_date;
10168  TimerGameEconomy::date_fract = economy_date_fract;
10169 
10170  TimerGameTick::counter = tick_counter;
10171  _display_opt = display_opt;
10172 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
ResetCustomHouses
static void ResetCustomHouses()
Reset and clear all NewGRF houses.
Definition: newgrf.cpp:8702
RoadTypeInfo::flags
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:127
ChangeGRFName
static bool ChangeGRFName(byte langid, const char *str)
Callback function for 'INFO'->'NAME' to add a translation to the newgrf name.
Definition: newgrf.cpp:8098
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:8378
RoadTypeInfo::new_engine
StringID new_engine
Name of an engine for this type of road in the engine preview GUI.
Definition: road.h:108
StationChangeInfo
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
Define properties for stations.
Definition: newgrf.cpp:1910
ParamSet
static void ParamSet(ByteReader *buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:7391
GRFLocation
Definition: newgrf.cpp:362
CalculateRefitMasks
static void CalculateRefitMasks()
Precalculate refit masks from cargo classes for all vehicles.
Definition: newgrf.cpp:9004
OBJECT_SIZE_1X1
static const uint8_t OBJECT_SIZE_1X1
The value of a NewGRF's size property when the object is 1x1 tiles: low nibble for X,...
Definition: newgrf_object.h:43
GRFP_USE_MASK
@ GRFP_USE_MASK
Bitmask to get only the use palette use states.
Definition: newgrf_config.h:68
RoadTypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: road.h:104
HouseSpec::removal_cost
byte removal_cost
cost multiplier for removing it
Definition: house.h:103
RoadStopSpec::clear_cost_multiplier
uint8_t clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_roadstop.h:147
AllocateSound
SoundEntry * AllocateSound(uint num)
Allocate sound slots.
Definition: newgrf_sound.cpp:31
RailVehicleInfo::pow_wag_power
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:56
GRFTempEngineData::UpdateRefittability
void UpdateRefittability(bool non_empty)
Update the summary refittability on setting a refittability property.
Definition: newgrf.cpp:341
RailVehicleInfo::curve_speed_mod
int16_t curve_speed_mod
Modifier to maximum speed in curves (fixed-point binary with 8 fractional bits)
Definition: engine_type.h:63
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:206
Action5Type::sprite_base
SpriteID sprite_base
Load the sprites starting from this sprite.
Definition: newgrf.cpp:6401
OrderSettings::improved_load
bool improved_load
improved loading algorithm
Definition: settings_type.h:506
GRFTownName::styles
std::vector< TownNameStyle > styles
Style names defined by the Town Name NewGRF.
Definition: newgrf_townname.h:42
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:25
RoadTypeInfo
Definition: road.h:78
DuplicateTileTable
static void DuplicateTileTable(AirportSpec *as)
Create a copy of the tile table so it can be freed later without problems.
Definition: newgrf.cpp:3867
NUM_STATIONS_PER_GRF
static const uint NUM_STATIONS_PER_GRF
The maximum amount of stations a single GRF is allowed to add.
Definition: newgrf.cpp:316
PROP_TRAIN_SPEED
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
Definition: newgrf_properties.h:21
GRFConfig::info
GRFTextWrapper info
NOSAVE: GRF info (author, copyright, ...) (Action 0x08)
Definition: newgrf_config.h:158
AllowedSubtags::AllowedSubtags
AllowedSubtags()
Create empty subtags object used to identify the end of a list.
Definition: newgrf.cpp:8313
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:29
RAILTYPE_MAGLEV
@ RAILTYPE_MAGLEV
Maglev.
Definition: rail_type.h:32
RailTypeInfo::introduction_date
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: rail.h:255
ResetCustomObjects
static void ResetCustomObjects()
Reset and clear all NewObjects.
Definition: newgrf.cpp:8740
RoadStopAvailabilityType
RoadStopAvailabilityType
Various different options for availability, restricting the roadstop to be only for busses or for tru...
Definition: newgrf_roadstop.h:46
RailVehicleInfo::pow_wag_weight
byte pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition: engine_type.h:57
Engine::IterateType
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
Definition: engine_base.h:186
IndustrySpec::map_colour
byte map_colour
colour used for the small map
Definition: industrytype.h:126
EngineDisplayFlags::HasVariants
@ HasVariants
Set if engine has variants.
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
TPE_NONE
@ TPE_NONE
Town will not produce this cargo type.
Definition: cargotype.h:35
LanguageMetadata
Make sure the size is right.
Definition: language.h:93
VE_DISABLE_EFFECT
@ VE_DISABLE_EFFECT
Flag to disable visual effect.
Definition: vehicle_base.h:91
MCT_GRAIN_WHEAT_MAIZE
@ MCT_GRAIN_WHEAT_MAIZE
Cargo can be grain, wheat or maize.
Definition: cargo_type.h:85
newgrf_station.h
SetUnicodeGlyph
void SetUnicodeGlyph(FontSize size, char32_t key, SpriteID sprite)
Map a SpriteID to the font size and key.
Definition: fontcache.h:167
newgrf_house.h
TPE_MAIL
@ TPE_MAIL
Cargo behaves mail-like for production.
Definition: cargotype.h:37
GRFFile::language_map
struct LanguageMap * language_map
Mappings related to the languages.
Definition: newgrf.h:143
GRFFile::roadtype_list
std::vector< RoadTypeLabel > roadtype_list
Roadtype translation table (road)
Definition: newgrf.h:135
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
EngineOverrideManager::ResetToDefaultMapping
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition: engine.cpp:509
CargoSpec::label
CargoLabel label
Unique label of the cargo type.
Definition: cargotype.h:69
AircraftVehicleInfo::max_range
uint16_t max_range
Maximum range of this aircraft.
Definition: engine_type.h:110
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition: timer_game_tick.h:33
StationSpec::flags
byte flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Definition: newgrf_station.h:159
OBJECT_FLAG_2CC_COLOUR
@ OBJECT_FLAG_2CC_COLOUR
Object wants 2CC colour mapping.
Definition: newgrf_object.h:34
LanguageMap::case_map
std::vector< Mapping > case_map
Mapping of NewGRF and OpenTTD IDs for cases.
Definition: newgrf_text.h:67
PROP_TRAIN_CARGO_CAPACITY
@ PROP_TRAIN_CARGO_CAPACITY
Capacity (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:24
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:630
ResetCustomAirports
static void ResetCustomAirports()
Reset and clear all NewGRF airports.
Definition: newgrf.cpp:8710
AircraftVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
Definition: engine_type.h:107
GRFTextList
std::vector< GRFText > GRFTextList
A GRF text with a list of translations.
Definition: newgrf_text.h:28
PROP_ROADVEH_TRACTIVE_EFFORT
@ PROP_ROADVEH_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
Definition: newgrf_properties.h:39
SNOW_LINE_DAYS
static const uint SNOW_LINE_DAYS
Number of days in each month in the snow line table.
Definition: landscape.h:17
ObjectChangeInfo
static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for objects.
Definition: newgrf.cpp:4117
RoadTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: road.h:105
TimerGameConst< struct Calendar >::DAYS_TILL_ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
The date of the first day of the original base year.
Definition: timer_game_common.h:184
GetFileByGRFID
static GRFFile * GetFileByGRFID(uint32_t grfid)
Obtain a NewGRF file by its grfID.
Definition: newgrf.cpp:403
DeterministicSpriteGroupRange
Definition: newgrf_spritegroup.h:160
GRFConfig::num_valid_params
uint8_t num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
Definition: newgrf_config.h:169
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition: newgrf_station.h:147
NUM_INDUSTRYTYPES_PER_GRF
static const IndustryType NUM_INDUSTRYTYPES_PER_GRF
maximum number of industry types per NewGRF; limited to 128 because bit 7 has a special meaning in so...
Definition: industry_type.h:23
SPR_SHORE_BASE
static const SpriteID SPR_SHORE_BASE
shore tiles - action 05-0D
Definition: sprites.h:224
IndustryProductionSpriteGroup::num_output
uint8_t num_output
How many add_output values are valid.
Definition: newgrf_spritegroup.h:275
TAE_FOOD
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:28
TLF_DODRAW
@ TLF_DODRAW
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
Definition: newgrf_commons.h:35
ReusableBuffer
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition: alloc_type.hpp:24
AircraftVehicleInfo::subtype
byte subtype
Type of aircraft.
Definition: engine_type.h:104
ShipVehicleChangeInfo
static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for ships.
Definition: newgrf.cpp:1553
GetRoadTypeByLabel
RoadType GetRoadTypeByLabel(RoadTypeLabel label, bool allow_alternate_labels)
Get the road type for a given label.
Definition: road.cpp:254
GRFError::custom_message
std::string custom_message
Custom message (if present)
Definition: newgrf_config.h:112
PROP_ROADVEH_COST_FACTOR
@ PROP_ROADVEH_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:35
IsInsideMM
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:268
GCS_ACTIVATED
@ GCS_ACTIVATED
GRF file has been activated.
Definition: newgrf_config.h:39
ObjectSpec
Allow incrementing of ObjectClassID variables.
Definition: newgrf_object.h:60
RoadStopSpec
Road stop specification.
Definition: newgrf_roadstop.h:122
TileLayoutRegisters::dodraw
uint8_t dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
Definition: newgrf_commons.h:92
ObjectSpec::grf_prop
GRFFilePropsBase< 2 > grf_prop
Properties related the the grf file.
Definition: newgrf_object.h:62
GrfProcessingState::grffile
GRFFile * grffile
Currently processed GRF file.
Definition: newgrf.cpp:105
DrawTileSeqStruct::IsParentSprite
bool IsParentSprite() const
Check whether this is a parent sprite with a boundingbox.
Definition: sprite.h:47
BridgeSpec::flags
byte flags
bit 0 set: disable drawing of far pillars.
Definition: bridge.h:53
RoadTypeInfo::introduction_date
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: road.h:166
NamePartList::maxprob
uint16_t maxprob
Total probability of all parts.
Definition: newgrf_townname.h:27
_engine_offsets
const uint8_t _engine_offsets[4]
Offset of the first engine of each vehicle type in original engine data.
Definition: engine.cpp:61
GetRailTypeInfo
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:307
IsValidNewGRFImageIndex
static bool IsValidNewGRFImageIndex(uint8_t image_index)
Helper to check whether an image index is valid for a particular NewGRF vehicle.
Definition: newgrf.cpp:206
ResetCustomIndustries
static void ResetCustomIndustries()
Reset and clear all NewGRF industries.
Definition: newgrf.cpp:8731
PROP_TRAIN_RUNNING_COST_FACTOR
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:23
TimerGameCalendar::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_calendar.h:35
smallmap_gui.h
_grf_files
static std::vector< GRFFile * > _grf_files
List of all loaded GRF files.
Definition: newgrf.cpp:68
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1527
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:356
ShipVehicleInfo::canal_speed_frac
byte canal_speed_frac
Fraction of maximum speed for canal/river tiles.
Definition: engine_type.h:78
TLF_CHILD_X_OFFSET
@ TLF_CHILD_X_OFFSET
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:43
RoadTypeInfo::introduces_roadtypes
RoadTypes introduces_roadtypes
Bitmask of which other roadtypes are introduced when this roadtype is introduced.
Definition: road.h:177
GRFFile::price_base_multipliers
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:149
FeatureTownName
static void FeatureTownName(ByteReader *buf)
Action 0x0F - Define Town names.
Definition: newgrf.cpp:7741
Map::LogX
static debug_inline uint LogX()
Logarithm of the map size along the X side.
Definition: map_func.h:251
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, BranchHandler handler)
Create a branch node with a callback handler.
Definition: newgrf.cpp:8347
HouseSpec::max_year
TimerGameCalendar::Year max_year
last year it can be built
Definition: house.h:101
IndustriesChangeInfo
static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
Define properties for industries.
Definition: newgrf.cpp:3488
DeterministicSpriteGroup
Definition: newgrf_spritegroup.h:167
PROP_TRAIN_TRACTIVE_EFFORT
@ PROP_TRAIN_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
Definition: newgrf_properties.h:27
AllowedSubtags::branch
BranchHandler branch
Callback function for a branch node, only valid if type == 'C' && call_handler.
Definition: newgrf.cpp:8375
TimerGameEconomy::ConvertYMDToDate
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: timer_game_economy.cpp:66
timer_game_calendar.h
HandleNodes
static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
Handle the contents of a 'C' choice of an Action14.
Definition: newgrf.cpp:8570
EngineDisplayFlags::IsFolded
@ IsFolded
Set if display of variants should be folded (hidden).
HouseSpec::accepts_cargo
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:108
RoadTypeInfo::sorting_order
byte sorting_order
The sorting order of this roadtype for the toolbar dropdown.
Definition: road.h:182
BuildCargoLabelMap
void BuildCargoLabelMap()
Build cargo label map.
Definition: cargotype.cpp:93
AirportSpec::size_y
byte size_y
size of airport in y direction
Definition: newgrf_airport.h:108
NewGRFSpriteLayout::AllocateRegisters
void AllocateRegisters()
Allocate memory for register modifiers.
Definition: newgrf_commons.cpp:615
PALETTE_MODIFIER_COLOUR
@ PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition: sprites.h:1542
BASESET_DIR
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
currency.h
RoadStopSpec::name
StringID name
Name of this stop.
Definition: newgrf_roadstop.h:132
AnimationInfo::triggers
uint16_t triggers
The triggers that trigger animation.
Definition: newgrf_animation_type.h:22
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
NamePart::prob
byte prob
The relative probability of the following name to appear in the bottom 7 bits.
Definition: newgrf_townname.h:21
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:89
PROP_AIRCRAFT_MAIL_CAPACITY
@ PROP_AIRCRAFT_MAIL_CAPACITY
Mail Capacity.
Definition: newgrf_properties.h:53
RailTypeInfo::new_loco
StringID new_loco
Name of an engine for this type of rail in the engine preview GUI.
Definition: rail.h:181
AirportSpec::name
StringID name
name of this airport
Definition: newgrf_airport.h:113
CC_EXPRESS
@ CC_EXPRESS
Express cargo (Goods, Food, Candy, but also possible for passengers)
Definition: cargotype.h:52
FinaliseCanals
static void FinaliseCanals()
Set to use the correct action0 properties for each canal feature.
Definition: newgrf.cpp:9173
CanalProperties::callback_mask
uint8_t callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf.h:40
LanguageMap::plural_form
int plural_form
The plural form used for this language.
Definition: newgrf_text.h:68
CanalProperties::flags
uint8_t flags
Flags controlling display.
Definition: newgrf.h:41
CargoLabel
StrongType::Typedef< uint32_t, struct CargoLabelTag, StrongType::Compare > CargoLabel
Globally unique label of a cargo type.
Definition: cargo_type.h:17
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:89
EC_STEAM
@ EC_STEAM
Steam rail engine.
Definition: engine_type.h:34
PriceBaseSpec::grf_feature
uint grf_feature
GRF Feature that decides whether price multipliers apply locally or globally, #GSF_END if none.
Definition: economy_type.h:210
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
RandomizedSpriteGroup::cmp_mode
RandomizedSpriteGroupCompareMode cmp_mode
Check for these triggers:
Definition: newgrf_spritegroup.h:195
DeterministicSpriteGroupAdjust::parameter
byte parameter
Used for variables between 0x60 and 0x7F inclusive.
Definition: newgrf_spritegroup.h:151
VE_DEFAULT
@ VE_DEFAULT
Default value to indicate that visual effect should be based on engine class.
Definition: vehicle_base.h:95
A5BLOCK_INVALID
@ A5BLOCK_INVALID
unknown/not-implemented type
Definition: newgrf.cpp:6396
Action5BlockType
Action5BlockType
The type of action 5 type.
Definition: newgrf.cpp:6393
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:8245
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
PROP_ROADVEH_SHORTEN_FACTOR
@ PROP_ROADVEH_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:41
BridgeSpec::sprite_table
PalSpriteID ** sprite_table
table of sprites for drawing the bridge
Definition: bridge.h:52
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:131
ResetPersistentNewGRFData
void ResetPersistentNewGRFData()
Reset NewGRF data which is stored persistently in savegames.
Definition: newgrf.cpp:8874
PROP_SHIP_CARGO_CAPACITY
@ PROP_SHIP_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:45
ObjectSpec::generate_amount
uint8_t generate_amount
Number of objects which are attempted to be generated per 256^2 map during world generation.
Definition: newgrf_object.h:77
HouseExtraFlags
HouseExtraFlags
Definition: house.h:88
_bridge
BridgeSpec _bridge[MAX_BRIDGES]
The specification of all bridges.
Definition: tunnelbridge_cmd.cpp:52
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
GrfProcessingState::ClearDataForNextFile
void ClearDataForNextFile()
Clear temporary data before processing the next file in the current loading stage.
Definition: newgrf.cpp:116
PROP_AIRCRAFT_RUNNING_COST_FACTOR
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:51
RAILTYPE_MONO
@ RAILTYPE_MONO
Monorail.
Definition: rail_type.h:31
HouseSpec::enabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:112
AirportSpec::noise_level
byte noise_level
noise that this airport generates
Definition: newgrf_airport.h:109
ChangeGRFVersion
static bool ChangeGRFVersion(size_t len, ByteReader *buf)
Callback function for 'INFO'->'VRSN' to the version of the NewGRF.
Definition: newgrf.cpp:8179
IndustryProductionSpriteGroup::add_output
uint16_t add_output[INDUSTRY_NUM_OUTPUTS]
Add this much output cargo when successful (unsigned, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:276
SortIndustryTypes
void SortIndustryTypes()
Initialize the list of sorted industry types.
Definition: industry_gui.cpp:234
ResetPriceBaseMultipliers
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:891
ChangeGRFParamName
static bool ChangeGRFParamName(byte langid, const char *str)
Callback function for 'INFO'->'PARAM'->param_num->'NAME' to set the name of a parameter.
Definition: newgrf.cpp:8214
ResetRailTypes
void ResetRailTypes()
Reset all rail type information to its default values.
Definition: rail_cmd.cpp:65
GrfProcessingState::spritesets
std::map< uint, SpriteSet > spritesets[GSF_END]
Currently referenceable spritesets.
Definition: newgrf.cpp:96
StrMakeValid
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition: string.cpp:114
GrfProcessingState::spriteid
SpriteID spriteid
First available SpriteID for loading realsprites.
Definition: newgrf.cpp:101
GRFConfig::filename
std::string filename
Filename - either with or without full path.
Definition: newgrf_config.h:156
RailTypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:127
VehicleSettings::wagon_speed_limits
bool wagon_speed_limits
enable wagon speed limits
Definition: settings_type.h:522
CIR_INVALID_ID
@ CIR_INVALID_ID
Attempt to modify an invalid ID.
Definition: newgrf.cpp:983
GRFParameterInfo::param_nr
byte param_nr
GRF parameter to store content in.
Definition: newgrf_config.h:135
TLF_CUSTOM_PALETTE
@ TLF_CUSTOM_PALETTE
Palette is from Action 1 (moved to SPRITE_MODIFIER_CUSTOM_SPRITE in palette during loading).
Definition: newgrf_commons.h:38
ObjectSpec::height
uint8_t height
The height of this structure, in heightlevels; max MAX_TILE_HEIGHT.
Definition: newgrf_object.h:75
RailTypeInfo::alternate_labels
RailTypeLabelList alternate_labels
Rail type labels this type provides in addition to the main label.
Definition: rail.h:241
IndustryTileSpec::acceptance
std::array< int8_t, INDUSTRY_NUM_INPUTS > acceptance
Level of acceptance per cargo type (signed, may be negative!)
Definition: industrytype.h:159
IndustryTileSpec::callback_mask
uint8_t callback_mask
Bitmask of industry tile callbacks that have to be called.
Definition: industrytype.h:169
_tags_info
AllowedSubtags _tags_info[]
Action14 tags for the INFO node.
Definition: newgrf.cpp:8466
AnimationInfo::frames
uint8_t frames
The number of frames.
Definition: newgrf_animation_type.h:19
vehicle_base.h
ConvertTTDBasePrice
static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
Converts TTD(P) Base Price pointers into the enum used by OTTD See http://wiki.ttdpatch....
Definition: newgrf.cpp:958
fileio_func.h
GCS_NOT_FOUND
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:37
AirportSpec::min_year
TimerGameCalendar::Year min_year
first year the airport is available
Definition: newgrf_airport.h:111
IsDefaultCargo
bool IsDefaultCargo(CargoID cid)
Test if a cargo is a default cargo type.
Definition: cargotype.cpp:111
newgrf_airport.h
SetupCargoForClimate
void SetupCargoForClimate(LandscapeID l)
Set up the default cargo types for the given landscape type.
Definition: cargotype.cpp:48
HouseSpec::callback_mask
uint16_t callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:116
build_industry.h
GRFTempEngineData::ctt_include_mask
CargoTypes ctt_include_mask
Cargo types always included in the refit mask.
Definition: newgrf.cpp:334
HouseSpec::building_name
StringID building_name
building name
Definition: house.h:104
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_economy.h:38
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:187
SetupEngines
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:565
GRFConfig::ident
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
Definition: newgrf_config.h:154
newgrf_townname.h
RailTypeInfo::introduction_required_railtypes
RailTypes introduction_required_railtypes
Bitmask of railtypes that are required for this railtype to be introduced at a given introduction_dat...
Definition: rail.h:261
AirportSpec::max_year
TimerGameCalendar::Year max_year
last year the airport is available
Definition: newgrf_airport.h:112
ttd_strnlen
size_t ttd_strnlen(const char *str, size_t maxlen)
Get the length of a string, within a limited buffer.
Definition: string_func.h:68
LiveryScheme
LiveryScheme
List of different livery schemes.
Definition: livery.h:21
AirportSpec::ResetAirports
static void ResetAirports()
This function initializes the airportspec array.
Definition: newgrf_airport.cpp:110
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:68
GetNewEngine
static Engine * GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access=false)
Returns the engine associated to a certain internal_id, resp.
Definition: newgrf.cpp:598
ReusableBuffer::Allocate
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition: alloc_type.hpp:42
GRFConfig::status
GRFStatus status
NOSAVE: GRFStatus, enum.
Definition: newgrf_config.h:165
GetNewGRFSoundID
SoundID GetNewGRFSoundID(const GRFFile *file, SoundID sound_id)
Resolve NewGRF sound ID.
Definition: newgrf_sound.cpp:169
VE_TYPE_COUNT
@ VE_TYPE_COUNT
Number of bits used for the effect type.
Definition: vehicle_base.h:85
town.h
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:716
NUM_OBJECTS_PER_GRF
static const ObjectType NUM_OBJECTS_PER_GRF
Number of supported objects per NewGRF.
Definition: object_type.h:24
BridgeSpec::speed
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: bridge.h:47
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition: cargotype.h:56
RoadStopSpec::cls_id
RoadStopClassID cls_id
The class to which this spec belongs.
Definition: newgrf_roadstop.h:130
GRFP_GRF_UNSET
@ GRFP_GRF_UNSET
The NewGRF provided no information.
Definition: newgrf_config.h:70
StrongType::Typedef
Templated helper to make a type-safe 'typedef' representing a single POD value.
Definition: strong_typedef_type.hpp:150
ObjectFlags
ObjectFlags
Various object behaviours.
Definition: newgrf_object.h:24
EngineInfo
Information about a vehicle.
Definition: engine_type.h:144
ChangeGRFParamType
static bool ChangeGRFParamType(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PARAM'->param_num->'TYPE' to set the typeof a parameter.
Definition: newgrf.cpp:8228
DSGA_OP_ADD
@ DSGA_OP_ADD
a + b
Definition: newgrf_spritegroup.h:121
GrfProcessingState::file
SpriteFile * file
File of currently processed GRF file.
Definition: newgrf.cpp:104
GRFLoadedFeatures::used_liveries
uint64_t used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:179
GMB_TRAIN_WIDTH_32_PIXELS
@ GMB_TRAIN_WIDTH_32_PIXELS
Use 32 pixels per train vehicle in depot gui and vehicle details. Never set in the global variable;.
Definition: newgrf.h:60
IndustrySpec::station_name
StringID station_name
Default name for nearby station.
Definition: industrytype.h:132
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
_display_opt
byte _display_opt
What do we want to draw/do?
Definition: transparency_gui.cpp:26
CIR_SUCCESS
@ CIR_SUCCESS
Variable was parsed and read.
Definition: newgrf.cpp:979
GRFConfig::min_loadable_version
uint32_t min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
Definition: newgrf_config.h:163
MAX_SPRITEGROUP
static const uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
Definition: newgrf.cpp:84
VehicleSettings::road_side
byte road_side
the side of the road vehicles drive on
Definition: settings_type.h:533
RoadTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: road.h:107
AllowedSubtags::text
TextHandler text
Callback function for a text node, only valid if type == 'T'.
Definition: newgrf.cpp:8372
RailTypeInfo::group
const SpriteGroup * group[RTSG_END]
Sprite groups for resolving sprites.
Definition: rail.h:281
VSG_SCOPE_PARENT
@ VSG_SCOPE_PARENT
Related object of the resolved one.
Definition: newgrf_spritegroup.h:101
Engine
Definition: engine_base.h:37
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:50
Action5Type::max_sprites
uint16_t max_sprites
If the Action5 contains more sprites, only the first max_sprites sprites will be used.
Definition: newgrf.cpp:6403
IndustryTileSpec::accepts_cargo
std::array< CargoID, INDUSTRY_NUM_INPUTS > accepts_cargo
Cargo accepted by this tile.
Definition: industrytype.h:157
GRFParameterInfo::type
GRFParameterType type
The type of this parameter.
Definition: newgrf_config.h:131
SoundEffectChangeInfo
static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
Define properties for sound effects.
Definition: newgrf.cpp:3136
RailTypeInfo::strings
struct RailTypeInfo::@26 strings
Strings associated with the rail type.
_tags_parameters
AllowedSubtags _tags_parameters[]
Action14 parameter tags.
Definition: newgrf.cpp:8422
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:128
SpriteFile::GetContainerVersion
byte GetContainerVersion() const
Get the version number of container type used by the file.
Definition: sprite_file_type.hpp:38
SoundEntry::grf_container_ver
byte grf_container_ver
NewGRF container version if the sound is from a NewGRF.
Definition: sound_type.h:22
IndustrySpec::cost_multiplier
uint8_t cost_multiplier
Base construction cost multiplier.
Definition: industrytype.h:107
fios.h
BridgeSpec::price
uint16_t price
the price multiplier
Definition: bridge.h:46
TranslateGRFStrings
static void TranslateGRFStrings(ByteReader *buf)
Action 0x13.
Definition: newgrf.cpp:8045
ConstructionSettings::max_bridge_length
uint16_t max_bridge_length
maximum length of bridges
Definition: settings_type.h:373
FinalisePriceBaseMultipliers
static void FinalisePriceBaseMultipliers()
Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them...
Definition: newgrf.cpp:9808
RandomAccessFile::ReadBlock
void ReadBlock(void *ptr, size_t size)
Read a block.
Definition: random_access_file.cpp:139
_engine_counts
const uint8_t _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:53
TLF_BB_Z_OFFSET
@ TLF_BB_Z_OFFSET
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:41
StrEmpty
bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:56
PaletteID
uint32_t PaletteID
The number of the palette.
Definition: gfx_type.h:18
GFX_WATERTILE_SPECIALCHECK
@ GFX_WATERTILE_SPECIALCHECK
not really a tile, but rather a very special check
Definition: industry_map.h:54
AirportSpec
Defines the data structure for an airport.
Definition: newgrf_airport.h:100
HasExactlyOneBit
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition: bitmath_func.hpp:259
GRFParameterInfo::min_value
uint32_t min_value
The minimal value this parameter can have.
Definition: newgrf_config.h:132
NUM_HOUSES_PER_GRF
static const HouseID NUM_HOUSES_PER_GRF
Number of supported houses per NewGRF; limited to 255 to allow extending Action3 with an extended byt...
Definition: house.h:25
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
genworld.h
TileLayoutRegisters
Additional modifiers for items in sprite layouts.
Definition: newgrf_commons.h:90
CargoSpec::initial_payment
int32_t initial_payment
Initial payment rate before inflation is applied.
Definition: cargotype.h:76
GRFP_BLT_UNSET
@ GRFP_BLT_UNSET
The NewGRF provided no information or doesn't care about a 32 bpp blitter.
Definition: newgrf_config.h:76
RandomAccessFile::ReadByte
byte ReadByte()
Read a byte from the file.
Definition: random_access_file.cpp:101
RailTypeInfo::curve_speed
byte curve_speed
Multiplier for curve maximum speed advantage.
Definition: rail.h:206
ObjectSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_object.h:63
CIR_UNHANDLED
@ CIR_UNHANDLED
Variable was parsed but unread.
Definition: newgrf.cpp:981
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
VSG_SCOPE_SELF
@ VSG_SCOPE_SELF
Resolved object itself.
Definition: newgrf_spritegroup.h:100
SPR_AQUEDUCT_BASE
static const SpriteID SPR_AQUEDUCT_BASE
Sprites for the Aqueduct.
Definition: sprites.h:186
RailVehicleInfo::cost_factor
byte cost_factor
Purchase cost factor; For multiheaded engines the sum of both engine prices.
Definition: engine_type.h:45
GrfProcessingState::nfo_line
uint32_t nfo_line
Currently processed pseudo sprite number in the GRF.
Definition: newgrf.cpp:107
RailTypeInfo::sorting_order
byte sorting_order
The sorting order of this railtype for the toolbar dropdown.
Definition: rail.h:271
ObjectSpec::callback_mask
uint16_t callback_mask
Bitmask of requested/allowed callbacks.
Definition: newgrf_object.h:74
industry_map.h
CargoSpec::array
static CargoSpec array[NUM_CARGO]
Array holding all CargoSpecs.
Definition: cargotype.h:193
DeterministicSpriteGroupAdjustOperation
DeterministicSpriteGroupAdjustOperation
Definition: newgrf_spritegroup.h:120
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:8323
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:619
GRFParameterInfo::num_bit
byte num_bit
Number of bits to use for this parameter.
Definition: newgrf_config.h:137
ReallocT
T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type.
Definition: alloc_func.hpp:111
RAILTYPE_ELECTRIC
@ RAILTYPE_ELECTRIC
Electric rails.
Definition: rail_type.h:30
RandomizedSpriteGroup::var_scope
VarSpriteGroupScope var_scope
Take this object:
Definition: newgrf_spritegroup.h:193
GCF_INVALID
@ GCF_INVALID
GRF is unusable with this version of OpenTTD.
Definition: newgrf_config.h:30
AllocateRoadType
RoadType AllocateRoadType(RoadTypeLabel label, RoadTramType rtt)
Allocate a new road type label.
Definition: road_cmd.cpp:134
AirportChangeInfo
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
Define properties for airports.
Definition: newgrf.cpp:3896
IndustryTileLayout
std::vector< IndustryTileLayoutTile > IndustryTileLayout
A complete tile layout for an industry is a list of tiles.
Definition: industrytype.h:100
GCF_INIT_ONLY
@ GCF_INIT_ONLY
GRF file is processed up to GLS_INIT.
Definition: newgrf_config.h:28
EC_ELECTRIC
@ EC_ELECTRIC
Electric rail engine.
Definition: engine_type.h:36
find_index
int find_index(Container const &container, typename Container::const_reference item)
Helper function to get the index of an item Consider using std::set, std::unordered_set or std::flat_...
Definition: container_func.hpp:41
FinaliseCargoArray
void FinaliseCargoArray()
Check for invalid cargoes.
Definition: newgrf.cpp:9251
StringIDMapping::target
StringID * target
Destination for mapping result.
Definition: newgrf.cpp:463
BridgeSpec
Struct containing information about a single bridge type.
Definition: bridge.h:42
IndustrySpec::closure_text
StringID closure_text
Message appearing when the industry closes.
Definition: industrytype.h:129
RailTypeInfo::compatible_railtypes
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition: rail.h:191
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:167
GrfProcessingState::SpriteSet::sprite
SpriteID sprite
SpriteID of the first sprite of the set.
Definition: newgrf.cpp:91
MemCpyT
void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition: mem_func.hpp:23
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:145
AirportTileSpec::ResetAirportTiles
static void ResetAirportTiles()
This function initializes the tile array of AirportTileSpec.
Definition: newgrf_airporttiles.cpp:58
TLF_KNOWN_FLAGS
@ TLF_KNOWN_FLAGS
Known flags. Any unknown set flag will disable the GRF.
Definition: newgrf_commons.h:49
ShipVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:76
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:59
HouseSpec::extra_flags
HouseExtraFlags extra_flags
some more flags
Definition: house.h:119
TileLayoutRegisters::sprite_var10
uint8_t sprite_var10
Value for variable 10 when resolving the sprite.
Definition: newgrf_commons.h:101
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition: newgrf_airporttiles.h:68
HouseSpec::probability
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:118
NETWORK_MAX_GRF_COUNT
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition: config.h:92
IndustryTileSpec::special_flags
IndustryTileSpecialFlags special_flags
Bitmask of extra flags used by the tile.
Definition: industrytype.h:171
StationSpec::cls_id
StationClassID cls_id
The class to which this spec belongs.
Definition: newgrf_station.h:125
RailTypeInfo::name
StringID name
Name of this rail type.
Definition: rail.h:176
EC_MAGLEV
@ EC_MAGLEV
Maglev engine.
Definition: engine_type.h:38
GRFTempEngineData::Refittability
Refittability
Summary state of refittability properties.
Definition: newgrf.cpp:321
GRFFileProps::override
uint16_t override
id of the entity been replaced by
Definition: newgrf_commons.h:332
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:626
RealSpriteGroup::loading
std::vector< const SpriteGroup * > loading
List of loading groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:90
Pool::PoolItem<&_engine_pool >::GetPoolSize
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:360
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
ObjectSpec::BindToClasses
static void BindToClasses()
Tie all ObjectSpecs to their class.
Definition: newgrf_object.cpp:111
InitGRFTownGeneratorNames
void InitGRFTownGeneratorNames()
Allocate memory for the NewGRF town names.
Definition: newgrf_townname.cpp:81
GRFP_GRF_DOS
@ GRFP_GRF_DOS
The NewGRF says the DOS palette can be used.
Definition: newgrf_config.h:71
ObjectSpec::size
uint8_t size
The size of this objects; low nibble for X, high nibble for Y.
Definition: newgrf_object.h:68
MAX_CATCHMENT
@ MAX_CATCHMENT
Maximum catchment for airports with "modified catchment" enabled.
Definition: station_type.h:84
TileLayoutRegisters::palette
uint8_t palette
Register specifying a signed offset for the palette.
Definition: newgrf_commons.h:94
MAX_NUM_CASES
static const uint8_t MAX_NUM_CASES
Maximum number of supported cases.
Definition: language.h:21
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, TextHandler handler)
Create a text leaf node.
Definition: newgrf.cpp:8335
GRFLoadedFeatures::has_2CC
bool has_2CC
Set if any vehicle is loaded which uses 2cc (two company colours).
Definition: newgrf.h:178
PROP_ROADVEH_SPEED
@ PROP_ROADVEH_SPEED
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
Definition: newgrf_properties.h:38
RailVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:58
GrfProcessingState::HasValidSpriteSets
bool HasValidSpriteSets(byte feature) const
Check whether there are any valid spritesets for a feature.
Definition: newgrf.cpp:152
DisableStaticNewGRFInfluencingNonStaticNewGRFs
static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
Disable a static NewGRF when it is influencing another (non-static) NewGRF as this could cause desync...
Definition: newgrf.cpp:6827
LoadNewGRF
void LoadNewGRF(uint load_index, uint num_baseset)
Load all the NewGRFs.
Definition: newgrf.cpp:10042
AirportSpec::rotation
const Direction * rotation
the rotation of each tiletable
Definition: newgrf_airport.h:103
LoadNewGRFFile
void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
Load a particular NewGRF.
Definition: newgrf.cpp:9720
SHORE_REPLACE_NONE
@ SHORE_REPLACE_NONE
No shore sprites were replaced.
Definition: newgrf.h:165
RailVehicleInfo::ai_passenger_only
byte ai_passenger_only
Bit value to tell AI that this engine is for passenger use only.
Definition: engine_type.h:55
GRFConfig::version
uint32_t version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
Definition: newgrf_config.h:162
AnimationInfo::status
uint8_t status
Status; 0: no looping, 1: looping, 0xFF: no animation.
Definition: newgrf_animation_type.h:20
EconomySettings::station_noise_level
bool station_noise_level
build new airports when the town noise level is still within accepted limits
Definition: settings_type.h:557
RailVehicleInfo
Information about a rail vehicle.
Definition: engine_type.h:42
GRFLoadedFeatures::shore
ShoreReplacement shore
In which way shore sprites were replaced.
Definition: newgrf.h:180
RailTypeInfo::maintenance_multiplier
uint16_t maintenance_multiplier
Cost multiplier for maintenance of this rail type.
Definition: rail.h:221
error_func.h
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:122
NUM_AIRPORTTILES_PER_GRF
static const uint NUM_AIRPORTTILES_PER_GRF
Number of airport tiles per NewGRF; limited to 255 to allow extending Action3 with an extended byte l...
Definition: airport.h:21
RailVehicleInfo::engclass
EngineClass engclass
Class of engine for this vehicle.
Definition: engine_type.h:53
GRFParameterInfo::value_names
std::map< uint32_t, GRFTextList > value_names
Names for each value.
Definition: newgrf_config.h:138
BindAirportSpecs
void BindAirportSpecs()
Tie all airportspecs to their class.
Definition: newgrf_airport.cpp:123
EngineInfo::callback_mask
uint16_t callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:156
LoadNextSprite
bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
Definition: spritecache.cpp:609
VE_TYPE_START
@ VE_TYPE_START
First bit used for the type of effect.
Definition: vehicle_base.h:84
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
VehicleSettings::freight_trains
uint8_t freight_trains
value to multiply the weight of cargo by
Definition: settings_type.h:529
GRFFile::tramtype_list
std::vector< RoadTypeLabel > tramtype_list
Roadtype translation table (tram)
Definition: newgrf.h:138
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:611
BSWAP32
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:345
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:282
PROP_AIRCRAFT_CARGO_AGE_PERIOD
@ PROP_AIRCRAFT_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:54
NEW_INDUSTRYOFFSET
static const IndustryType NEW_INDUSTRYOFFSET
original number of industry types
Definition: industry_type.h:25
RailVehicleInfo::air_drag
byte air_drag
Coefficient of air drag.
Definition: engine_type.h:61
GCF_UNSAFE
@ GCF_UNSAFE
GRF file is unsafe for static usage.
Definition: newgrf_config.h:24
GCS_INITIALISED
@ GCS_INITIALISED
GRF file has been initialised.
Definition: newgrf_config.h:38
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:147
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
CargoSpec::weight
uint8_t weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:73
newgrf_engine.h
PROP_ROADVEH_CARGO_AGE_PERIOD
@ PROP_ROADVEH_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:40
GRFUnsafe
static void GRFUnsafe(ByteReader *)
Set the current NewGRF as unsafe for static use.
Definition: newgrf.cpp:8595
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:35
StringIDMapping::source
StringID source
Source StringID (GRF local).
Definition: newgrf.cpp:462
AirportSpec::num_table
byte num_table
number of elements in the table
Definition: newgrf_airport.h:104
SetPriceBaseMultiplier
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:903
IndustrySpec::conflicting
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:110
RoadStopSpec::spec_id
int spec_id
The ID of this spec inside the class.
Definition: newgrf_roadstop.h:131
MapNewGRFIndustryType
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32_t grf_id)
Map the GRF local type to an industry type.
Definition: newgrf_industries.cpp:40
CurrencySpec::suffix
std::string suffix
Suffix to apply when formatting money in this currency.
Definition: currency.h:78
TLF_BB_XY_OFFSET
@ TLF_BB_XY_OFFSET
Add signed offset to bounding box X and Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:40
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
StationSpec::layouts
std::vector< std::vector< std::vector< byte > > > layouts
Custom platform layouts.
Definition: newgrf_station.h:175
GetGRFSpriteOffset
size_t GetGRFSpriteOffset(uint32_t id)
Get the file offset for a specific sprite in the sprite section of a GRF.
Definition: spritecache.cpp:544
OverrideManagerBase::ResetMapping
void ResetMapping()
Resets the mapping, which is used while initializing game.
Definition: newgrf_commons.cpp:72
FinaliseIndustriesArray
static void FinaliseIndustriesArray()
Add all new industries to the industry array.
Definition: newgrf.cpp:9432
TLF_CHILD_Y_OFFSET
@ TLF_CHILD_Y_OFFSET
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:44
GRFP_GRF_ANY
@ GRFP_GRF_ANY
The NewGRF says any palette can be used.
Definition: newgrf_config.h:73
GCF_SYSTEM
@ GCF_SYSTEM
GRF file is an openttd-internal system grf.
Definition: newgrf_config.h:23
NEW_HOUSE_OFFSET
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
HandleParameterInfo
static bool HandleParameterInfo(ByteReader *buf)
Callback function for 'INFO'->'PARA' to set extra information about the parameters.
Definition: newgrf.cpp:8439
StationSpec::pylons
byte pylons
Bitmask of base tiles (0 - 7) which should contain elrail pylons.
Definition: newgrf_station.h:161
AirportTileTable::gfx
StationGfx gfx
AirportTile to use for this tile.
Definition: newgrf_airport.h:27
free
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:379
CallbackResultSpriteGroup
Definition: newgrf_spritegroup.h:210
CargoSpec::units_volume
StringID units_volume
Name of a single unit of cargo of this type.
Definition: cargotype.h:87
CargoSpec::IsValid
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:112
TAE_GOODS
@ TAE_GOODS
Cargo behaves goods/candy-like.
Definition: cargotype.h:26
RoadTypeInfo::maintenance_multiplier
uint16_t maintenance_multiplier
Cost multiplier for maintenance of this road type.
Definition: road.h:137
IndustryProductionSpriteGroup::version
uint8_t version
Production callback version used, or 0xFF if marked invalid.
Definition: newgrf_spritegroup.h:271
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:110
GetFileByFilename
static GRFFile * GetFileByFilename(const std::string &filename)
Obtain a NewGRF file by its filename.
Definition: newgrf.cpp:416
ConstructionSettings::map_height_limit
uint8_t map_height_limit
the maximum allowed heightlevel
Definition: settings_type.h:370
RoadVehicleInfo
Information about a road vehicle.
Definition: engine_type.h:114
CC_PIECE_GOODS
@ CC_PIECE_GOODS
Piece goods (Livestock, Wood, Steel, Paper)
Definition: cargotype.h:55
DrawTileSeqStruct::delta_z
int8_t delta_z
0x80 identifies child sprites
Definition: sprite.h:28
RoadStopSpec::build_cost_multiplier
uint8_t build_cost_multiplier
Build cost multiplier per tile.
Definition: newgrf_roadstop.h:146
BranchHandler
bool(* BranchHandler)(ByteReader *)
Type of callback function for branch nodes.
Definition: newgrf.cpp:8302
EngineIDMapping::grfid
uint32_t grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:193
ObjectSpec::end_of_life_date
TimerGameCalendar::Date end_of_life_date
When can't this object be built anymore.
Definition: newgrf_object.h:72
LanguageMap::Mapping::openttd_id
byte openttd_id
OpenTTD's internal ID for a case/gender.
Definition: newgrf_text.h:57
RoadVehicleInfo::visual_effect
byte visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:126
IndustryProductionSpriteGroup
Definition: newgrf_spritegroup.h:268
IndustrySpec::layouts
std::vector< IndustryTileLayout > layouts
List of possible tile layouts for the industry.
Definition: industrytype.h:106
TimerGameCalendar::ConvertYMDToDate
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: timer_game_calendar.cpp:55
SPRITE_MODIFIER_OPAQUE
@ SPRITE_MODIFIER_OPAQUE
Set when a sprite must not ever be displayed transparently.
Definition: sprites.h:1540
AnimationInfo::speed
uint8_t speed
The speed, i.e. the amount of time between frames.
Definition: newgrf_animation_type.h:21
IndustrySpec::accepts_cargo
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 accepted cargoes.
Definition: industrytype.h:120
INDUSTRYTILE_NOANIM
static const IndustryGfx INDUSTRYTILE_NOANIM
flag to mark industry tiles as having no animation
Definition: industry_type.h:31
INVALID_INDUSTRYTILE
static const IndustryGfx INVALID_INDUSTRYTILE
one above amount is considered invalid
Definition: industry_type.h:34
EF_USES_2CC
@ EF_USES_2CC
Vehicle uses two company colours.
Definition: engine_type.h:170
SHORE_REPLACE_ONLY_NEW
@ SHORE_REPLACE_ONLY_NEW
Only corner-shores were loaded by Action5 (openttd(w/d).grf only).
Definition: newgrf.h:168
BridgeSpec::transport_name
StringID transport_name[2]
description of the bridge, when built for road or rail
Definition: bridge.h:51
CC_BULK
@ CC_BULK
Bulk cargo (Coal, Grain etc., Ores, Fruit)
Definition: cargotype.h:54
_cargo_mask
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition: cargotype.cpp:31
SP_CUSTOM
@ SP_CUSTOM
No profile, special "custom" highscore.
Definition: settings_type.h:46
NUM_AIRPORTS_PER_GRF
@ NUM_AIRPORTS_PER_GRF
Maximal number of airports per NewGRF.
Definition: airport.h:40
IndustrySpec::production_up_text
StringID production_up_text
Message appearing when the industry's production is increasing.
Definition: industrytype.h:130
CleanUpStrings
void CleanUpStrings()
House cleaning.
Definition: newgrf_text.cpp:682
RailTypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: rail.h:177
EnsureEarlyHouse
static void EnsureEarlyHouse(HouseZones bitmask)
Make sure there is at least one house available in the year 0 for the given climate / housezone combi...
Definition: newgrf.cpp:9327
GrfProcessingState::SpriteSet
Definition of a single Action1 spriteset.
Definition: newgrf.cpp:90
LoadNewGRFFileFromFile
static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
Load a particular NewGRF from a SpriteFile.
Definition: newgrf.cpp:9631
CargoSpec::grffile
const struct GRFFile * grffile
NewGRF where #group belongs to.
Definition: cargotype.h:93
StaticGRFInfo
static void StaticGRFInfo(ByteReader *buf)
Handle Action 0x14.
Definition: newgrf.cpp:8585
EC_DIESEL
@ EC_DIESEL
Diesel rail engine.
Definition: engine_type.h:35
HZ_ZONALL
@ HZ_ZONALL
1F This is just to englobe all above types at once
Definition: house.h:78
SpriteGroupCargo::SG_DEFAULT
static constexpr CargoID SG_DEFAULT
Default type used when no more-specific cargo matches.
Definition: newgrf_cargo.h:23
NewGRFClass
Struct containing information relating to NewGRF classes for stations and airports.
Definition: newgrf_class.h:20
StationSettings::never_expire_airports
bool never_expire_airports
never expire airports
Definition: settings_type.h:594
AfterLoadGRFs
static void AfterLoadGRFs()
Finish loading NewGRFs and execute needed post-processing.
Definition: newgrf.cpp:9923
_cur_parameter
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:8211
IndustrySpec::minimal_cargo
byte minimal_cargo
minimum amount of cargo transported to the stations.
Definition: industrytype.h:119
TileLayoutRegisters::max_palette_offset
uint16_t max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset)
Definition: newgrf_commons.h:96
RoadTypeInfo::group
const SpriteGroup * group[ROTSG_END]
Sprite groups for resolving sprites.
Definition: road.h:192
LanguageMap::gender_map
std::vector< Mapping > gender_map
Mapping of NewGRF and OpenTTD IDs for genders.
Definition: newgrf_text.h:66
SHORE_REPLACE_ACTION_5
@ SHORE_REPLACE_ACTION_5
Shore sprites were replaced by Action5.
Definition: newgrf.h:166
StringIDMapping
Information for mapping static StringIDs.
Definition: newgrf.cpp:460
MAX_NUM_GENDERS
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
Definition: language.h:20
RoadVehicleInfo::air_drag
uint8_t air_drag
Coefficient of air drag.
Definition: engine_type.h:125
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:55
StationSpec::cargo_threshold
uint16_t cargo_threshold
Cargo threshold for choosing between little and lots of cargo.
Definition: newgrf_station.h:153
HouseSpec::animation
AnimationInfo animation
information about the animation.
Definition: house.h:121
NUM_INDUSTRYTILES_PER_GRF
static const IndustryGfx NUM_INDUSTRYTILES_PER_GRF
Maximum number of industry tiles per NewGRF; limited to 255 to allow extending Action3 with an extend...
Definition: industry_type.h:29
ValidateIndustryLayout
static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
Validate the industry layout; e.g.
Definition: newgrf.cpp:3455
RailTypeInfo::label
RailTypeLabel label
Unique 32 bit rail type identifier.
Definition: rail.h:236
timer_game_tick.h
TimerGameConst< struct Calendar >::ORIGINAL_MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: timer_game_common.h:167
RoadTypeInfo::alternate_labels
RoadTypeLabelList alternate_labels
Road type labels this type provides in addition to the main label.
Definition: road.h:152
ChangeGRFURL
static bool ChangeGRFURL(byte langid, const char *str)
Callback function for 'INFO'->'URL_' to set the newgrf url.
Definition: newgrf.cpp:8112
_water_feature
WaterFeature _water_feature[CF_END]
Table of canal 'feature' sprite groups.
Definition: newgrf_canal.cpp:21
PriceBaseSpec::fallback_price
Price fallback_price
Fallback price multiplier for new prices but old grfs.
Definition: economy_type.h:211
GRFParameterInfo
Information about one grf parameter.
Definition: newgrf_config.h:127
CargoSpec::sprite
SpriteID sprite
Icon to display this cargo type, may be 0xFFF (which means to resolve an action123 chain).
Definition: cargotype.h:91
GRFConfig::error
std::optional< GRFError > error
NOSAVE: Error/Warning during GRF loading (Action 0x0B)
Definition: newgrf_config.h:160
ANIM_STATUS_NO_ANIMATION
static const uint8_t ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:628
DrawTileSeqStruct::IsTerminator
bool IsTerminator() const
Check whether this is a sequence terminator.
Definition: sprite.h:41
AirportSpec::ttd_airport_type
TTDPAirportType ttd_airport_type
ttdpatch airport type (Small/Large/Helipad/Oilrig)
Definition: newgrf_airport.h:114
PROP_SHIP_CARGO_AGE_PERIOD
@ PROP_SHIP_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:47
CurrencySpec::code
std::string code
3 letter untranslated code to identify the currency.
Definition: currency.h:79
_action5_types
static const Action5Type _action5_types[]
The information about action 5 types.
Definition: newgrf.cpp:6408
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition: newgrf_commons.h:112
MAX_LANG
static const uint MAX_LANG
Maximum number of languages supported by the game, and the NewGRF specs.
Definition: strings_type.h:19
TimerGameCalendar::ConvertDateToYMD
static YearMonthDay ConvertDateToYMD(Date date)
Converts a Date to a Year, Month & Day.
Definition: timer_game_calendar.cpp:42
safeguards.h
RoadVehicleInfo::power
uint8_t power
Power in 10hp units.
Definition: engine_type.h:123
EngineIDMapping::substitute_id
uint8_t substitute_id
The (original) entity ID to use if this GRF is not available (currently not used)
Definition: engine_base.h:196
ChangeGRFParamMask
static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PARAM'->param_num->'MASK' to set the parameter and bits to use.
Definition: newgrf.cpp:8267
StationSpec::name
StringID name
Name of this station.
Definition: newgrf_station.h:126
ObjectOverrideManager::SetEntitySpec
void SetEntitySpec(ObjectSpec *spec)
Method to install the new object data in its proper slot The slot assignment is internal of this meth...
Definition: newgrf_commons.cpp:298
GameCreationSettings::starting_year
TimerGameCalendar::Year starting_year
starting date
Definition: settings_type.h:341
AddGRFString
StringID AddGRFString(uint32_t grfid, uint16_t stringid, byte langid_to_add, bool new_scheme, bool allow_newlines, const char *text_to_add, StringID def_string)
Add the new read string into our structure.
Definition: newgrf_text.cpp:543
GRFP_BLT_32BPP
@ GRFP_BLT_32BPP
The NewGRF prefers a 32 bpp blitter.
Definition: newgrf_config.h:77
IndustryTileSpec::slopes_refused
Slope slopes_refused
slope pattern on which this tile cannot be built
Definition: industrytype.h:160
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:8392
ImportGRFSound
static void ImportGRFSound(SoundEntry *sound)
Process a sound import from another GRF file.
Definition: newgrf.cpp:7837
GRFConfig::has_param_defaults
bool has_param_defaults
NOSAVE: did this newgrf specify any defaults for it's parameters.
Definition: newgrf_config.h:172
GRFFile::param_end
uint param_end
one more than the highest set parameter
Definition: newgrf.h:125
TLR_MAX_VAR10
static const uint TLR_MAX_VAR10
Maximum value for var 10.
Definition: newgrf_commons.h:105
GrfProcessingState
Temporary data during loading of GRFs.
Definition: newgrf.cpp:87
IndustryProductionSpriteGroup::subtract_input
int16_t subtract_input[INDUSTRY_NUM_INPUTS]
Take this much of the input cargo (can be negative, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:273
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1539
IndustryTileSpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:172
_tags_root
AllowedSubtags _tags_root[]
Action14 root tags.
Definition: newgrf.cpp:8480
FinaliseObjectsArray
static void FinaliseObjectsArray()
Add all new objects to the object array.
Definition: newgrf.cpp:9506
GRFTempEngineData::EMPTY
@ EMPTY
GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
Definition: newgrf.cpp:323
GRFTownName::partlists
std::vector< NamePartList > partlists[MAX_LISTS]
Lists of town name parts.
Definition: newgrf_townname.h:43
NamePart::text
std::string text
If probability bit 7 is clear.
Definition: newgrf_townname.h:19
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:58
HouseSpec::minimum_life
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:123
RoadStopSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_roadstop.h:129
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:59
AirportSpec::maintenance_cost
uint16_t maintenance_cost
maintenance cost multiplier
Definition: newgrf_airport.h:117
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:27
CurrencySpec::rate
uint16_t rate
The conversion rate compared to the base currency.
Definition: currency.h:75
TTDPAirportType
TTDPAirportType
Allow incrementing of AirportClassID variables.
Definition: newgrf_airport.h:83
CanalChangeInfo
static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for water features.
Definition: newgrf.cpp:2157
WaterFeature::callback_mask
uint8_t callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf_canal.h:25
CargoSpec::callback_mask
uint8_t callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:83
GlobalVarChangeInfo
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
Define properties for global variables.
Definition: newgrf.cpp:2682
newgrf_text.h
road.h
RoadVehicleInfo::tractive_effort
uint8_t tractive_effort
Coefficient of tractive effort.
Definition: engine_type.h:124
ObjectSpec::introduction_date
TimerGameCalendar::Date introduction_date
From when can this object be built.
Definition: newgrf_object.h:71
IndustrySpec::prospecting_chance
uint32_t prospecting_chance
Chance prospecting succeeds.
Definition: industrytype.h:109
NamePartList::bitcount
byte bitcount
Number of bits of random seed to use.
Definition: newgrf_townname.h:26
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:103
error.h
GrfProcessingState::GetSprite
SpriteID GetSprite(byte feature, uint set) const
Returns the first sprite of a spriteset.
Definition: newgrf.cpp:177
RailVehicleChangeInfo
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for rail vehicles.
Definition: newgrf.cpp:1038
OverrideManagerBase::AddEntityID
virtual uint16_t AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
Reserves a place in the mapping array for an entity to be installed.
Definition: newgrf_commons.cpp:109
CargoSpec::is_freight
bool is_freight
Cargo type is considered to be freight (affects train freight multiplier).
Definition: cargotype.h:79
RailTypeInfo::cost_multiplier
uint16_t cost_multiplier
Cost multiplier for building this rail type.
Definition: rail.h:216
HZ_ZON5
@ HZ_ZON5
center of town
Definition: house.h:77
TimerGameConst< struct Calendar >::MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year MAX_YEAR
MAX_YEAR, nicely rounded value of the number of years that can be encoded in a single 32 bits date,...
Definition: timer_game_common.h:173
GRFTempEngineData::ctt_exclude_mask
CargoTypes ctt_exclude_mask
Cargo types always excluded from the refit mask.
Definition: newgrf.cpp:335
GRFTempEngineData::defaultcargo_grf
const GRFFile * defaultcargo_grf
GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
Definition: newgrf.cpp:331
ResetCurrencies
void ResetCurrencies(bool preserve_custom)
Will fill _currency_specs array with default values from origin_currency_specs Called only from newgr...
Definition: currency.cpp:159
EngineIDMapping
Definition: engine_base.h:192
AirportTileTable
Tile-offset / AirportTileID pair.
Definition: newgrf_airport.h:25
IndustrySpec::appear_creation
byte appear_creation[NUM_LANDSCAPE]
Probability of appearance during map creation.
Definition: industrytype.h: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:82
Pool::CleanPool
void CleanPool() override
Virtual method that deletes all items in the pool.
language.h
RoadTypeInfo::cost_multiplier
uint16_t cost_multiplier
Cost multiplier for building this road type.
Definition: road.h:132
IndustryTileSpec::anim_production
byte anim_production
Animation frame to start when goods are produced.
Definition: industrytype.h:161
newgrf_roadstop.h
RandomAccessFile::filename
std::string filename
Full name of the file; relative path to subdir plus the extension of the file.
Definition: random_access_file_type.h:26
CargoSpec::bitnum
uint8_t bitnum
Cargo bit number, is INVALID_CARGO_BITNUM for a non-used spec.
Definition: cargotype.h:70
RailVehicleInfo::tractive_effort
byte tractive_effort
Tractive effort coefficient.
Definition: engine_type.h:60
GetActiveCargoLabel
static CargoLabel GetActiveCargoLabel(const std::initializer_list< CargoLabel > &labels)
Find first cargo label that exists and is active from a list of cargo labels.
Definition: newgrf.cpp:8973
GRFFile::traininfo_vehicle_width
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Definition: newgrf.h:146
GetGRFStringID
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:587
CargoChangeInfo
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
Define properties for cargoes.
Definition: newgrf.cpp:2978
SoundEntry
Definition: sound_type.h:13
StationSpec::disallowed_platforms
byte disallowed_platforms
Bitmask of number of platforms available for the station.
Definition: newgrf_station.h:132
stdafx.h
GrfProcessingState::grfconfig
GRFConfig * grfconfig
Config of the currently processed GRF file.
Definition: newgrf.cpp:106
TLF_NON_GROUND_FLAGS
@ TLF_NON_GROUND_FLAGS
Flags which do not work for the (first) ground sprite.
Definition: newgrf_commons.h:55
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
RailTypeInfo::grffile
const GRFFile * grffile[RTSG_END]
NewGRF providing the Action3 for the railtype.
Definition: rail.h:276
landscape.h
OTTDByteReaderSignal
Definition: newgrf.cpp:211
PROP_AIRCRAFT_COST_FACTOR
@ PROP_AIRCRAFT_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:49
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:105
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
PROP_TRAIN_CURVE_SPEED_MOD
@ PROP_TRAIN_CURVE_SPEED_MOD
Modifier to maximum speed in curves.
Definition: newgrf_properties.h:31
IndustryTileSpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:173
SPR_RAILTYPE_TUNNEL_BASE
static const SpriteID SPR_RAILTYPE_TUNNEL_BASE
Tunnel sprites with grass only for custom railtype tunnel.
Definition: sprites.h:299
EngineClass
EngineClass
Type of rail engine.
Definition: engine_type.h:33
PALETTE_MODIFIER_TRANSPARENT
@ PALETTE_MODIFIER_TRANSPARENT
when a sprite is to be displayed transparently, this bit needs to be set.
Definition: sprites.h:1541
NEWGRF_DIR
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
Definition: fileio_type.h:117
IgnoreIndustryProperty
static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
Ignore an industry property.
Definition: newgrf.cpp:3365
GRFTempEngineData::refittability
Refittability refittability
Did the newgrf set any refittability property? If not, default refittability will be applied.
Definition: newgrf.cpp:332
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:155
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:6394
GRFTownName
Definition: newgrf_townname.h:38
A5BLOCK_ALLOW_OFFSET
@ A5BLOCK_ALLOW_OFFSET
Allow replacing any subset by specifiing an offset.
Definition: newgrf.cpp:6395
GRFConfig::palette
uint8_t palette
GRFPalette, bitset.
Definition: newgrf_config.h:170
HouseSpec::population
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:102
PROP_SHIP_RUNNING_COST_FACTOR
@ PROP_SHIP_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:46
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, byte type, uint16_t num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:113
IndustryProductionSpriteGroup::num_input
uint8_t num_input
How many subtract_input values are valid.
Definition: newgrf_spritegroup.h:272
GRFConfig::param_info
std::vector< std::optional< GRFParameterInfo > > param_info
NOSAVE: extra information about the parameters.
Definition: newgrf_config.h:171
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition: engine_type.h:29
RealSpriteGroup::loaded
std::vector< const SpriteGroup * > loaded
List of loaded groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:89
LanguageMap::Mapping
Mapping between NewGRF and OpenTTD IDs.
Definition: newgrf_text.h:55
VehicleSettings::plane_speed
uint8_t plane_speed
divisor for speed of aircraft
Definition: settings_type.h:528
NamePartList::bitstart
byte bitstart
Start of random seed bits to use.
Definition: newgrf_townname.h:25
BuildCargoTranslationMap
static void BuildCargoTranslationMap()
Construct the Cargo Mapping.
Definition: newgrf.cpp:8889
IndustrySpec::number_of_sounds
uint8_t number_of_sounds
Number of sounds available in the sounds array.
Definition: industrytype.h:135
HouseSpec::cargo_acceptance
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:107
WaterFeature::grffile
const GRFFile * grffile
NewGRF where 'group' belongs to.
Definition: newgrf_canal.h:24
HandleNode
static bool HandleNode(byte type, uint32_t id, ByteReader *buf, AllowedSubtags subtags[])
Handle the nodes of an Action14.
Definition: newgrf.cpp:8532
GRFFilePropsBase::local_id
uint16_t local_id
id defined by the grf file for this entity
Definition: newgrf_commons.h:318
ShipVehicleInfo::old_refittable
bool old_refittable
Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
Definition: engine_type.h:75
AllowedSubtags::type
byte type
The type of the node, must be one of 'C', 'B' or 'T'.
Definition: newgrf.cpp:8369
GRFParameterInfo::first_bit
byte first_bit
First bit to use in the GRF parameter.
Definition: newgrf_config.h:136
BuildIndustriesLegend
void BuildIndustriesLegend()
Fills an array for the industries legends.
Definition: smallmap_gui.cpp:186
SetSnowLine
void SetSnowLine(byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
Set a variable snow line, as loaded from a newgrf file.
Definition: landscape.cpp:592
newgrf_object.h
RailTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:231
ReadSpriteLayoutSprite
static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16_t *max_sprite_offset=nullptr, uint16_t *max_palette_offset=nullptr)
Read a sprite and a palette from the GRF and convert them into a format suitable to OpenTTD.
Definition: newgrf.cpp:737
BridgeSpec::min_length
byte min_length
the minimum length (not counting start and end tile)
Definition: bridge.h:44
IndustrySpec::callback_mask
uint16_t callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:138
ObjectSpec::name
StringID name
The name for this object.
Definition: newgrf_object.h:65
ChangeGRFBlitter
static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
Callback function for 'INFO'->'BLTR' to set the blitter info.
Definition: newgrf.cpp:8157
RailTypeInfo::powered_railtypes
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
Definition: rail.h:188
GRFTempEngineData::rv_max_speed
uint8_t rv_max_speed
Temporary storage of RV prop 15, maximum speed in mph/0.8.
Definition: newgrf.cpp:333
RandomAccessFile::GetPos
size_t GetPos() const
Get position in the file.
Definition: random_access_file.cpp:74
AirportSpec::size_x
byte size_x
size of airport in x direction
Definition: newgrf_airport.h:107
FinaliseEngineArray
static void FinaliseEngineArray()
Check for invalid engines.
Definition: newgrf.cpp:9184
GRFParameterType
GRFParameterType
The possible types of a newgrf parameter.
Definition: newgrf_config.h:120
ChangeGRFNumUsedParams
static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
Callback function for 'INFO'->'NPAR' to set the number of valid parameters.
Definition: newgrf.cpp:8119
GRFTempEngineData::UNSET
@ UNSET
No properties assigned. Default refit masks shall be activated.
Definition: newgrf.cpp:322
TranslateRefitMask
static CargoTypes TranslateRefitMask(uint32_t refit_mask)
Translate the refit mask.
Definition: newgrf.cpp:941
ChangeGRFMinVersion
static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
Callback function for 'INFO'->'MINV' to the minimum compatible version of the NewGRF.
Definition: newgrf.cpp:8192
GetGlobalVariable
bool GetGlobalVariable(byte param, uint32_t *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
Definition: newgrf.cpp:6549
RAILTYPE_RAIL
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition: rail_type.h:29
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:62
GCS_UNKNOWN
@ GCS_UNKNOWN
The status of this grf file is unknown.
Definition: newgrf_config.h:35
RailTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: rail.h:178
SpriteFile
RandomAccessFile with some extra information specific for sprite files.
Definition: sprite_file_type.hpp:19
DeterministicSpriteGroupAdjust
Definition: newgrf_spritegroup.h:147
PriceBaseSpec
Describes properties of price bases.
Definition: economy_type.h:207
GRFError::param_value
std::array< uint32_t, 2 > param_value
Values of GRF parameters to show for message and custom_message.
Definition: newgrf_config.h:116
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:140
GRFFile::canal_local_properties
CanalProperties canal_local_properties[CF_END]
Canal properties as set by this NewGRF.
Definition: newgrf.h:141
GRFError
Information about why GRF had problems during initialisation.
Definition: newgrf_config.h:109
RoadTypeInfo::grffile
const GRFFile * grffile[ROTSG_END]
NewGRF providing the Action3 for the roadtype.
Definition: road.h:187
NUM_ROADSTOPS_PER_GRF
static const int NUM_ROADSTOPS_PER_GRF
The maximum amount of roadstops a single GRF is allowed to add.
Definition: newgrf_roadstop.h:23
ChangeGRFDescription
static bool ChangeGRFDescription(byte langid, const char *str)
Callback function for 'INFO'->'DESC' to add a translation to the newgrf description.
Definition: newgrf.cpp:8105
GCS_DISABLED
@ GCS_DISABLED
GRF file is disabled.
Definition: newgrf_config.h:36
CIR_DISABLED
@ CIR_DISABLED
GRF was disabled due to error.
Definition: newgrf.cpp:980
RandomAccessFile::ReadWord
uint16_t ReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: random_access_file.cpp:118
CT_INVALID
static constexpr CargoLabel CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:71
GRFError::message
StringID message
Default message.
Definition: newgrf_config.h:114
AllocateRailType
RailType AllocateRailType(RailTypeLabel label)
Allocate a new rail type label.
Definition: rail_cmd.cpp:150
GRFParameterInfo::max_value
uint32_t max_value
The maximal value of this parameter.
Definition: newgrf_config.h:133
vehicle_func.h
rev.h
CURRENCY_END
@ CURRENCY_END
always the last item
Definition: currency.h:70
PROP_TRAIN_WEIGHT
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:25
PROP_VEHICLE_LOAD_AMOUNT
@ PROP_VEHICLE_LOAD_AMOUNT
Loading speed.
Definition: newgrf_properties.h:19
GRFFile::GRFFile
GRFFile(const struct GRFConfig *config)
Constructor for GRFFile.
Definition: newgrf.cpp:8928
INVALID_TPE
@ INVALID_TPE
Invalid town production effect.
Definition: cargotype.h:44
CT_PASSENGERS
static constexpr CargoLabel CT_PASSENGERS
Available types of cargo Labels may be re-used between different climates.
Definition: cargo_type.h:30
CargoSpec::town_production_effect
TownProductionEffect town_production_effect
The effect on town cargo production.
Definition: cargotype.h:81
VehicleSettings::dynamic_engines
bool dynamic_engines
enable dynamic allocation of engine data
Definition: settings_type.h:530
newgrf_sound.h
RoadVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:127
Pool::PoolItem<&_engine_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:320
GRFConfig::flags
uint8_t flags
NOSAVE: GCF_Flags, bitset.
Definition: newgrf_config.h:164
GRFP_GRF_WINDOWS
@ GRFP_GRF_WINDOWS
The NewGRF says the Windows palette can be used.
Definition: newgrf_config.h:72
strings_func.h
TLF_VAR10_FLAGS
@ TLF_VAR10_FLAGS
Flags which refer to using multiple action-1-2-3 chains.
Definition: newgrf_commons.h:58
TimerGameEconomy::year
static Year year
Current year, starting at 0.
Definition: timer_game_economy.h:35
StationSpec
Station specification.
Definition: newgrf_station.h:112
CLEAN_RANDOMSOUNDS
@ CLEAN_RANDOMSOUNDS
Free the dynamically allocated sounds table.
Definition: industrytype.h:22
AirportSpec::enabled
bool enabled
Entity still available (by default true). Newgrf can disable it, though.
Definition: newgrf_airport.h:119
SetNewGRFOverride
static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
Set the override for a NewGRF.
Definition: newgrf.cpp:584
LanguageMap
Mapping of language data between a NewGRF and OpenTTD.
Definition: newgrf_text.h:53
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:28
IndustrySpec::removal_cost_multiplier
uint32_t removal_cost_multiplier
Base removal cost multiplier.
Definition: industrytype.h:108
IndustrytilesChangeInfo
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
Define properties for industry tiles.
Definition: newgrf.cpp:3231
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:126
bridge.h
RailTypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: rail.h:246
EngineIDMapping::internal_id
uint16_t internal_id
The internal ID within the GRF file.
Definition: engine_base.h:194
NEW_AIRPORT_OFFSET
@ NEW_AIRPORT_OFFSET
Number of the first newgrf airport.
Definition: airport.h:39
RandomAccessFile::SkipBytes
void SkipBytes(size_t n)
Skip n bytes ahead in the file.
Definition: random_access_file.cpp:149
EngineInfo::base_life
TimerGameCalendar::Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life.
Definition: engine_type.h:147
GameCreationSettings::generation_seed
uint32_t generation_seed
noise seed for world generation
Definition: settings_type.h:340
GRFTempEngineData
Temporary engine data used when loading only.
Definition: newgrf.cpp:319
CC_ARMOURED
@ CC_ARMOURED
Armoured cargo (Valuables, Gold, Diamonds)
Definition: cargotype.h:53
ResetNewGRFErrors
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8766
IsHouseSpecValid
static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const std::string &filename)
Check if a given housespec is valid and disable it if it's not.
Definition: newgrf.cpp:9281
GRFConfig::name
GRFTextWrapper name
NOSAVE: GRF name (Action 0x08)
Definition: newgrf_config.h:157
ResetNewGRF
static void ResetNewGRF()
Reset and clear all NewGRFs.
Definition: newgrf.cpp:8755
GRFLoadedFeatures::tram
TramReplacement tram
In which way tram depots were replaced.
Definition: newgrf.h:181
GRFConfig::param
std::array< uint32_t, 0x80 > param
GRF parameters.
Definition: newgrf_config.h:167
GRFParameterInfo::desc
GRFTextList desc
The description of this parameter.
Definition: newgrf_config.h:130
AllowedSubtags
Data structure to store the allowed id/type combinations for action 14.
Definition: newgrf.cpp:8311
FinaliseAirportsArray
static void FinaliseAirportsArray()
Add all new airports to the airport array.
Definition: newgrf.cpp:9524
TileLayoutRegisters::parent
uint8_t parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
Definition: newgrf_commons.h:98
RailTypeInfo::fallback_railtype
byte fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition: rail.h:201
SHORE_REPLACE_ACTION_A
@ SHORE_REPLACE_ACTION_A
Shore sprites were replaced by ActionA (using grass tiles for the corner-shores).
Definition: newgrf.h:167
GCF_RESERVED
@ GCF_RESERVED
GRF file passed GLS_RESERVE stage.
Definition: newgrf_config.h:29
NamePartList
Definition: newgrf_townname.h:24
TRAMWAY_REPLACE_DEPOT_WITH_TRACK
@ TRAMWAY_REPLACE_DEPOT_WITH_TRACK
Electrified depot graphics with tram track were loaded.
Definition: newgrf.h:173
abs
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:23
IndustryTileSpec::animation
AnimationInfo animation
Information about the animation (is it looping, how many loops etc)
Definition: industrytype.h:170
MapSpriteMappingRecolour
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
Map the colour modifiers of TTDPatch to those that Open is using.
Definition: newgrf.cpp:706
ObjectSpec::climate
uint8_t climate
In which climates is this object available?
Definition: newgrf_object.h:67
TranslateTTDPatchCodes
std::string TranslateTTDPatchCodes(uint32_t grfid, uint8_t language_id, bool allow_newlines, const std::string &str, StringControlCode byte80)
Translate TTDPatch string codes into something OpenTTD can handle (better).
Definition: newgrf_text.cpp:236
RAILTYPE_END
@ RAILTYPE_END
Used for iterations.
Definition: rail_type.h:33
CC_REFRIGERATED
@ CC_REFRIGERATED
Refrigerated cargo (Food, Fruit)
Definition: cargotype.h:57
CommonVehicleChangeInfo
static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
Define properties common to all vehicles.
Definition: newgrf.cpp:995
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:371
RealSpriteGroup
Definition: newgrf_spritegroup.h:79
AllowedSubtags::subtags
AllowedSubtags * subtags
Pointer to a list of subtags, only valid if type == 'C' && !call_handler.
Definition: newgrf.cpp:8376
MCT_LIVESTOCK_FRUIT
@ MCT_LIVESTOCK_FRUIT
Cargo can be livestock or fruit.
Definition: cargo_type.h:84
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:8301
Action5Type::block_type
Action5BlockType block_type
How is this Action5 type processed?
Definition: newgrf.cpp:6400
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition: newgrf_airport.h:120
CargoSpec::quantifier
StringID quantifier
Text for multiple units of cargo of this type.
Definition: cargotype.h:88
IndustrySpec::random_sounds
const uint8_t * random_sounds
array of random sounds.
Definition: industrytype.h:136
SPR_AIRPORT_PREVIEW_BASE
static const SpriteID SPR_AIRPORT_PREVIEW_BASE
Airport preview sprites.
Definition: sprites.h:248
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:174
industrytype.h
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition: engine_type.h:28
TimerGame< struct Calendar >::IsLeapYear
static constexpr bool IsLeapYear(Year year)
Checks whether the given year is a leap year or not.
Definition: timer_game_common.h:63
GetEngineLiveryScheme
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
Definition: vehicle.cpp:1941
ShipVehicleInfo::acceleration
uint8_t acceleration
Acceleration (1 unit = 1/3.2 mph per tick = 0.5 km-ish/h per tick)
Definition: engine_type.h:70
LanguagePackHeader::GetGenderIndex
uint8_t GetGenderIndex(const char *gender_str) const
Get the index for the given gender.
Definition: language.h:68
InitializeSortedCargoSpecs
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
Definition: cargotype.cpp:201
EngineInfo::variant_id
EngineID variant_id
Engine variant ID. If set, will be treated specially in purchase lists.
Definition: engine_type.h:160
EngineOverrideManager::GetID
EngineID GetID(VehicleType type, uint16_t grf_local_id, uint32_t grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:532
GrfProcessingState::AddSpriteSets
void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
Records new spritesets.
Definition: newgrf.cpp:136
SPR_OPENTTD_BASE
static const SpriteID SPR_OPENTTD_BASE
Extra graphic spritenumbers.
Definition: sprites.h:56
SpriteGroupCargo::SG_PURCHASE
static constexpr CargoID SG_PURCHASE
Used in purchase lists before an item exists.
Definition: newgrf_cargo.h:24
IndustrySpec::production_down_text
StringID production_down_text
Message appearing when the industry's production is decreasing.
Definition: industrytype.h:131
TAE_WATER
@ TAE_WATER
Cargo behaves water-like.
Definition: cargotype.h:27
TRAMWAY_REPLACE_DEPOT_NONE
@ TRAMWAY_REPLACE_DEPOT_NONE
No tram depot graphics were loaded.
Definition: newgrf.h:172
RailVehicleInfo::user_def_data
byte user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition: engine_type.h:62
AlterVehicleListOrder
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
Definition: newgrf_engine.cpp:1299
GetNewEngineID
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
Return the ID of a new engine.
Definition: newgrf.cpp:690
RoadVehicleChangeInfo
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for road vehicles.
Definition: newgrf.cpp:1347
LanguageMap::GetLanguageMap
static const LanguageMap * GetLanguageMap(uint32_t grfid, uint8_t language_id)
Get the language map associated with a given NewGRF and language.
Definition: newgrf.cpp:2629
AirportTileSpec::enabled
bool enabled
entity still available (by default true). newgrf can disable it, though
Definition: newgrf_airporttiles.h:73
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:330
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
_ttdpatch_flags
static uint32_t _ttdpatch_flags[8]
32 * 8 = 256 flags.
Definition: newgrf.cpp:79
TRAMWAY_REPLACE_DEPOT_NO_TRACK
@ TRAMWAY_REPLACE_DEPOT_NO_TRACK
Electrified depot graphics without tram track were loaded.
Definition: newgrf.h:174
RoadTypeInfo::map_colour
byte map_colour
Colour on mini-map.
Definition: road.h:157
NewGRFSpriteLayout::consistent_max_offset
uint consistent_max_offset
Number of sprites in all referenced spritesets.
Definition: newgrf_commons.h:119
HouseSpec::watched_cargoes
CargoTypes watched_cargoes
Cargo types watched for acceptance.
Definition: house.h:124
IsSnowLineSet
bool IsSnowLineSet()
Has a snow line table already been loaded.
Definition: landscape.cpp:582
StationClassID
StationClassID
Definition: newgrf_station.h:83
ConstructionSettings::train_signal_side
byte train_signal_side
show signals on left / driving / right side
Definition: settings_type.h:376
HouseSpec::class_id
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:120
GRFParameterInfo::name
GRFTextList name
The name of this parameter.
Definition: newgrf_config.h:129
IndustrySpec::cleanup_flag
uint8_t cleanup_flag
flags indicating which data should be freed upon cleaning up
Definition: industrytype.h:139
GRFParameterInfo::def_value
uint32_t def_value
Default value of this parameter.
Definition: newgrf_config.h:134
RailVehicleInfo::weight
uint16_t weight
Weight of vehicle (tons); For multiheaded engines the weight of each single engine.
Definition: engine_type.h:50
Pool::PoolItem<&_engine_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:309
IndustryTileLayoutTile
Definition of one tile in an industry tile layout.
Definition: industrytype.h:94
EngineInfo::cargo_age_period
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:159
VehicleSettings::disable_elrails
bool disable_elrails
when true, the elrails are disabled
Definition: settings_type.h:523
TimerGameConst< struct Calendar >::MIN_YEAR
static constexpr TimerGame< struct Calendar >::Year MIN_YEAR
The absolute minimum year in OTTD.
Definition: timer_game_common.h:176
InitNewGRFFile
static void InitNewGRFFile(const GRFConfig *config)
Prepare loading a NewGRF file with its config.
Definition: newgrf.cpp:8911
CommitVehicleListOrderChanges
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
Definition: newgrf_engine.cpp:1329
ShipVehicleInfo
Information about a ship vehicle.
Definition: engine_type.h:67
HouseSpec::building_availability
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:111
NFO_UTF8_IDENTIFIER
static const char32_t NFO_UTF8_IDENTIFIER
This character, the thorn ('þ'), indicates a unicode string to NFO.
Definition: newgrf_text.h:19
NewGRFClass::name
StringID name
Name of this class.
Definition: newgrf_class.h:39
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:25
MapGRFStringID
StringID MapGRFStringID(uint32_t grfid, StringID str)
Used when setting an object's property to map to the GRF's strings while taking in consideration the ...
Definition: newgrf.cpp:550
RoadTypeFlags
RoadTypeFlags
Roadtype flags.
Definition: road.h:46
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
AirportSpec::GetWithoutOverride
static AirportSpec * GetWithoutOverride(byte type)
Retrieve airport spec for the given airport.
Definition: newgrf_airport.cpp:74
TileLayoutFlags
TileLayoutFlags
Flags to enable register usage in sprite layouts.
Definition: newgrf_commons.h:32
CargoSpec::name
StringID name
Name of this type of cargo.
Definition: cargotype.h:85
PROP_ROADVEH_CARGO_CAPACITY
@ PROP_ROADVEH_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:34
RailVehicleInfo::railtype
RailType railtype
Railtype, mangled if elrail is disabled.
Definition: engine_type.h:46
ResetNewGRFData
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8776
AircraftVehicleChangeInfo
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
Define properties for aircraft.
Definition: newgrf.cpp:1745
GRFFile::cargo_list
std::vector< CargoLabel > cargo_list
Cargo translation table (local ID -> label)
Definition: newgrf.h:129
SanitizeSpriteOffset
static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const char *name)
Sanitize incoming sprite offsets for Action 5 graphics replacements.
Definition: newgrf.cpp:6371
GrfMsgI
void GrfMsgI(int severity, const std::string &msg)
Debug() function dedicated to newGRF debugging messages Function is essentially the same as Debug(grf...
Definition: newgrf.cpp:393
PalSpriteID
Combination of a palette sprite and a 'real' sprite.
Definition: gfx_type.h:22
GRFConfig::url
GRFTextWrapper url
NOSAVE: URL belonging to this GRF.
Definition: newgrf_config.h:159
GRFFile::labels
std::vector< GRFLabel > labels
List of labels.
Definition: newgrf.h:127
VSG_SCOPE_RELATIVE
@ VSG_SCOPE_RELATIVE
Relative position (vehicles only)
Definition: newgrf_spritegroup.h:102
ActivateOldTramDepot
static void ActivateOldTramDepot()
Replocate the old tram depot sprites to the new position, if no new ones were loaded.
Definition: newgrf.cpp:9793
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, AllowedSubtags *subtags)
Create a branch node with a list of sub-nodes.
Definition: newgrf.cpp:8360
container_func.hpp
ExtraEngineFlags
ExtraEngineFlags
Definition: engine_type.h:131
HZ_CLIMALL
@ HZ_CLIMALL
Bitmask of all climate bits.
Definition: house.h:84
RoadTypeInfo::strings
struct RoadTypeInfo::@29 strings
Strings associated with the rail type.
GrfProcessingState::stage
GrfLoadingStage stage
Current loading stage.
Definition: newgrf.cpp:100
ORIGINAL_SAMPLE_COUNT
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition: sound_type.h:116
_gted
static std::vector< GRFTempEngineData > _gted
Temporary engine data used during NewGRF loading.
Definition: newgrf.cpp:351
IgnoreObjectProperty
static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
Ignore properties for objects.
Definition: newgrf.cpp:4070
CHECK_NOTHING
@ CHECK_NOTHING
Always succeeds.
Definition: industrytype.h:38
AircraftVehicleInfo::mail_capacity
byte mail_capacity
Mail capacity (bags).
Definition: engine_type.h:108
NamePart
Definition: newgrf_townname.h:18
CargoSpec::name_single
StringID name_single
Name of a single entity of this type of cargo.
Definition: cargotype.h:86
GRFTownName::MAX_LISTS
static const uint MAX_LISTS
Maximum number of town name lists that can be defined per GRF.
Definition: newgrf_townname.h:39
PTYPE_END
@ PTYPE_END
Invalid parameter type.
Definition: newgrf_config.h:123
AllowedSubtags::id
uint32_t id
The identifier for this node.
Definition: newgrf.cpp:8368
GrfProcessingState::GetNumEnts
uint GetNumEnts(byte feature, uint set) const
Returns the number of sprites in a spriteset.
Definition: newgrf.cpp:189
CargoSpec::abbrev
StringID abbrev
Two letter abbreviation for this cargo type.
Definition: cargotype.h:89
HouseSpec::processing_time
byte processing_time
Periodic refresh multiplier.
Definition: house.h:122
IndustrySpec::life_type
IndustryLifeType life_type
This is also known as Industry production flag, in newgrf specs.
Definition: industrytype.h:123
Action5Type::name
const char * name
Name for error messages.
Definition: newgrf.cpp:6404
WaterFeature::flags
uint8_t flags
Flags controlling display.
Definition: newgrf_canal.h:26
RailVehicleInfo::power
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition: engine_type.h:49
FinaliseHouseArray
static void FinaliseHouseArray()
Add all new houses to the house array.
Definition: newgrf.cpp:9354
RailVehicleInfo::intended_railtype
RailType intended_railtype
Intended railtype, regardless of elrail being enabled or disabled.
Definition: engine_type.h:47
ObjectSpec::build_cost_multiplier
uint8_t build_cost_multiplier
Build cost multiplier per tile.
Definition: newgrf_object.h:69
NamePartList::parts
std::vector< NamePart > parts
List of parts to choose from.
Definition: newgrf_townname.h:28
LoadTranslationTable
static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, std::vector< T > &translation_table, const char *name)
Load a cargo- or railtype-translation table.
Definition: newgrf.cpp:2646
NewGRFSpriteLayout::Clone
void Clone(const DrawTileSeqStruct *source)
Clone the building sprites of a spritelayout.
Definition: newgrf_commons.cpp:565
TileIndexDiffC::y
int16_t y
The y value of the coordinate.
Definition: map_type.h:33
RandomAccessFile::SeekTo
void SeekTo(size_t pos, int mode)
Seek in the current file.
Definition: random_access_file.cpp:84
RailTypeInfo::introduces_railtypes
RailTypes introduces_railtypes
Bitmask of which other railtypes are introduced when this railtype is introduced.
Definition: rail.h:266
RailVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:59
CurrencySpec::to_euro
TimerGameCalendar::Year to_euro
Year of switching to the Euro. May also be CF_NOEURO or CF_ISEURO.
Definition: currency.h:76
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:164
DrawTileSprites::seq
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition: sprite.h:60
CIR_UNKNOWN
@ CIR_UNKNOWN
Variable is unknown.
Definition: newgrf.cpp:982
GRFTempEngineData::NONEMPTY
@ NONEMPTY
GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not av...
Definition: newgrf.cpp:324
TimerGame< struct Calendar >::DateFract
uint16_t DateFract
The fraction of a date we're in, i.e.
Definition: timer_game_common.h:38
IndustrySpec::behaviour
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Definition: industrytype.h:125
ResetObjects
void ResetObjects()
This function initialize the spec arrays of objects.
Definition: newgrf_object.cpp:121
EngineInfo::retire_early
int8_t retire_early
Number of years early to retire vehicle.
Definition: engine_type.h:157
TileLayoutRegisters::sprite
uint8_t sprite
Register specifying a signed offset for the sprite.
Definition: newgrf_commons.h:93
RoadTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:142
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:300
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:124
RailVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:48
NewGRFClass::Get
static NewGRFClass * Get(Tid cls_id)
Get a particular class.
Definition: newgrf_class_func.h:98
Map::LogY
static uint LogY()
Logarithm of the map size along the y side.
Definition: map_func.h:261
InitializeGRFSpecial
static void InitializeGRFSpecial()
Initialize the TTDPatch flags.
Definition: newgrf.cpp:8605
BridgeSpec::avail_year
TimerGameCalendar::Year avail_year
the year where it becomes available
Definition: bridge.h:43
MemSetT
void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
HouseSpec::accepts_cargo_label
CargoLabel accepts_cargo_label[HOUSE_NUM_ACCEPTS]
input landscape cargo slots
Definition: house.h:109
DataHandler
bool(* DataHandler)(size_t, ByteReader *)
Type of callback function for binary nodes.
Definition: newgrf.cpp:8300
GRFIdentifier::grfid
uint32_t grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:84
RandomizedSpriteGroup::lowest_randbit
byte lowest_randbit
Look for this in the per-object randomized bitmask:
Definition: newgrf_spritegroup.h:199
ActivateOldShore
static void ActivateOldShore()
Relocates the old shore sprites at new positions.
Definition: newgrf.cpp:9756
AircraftVehicleInfo::passenger_capacity
uint16_t passenger_capacity
Passenger capacity (persons).
Definition: engine_type.h:109
BridgeSpec::material
StringID material
the string that contains the bridge description
Definition: bridge.h:50
TileLayoutRegisters::flags
TileLayoutFlags flags
Flags defining which members are valid and to be used.
Definition: newgrf_commons.h:91
AirportSpec::depot_table
const HangarTileTable * depot_table
gives the position of the depots on the airports
Definition: newgrf_airport.h:105
GRFConfig::num_params
uint8_t num_params
Number of used parameters.
Definition: newgrf_config.h:168
SkipUnknownInfo
static bool SkipUnknownInfo(ByteReader *buf, byte type)
Try to skip the current node and all subnodes (if it's a branch node).
Definition: newgrf.cpp:8492
LanguagePackHeader::GetCaseIndex
uint8_t GetCaseIndex(const char *case_str) const
Get the index for the given case.
Definition: language.h:81
newgrf_canal.h
TimerGameConst< struct Calendar >::ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: timer_game_common.h:163
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_LVL_BASE.
Definition: tile_type.h:18
IgnoreTownHouseProperty
static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
Ignore a house property.
Definition: newgrf.cpp:2306
RoadStopDrawMode
RoadStopDrawMode
Different draw modes to disallow rendering of some parts of the stop or road.
Definition: newgrf_roadstop.h:58
ROADTYPE_TRAM
@ ROADTYPE_TRAM
Trams.
Definition: road_type.h:28
TileLayoutRegisters::child
uint8_t child[2]
Registers for signed offsets for the position of child sprites.
Definition: newgrf_commons.h:99
VehicleSettings::never_expire_vehicles
bool never_expire_vehicles
never expire vehicles
Definition: settings_type.h:531
OverrideManagerBase::Add
void Add(uint16_t local_id, uint32_t grfid, uint entity_type)
Since the entity IDs defined by the GRF file does not necessarily correlate to those used by the game...
Definition: newgrf_commons.cpp:62
HouseSpec
Definition: house.h:98
config.h
GetNewgrfCurrencyIdConverted
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id)
Will return the ottd's index correspondence to the ttdpatch's id.
Definition: currency.cpp:115
GrfProcessingState::SpriteSet::num_sprites
uint num_sprites
Number of sprites in the set.
Definition: newgrf.cpp:92
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:24
RoadVehicleInfo::weight
uint8_t weight
Weight in 1/4t units.
Definition: engine_type.h:122
PROP_SHIP_COST_FACTOR
@ PROP_SHIP_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:43
ChangeInfoResult
ChangeInfoResult
Possible return values for the FeatureChangeInfo functions.
Definition: newgrf.cpp:978
engine_base.h
IndustryProductionSpriteGroup::cargo_output
CargoID cargo_output[INDUSTRY_NUM_OUTPUTS]
Which output cargoes to add to (only cb version 2)
Definition: newgrf_spritegroup.h:277
SpriteGroupCargo::SG_DEFAULT_NA
static constexpr CargoID SG_DEFAULT_NA
Used only by stations and roads when no more-specific cargo matches.
Definition: newgrf_cargo.h:25
IgnoreRoadStopProperty
static ChangeInfoResult IgnoreRoadStopProperty(uint prop, ByteReader *buf)
Ignore properties for roadstops.
Definition: newgrf.cpp:4776
BridgeChangeInfo
static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
Define properties for bridges.
Definition: newgrf.cpp:2195
RailTypeInfo::flags
RailTypeFlags flags
Bit mask of rail type flags.
Definition: rail.h:211
fontcache.h
_object_mngr
ObjectOverrideManager _object_mngr
The override manager for our objects.
RandomAccessFile::ReadDword
uint32_t ReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: random_access_file.cpp:128
HouseZones
HouseZones
Definition: house.h:71
ShipVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:71
ReadDWordAsString
static std::string ReadDWordAsString(ByteReader *reader)
Helper to read a DWord worth of bytes from the reader and to return it as a valid string.
Definition: newgrf.cpp:2667
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
RailTypeChangeInfo
static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
Define properties for railtypes.
Definition: newgrf.cpp:4249
Engine::grf_prop
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:77
RAILVEH_SINGLEHEAD
@ RAILVEH_SINGLEHEAD
indicates a "standalone" locomotive
Definition: engine_type.h:27
MCT_VALUABLES_GOLD_DIAMONDS
@ MCT_VALUABLES_GOLD_DIAMONDS
Cargo can be valuables, gold or diamonds.
Definition: cargo_type.h:86
GRFFile::GetParam
uint32_t GetParam(uint number) const
Get GRF Parameter with range checking.
Definition: newgrf.h:155
IndustryTileSpecialFlags
IndustryTileSpecialFlags
Flags for miscellaneous industry tile specialities.
Definition: industrytype.h:86
IndustrySpec::check_proc
byte check_proc
Index to a procedure to check for conflicting circumstances.
Definition: industrytype.h:111
ReadGRFSpriteOffsets
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Definition: spritecache.cpp:553
SB
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
RailVehicleInfo::running_cost
byte running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition: engine_type.h:51
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:169
GetRailTypeByLabel
RailType GetRailTypeByLabel(RailTypeLabel label, bool allow_alternate_labels)
Get the rail type for a given label.
Definition: rail.cpp:311
NEW_INDUSTRYTILEOFFSET
static const IndustryGfx NEW_INDUSTRYTILEOFFSET
original number of tiles
Definition: industry_type.h:32
newgrf_industries.h
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
EconomySettings::inflation
bool inflation
disable inflation
Definition: settings_type.h:539
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition: timer_game_calendar.h:34
TAE_NONE
@ TAE_NONE
Cargo has no effect.
Definition: cargotype.h:23
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:620
GrfProcessingState::IsValidSpriteSet
bool IsValidSpriteSet(byte feature, uint set) const
Check whether a specific set is defined.
Definition: newgrf.cpp:165
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:627
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:202
EngineID
uint16_t EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
TLF_PALETTE_REG_FLAGS
@ TLF_PALETTE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the palette, even if it is no action-1 palet...
Definition: newgrf_commons.h:64
TLF_SPRITE
@ TLF_SPRITE
Add signed offset to sprite from register TileLayoutRegisters::sprite.
Definition: newgrf_commons.h:36
ClearTemporaryNewGRFData
static void ClearTemporaryNewGRFData(GRFFile *gf)
Reset all NewGRFData that was used only while processing data.
Definition: newgrf.cpp:425
EngineInfo::climates
byte climates
Climates supported by the engine.
Definition: engine_type.h:150
TLF_PALETTE
@ TLF_PALETTE
Add signed offset to palette from register TileLayoutRegisters::palette.
Definition: newgrf_commons.h:37
PTYPE_UINT_ENUM
@ PTYPE_UINT_ENUM
The parameter allows a range of numbers, each of which can have a special name.
Definition: newgrf_config.h:121
AirportSpec::nof_depots
byte nof_depots
the number of hangar tiles in this airport
Definition: newgrf_airport.h:106
_grm_cargoes
static uint32_t _grm_cargoes[NUM_CARGO *2]
Contains the GRF ID of the owner of a cargo if it has been reserved.
Definition: newgrf.cpp:360
PROP_AIRCRAFT_PASSENGER_CAPACITY
@ PROP_AIRCRAFT_PASSENGER_CAPACITY
Passenger Capacity.
Definition: newgrf_properties.h:52
PROP_SHIP_SPEED
@ PROP_SHIP_SPEED
Max. speed: 1 unit = 1/3.2 mph = 0.5 km-ish/h.
Definition: newgrf_properties.h:44
ClearSnowLine
void ClearSnowLine()
Clear the variable snow line table and free the memory.
Definition: landscape.cpp:643
HouseSpec::random_colour
Colours random_colour[4]
4 "random" colours
Definition: house.h:117
ResetRoadTypes
void ResetRoadTypes()
Reset all road type information to its default values.
Definition: road_cmd.cpp:67
AirportTileSpec::callback_mask
uint8_t callback_mask
Bitmask telling which grf callback is set.
Definition: newgrf_airporttiles.h:71
GRFPalette
GRFPalette
Information that can/has to be stored about a GRF's palette.
Definition: newgrf_config.h:59
StationSpec::callback_mask
byte callback_mask
Bitmask of station callbacks that have to be called.
Definition: newgrf_station.h:157
PROP_ROADVEH_POWER
@ PROP_ROADVEH_POWER
Power in 10 HP.
Definition: newgrf_properties.h:36
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
RandomizedSpriteGroup
Definition: newgrf_spritegroup.h:190
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:8288
IndustryBehaviour
IndustryBehaviour
Various industry behaviours mostly to represent original TTD specialities.
Definition: industrytype.h:59
PROP_TRAIN_COST_FACTOR
@ PROP_TRAIN_COST_FACTOR
Purchase cost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:26
IndustrySpec::new_industry_text
StringID new_industry_text
Message appearing when the industry is built.
Definition: industrytype.h:128
StationSpec::disallowed_lengths
byte disallowed_lengths
Bitmask of platform lengths available for the station.
Definition: newgrf_station.h:137
_misc_grf_features
byte _misc_grf_features
Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E.
Definition: newgrf.cpp:76
RailVehicleInfo::capacity
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition: engine_type.h:54
IndustryProductionSpriteGroup::cargo_input
CargoID cargo_input[INDUSTRY_NUM_INPUTS]
Which input cargoes to take from (only cb version 2)
Definition: newgrf_spritegroup.h:274
DefineGotoLabel
static void DefineGotoLabel(ByteReader *buf)
Action 0x10 - Define goto label.
Definition: newgrf.cpp:7819
TPE_PASSENGERS
@ TPE_PASSENGERS
Cargo behaves passenger-like for production.
Definition: cargotype.h:36
ByteReader
Class to read from a NewGRF file.
Definition: newgrf.cpp:214
LoadGRFSound
static void LoadGRFSound(size_t offs, SoundEntry *sound)
Load a sound from a file.
Definition: newgrf.cpp:7868
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
TTDPStringIDToOTTDStringIDMapping
static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
Perform a mapping from TTDPatch's string IDs to OpenTTD's string IDs, but only for the ones we are aw...
Definition: newgrf.cpp:486
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:319
PROP_AIRCRAFT_SPEED
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
Definition: newgrf_properties.h:50
CanalProperties
Canal properties local to the NewGRF.
Definition: newgrf.h:39
CargoSpec::town_production_multiplier
uint16_t town_production_multiplier
Town production multipler, if commanded by TownProductionEffect.
Definition: cargotype.h:82
ResetBridges
void ResetBridges()
Reset the data been eventually changed by the grf loaded.
Definition: tunnelbridge_cmd.cpp:86
Utf8Decode
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:438
AllowedSubtags::data
DataHandler data
Callback function for a binary node, only valid if type == 'B'.
Definition: newgrf.cpp:8371
AirportTileTable::ti
TileIndexDiffC ti
Tile offset from the top-most airport tile.
Definition: newgrf_airport.h:26
NUM_CARGO
static const CargoID NUM_CARGO
Maximum number of cargo types in a game.
Definition: cargo_type.h:74
EngineInfo::string_id
StringID string_id
Default name of engine.
Definition: engine_type.h:158
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition: engine_type.h:100
GetLanguage
const LanguageMetadata * GetLanguage(byte newgrflangid)
Get the language with the given NewGRF language ID.
Definition: strings.cpp:2048
RailTypeFlags
RailTypeFlags
Railtype flags.
Definition: rail.h:35
TileLayoutRegisters::max_sprite_offset
uint16_t max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset)
Definition: newgrf_commons.h:95
AirportSpec::table
const AirportTileTable *const * table
list of the tiles composing the airport
Definition: newgrf_airport.h:102
HangarTileTable
A list of all hangar tiles in an airport.
Definition: newgrf_airport.h:91
DrawTileSeqStruct::delta_x
int8_t delta_x
0x80 is sequence terminator
Definition: sprite.h:26
CreateGroupFromGroupID
static const SpriteGroup * CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16_t spriteid)
Helper function to either create a callback or a result sprite group.
Definition: newgrf.cpp:5166
PROP_TRAIN_POWER
@ PROP_TRAIN_POWER
Power in hp (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:22
AirportTileSpec::Get
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
Definition: newgrf_airporttiles.cpp:37
HouseSpec::min_year
TimerGameCalendar::Year min_year
introduction year of the house
Definition: house.h:100
TownHouseChangeInfo
static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
Define properties for houses.
Definition: newgrf.cpp:2373
HouseSpec::remove_rating_decrease
uint16_t remove_rating_decrease
rating decrease if removed
Definition: house.h:105
TAE_MAIL
@ TAE_MAIL
Cargo behaves mail-like.
Definition: cargotype.h:25
IndustryOverrideManager::SetEntitySpec
void SetEntitySpec(IndustrySpec *inds)
Method to install the new industry data in its proper slot The slot assignment is internal of this me...
Definition: newgrf_commons.cpp:243
PROP_TRAIN_CARGO_AGE_PERIOD
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:30
ResetIndustries
void ResetIndustries()
This function initialize the spec arrays of both industry and industry tiles.
Definition: industry_cmd.cpp:80
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
ChangeGRFPalette
static bool ChangeGRFPalette(size_t len, ByteReader *buf)
Callback function for 'INFO'->'PALS' to set the number of valid parameters.
Definition: newgrf.cpp:8131
LoadFontGlyph
static void LoadFontGlyph(ByteReader *buf)
Action 0x12.
Definition: newgrf.cpp:7988
PROP_ROADVEH_RUNNING_COST_FACTOR
@ PROP_ROADVEH_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:33
SPR_TRACKS_FOR_SLOPES_BASE
static const SpriteID SPR_TRACKS_FOR_SLOPES_BASE
Sprites for 'highlighting' tracks on sloped land.
Definition: sprites.h:198
ResultSpriteGroup
Definition: newgrf_spritegroup.h:236
GetCargoTranslation
CargoID GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:79
IndustryTileSpec::anim_next
byte anim_next
Next frame in an animation.
Definition: industrytype.h:162
IndustryTileSpec
Defines the data structure of each individual tile of an industry.
Definition: industrytype.h:156
GRFLoadedFeatures
Definition: newgrf.h:177
TLF_DRAWING_FLAGS
@ TLF_DRAWING_FLAGS
Flags which are still required after loading the GRF.
Definition: newgrf_commons.h:52
TLF_PALETTE_VAR10
@ TLF_PALETTE_VAR10
Resolve palette with a specific value in variable 10.
Definition: newgrf_commons.h:47
InitRailTypes
void InitRailTypes()
Resolve sprites of custom rail types.
Definition: rail_cmd.cpp:130
CurrencySpec::prefix
std::string prefix
Prefix to apply when formatting money in this currency.
Definition: currency.h:77
CC_MAIL
@ CC_MAIL
Mail.
Definition: cargotype.h:51
RailTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: rail.h:179
RoadVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:120
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
DisableGrf
static GRFError * DisableGrf(StringID message=STR_NULL, GRFConfig *config=nullptr)
Disable a GRF.
Definition: newgrf.cpp:436
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition: newgrf_airporttiles.h:74
TLF_SPRITE_REG_FLAGS
@ TLF_SPRITE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the sprite, even if it is no action-1 sprite...
Definition: newgrf_commons.h:61
InitRoadTypes
void InitRoadTypes()
Resolve sprites of custom road types.
Definition: road_cmd.cpp:114
RailTypeInfo::acceleration_type
uint8_t acceleration_type
Acceleration type of this rail type.
Definition: rail.h:226
RoadTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: road.h:106
GrfProcessingState::skip_sprites
int skip_sprites
Number of pseudo sprites to skip before processing the next one. (-1 to skip to end of file)
Definition: newgrf.cpp:110
RailTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: rail.h:180
OpenCachedSpriteFile
SpriteFile & OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
Open/get the SpriteFile that is cached for use in the sprite cache.
Definition: spritecache.cpp:84
ResetCustomStations
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8694
HZ_ZON1
@ HZ_ZON1
0..4 1,2,4,8,10 which town zones the building can be built in, Zone1 been the further suburb
Definition: house.h:73
TLF_SPRITE_VAR10
@ TLF_SPRITE_VAR10
Resolve sprite with a specific value in variable 10.
Definition: newgrf_commons.h:46
PROP_AIRCRAFT_RANGE
@ PROP_AIRCRAFT_RANGE
Aircraft range.
Definition: newgrf_properties.h:55
EconomySettings::allow_town_roads
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Definition: settings_type.h:555
GRFFile::cargo_map
std::array< uint8_t, NUM_CARGO > cargo_map
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:130
BuildLinkStatsLegend
void BuildLinkStatsLegend()
Populate legend table for the link stat view.
Definition: smallmap_gui.cpp:216
ChangeGRFParamDescription
static bool ChangeGRFParamDescription(byte langid, const char *str)
Callback function for 'INFO'->'PARAM'->param_num->'DESC' to set the description of a parameter.
Definition: newgrf.cpp:8221
IndustrySpec::input_cargo_multiplier
uint16_t input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes)
Definition: industrytype.h:122
RoadTypeInfo::introduction_required_roadtypes
RoadTypes introduction_required_roadtypes
Bitmask of roadtypes that are required for this roadtype to be introduced at a given introduction_dat...
Definition: road.h:172
ReadSpriteLayout
static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
Read a spritelayout from the GRF.
Definition: newgrf.cpp:848
TileIndexDiffC::x
int16_t x
The x value of the coordinate.
Definition: map_type.h:32
newgrf_cargo.h
SetYearEngineAgingStops
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:657
GRFFile::railtype_list
std::vector< RailTypeLabel > railtype_list
Railtype translation table.
Definition: newgrf.h:132
AirportSpec::catchment
byte catchment
catchment area of this airport
Definition: newgrf_airport.h:110
RandomizedSpriteGroup::groups
std::vector< const SpriteGroup * > groups
Take the group with appropriate index:
Definition: newgrf_spritegroup.h:201
StationSpec::cargo_triggers
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
Definition: newgrf_station.h:155
ObjectSpec::clear_cost_multiplier
uint8_t clear_cost_multiplier
Clear cost multiplier per tile.
Definition: newgrf_object.h:70
SpriteGroup
Definition: newgrf_spritegroup.h:57
GRFLabel
Definition: newgrf.h:98
SkipAct12
static void SkipAct12(ByteReader *buf)
Action 0x12 (SKIP)
Definition: newgrf.cpp:8019
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:115
AddStringForMapping
static void AddStringForMapping(StringID source, StringID *target)
Record a static StringID for getting translated later.
Definition: newgrf.cpp:473
CargoSpec::multiplier
uint16_t multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:74
ResetGenericCallbacks
void ResetGenericCallbacks()
Reset all generic feature callback sprite groups.
Definition: newgrf_generic.cpp:94
Action5Type
Information about a single action 5 type.
Definition: newgrf.cpp:6399
_currency_specs
CurrencySpec _currency_specs[CURRENCY_END]
Array of currencies used by the system.
Definition: currency.cpp:76
EngineInfo::base_intro
TimerGameCalendar::Date base_intro
Basic date of engine introduction (without random parts).
Definition: engine_type.h:145
NamePart::id
byte id
If probability bit 7 is set.
Definition: newgrf_townname.h:20
LanguageMap::Mapping::newgrf_id
byte newgrf_id
NewGRF's internal ID for a case/gender.
Definition: newgrf_text.h:56
StationSpec::wires
byte wires
Bitmask of base tiles (0 - 7) which should contain elrail wires.
Definition: newgrf_station.h:162
TAE_PASSENGERS
@ TAE_PASSENGERS
Cargo behaves passenger-like.
Definition: cargotype.h:24
AddGRFTextToList
static void AddGRFTextToList(GRFTextList &list, byte langid, const std::string &text_to_add)
Add a new text to a GRFText list.
Definition: newgrf_text.cpp:485
EngineInfo::lifelength
TimerGameCalendar::Year lifelength
Lifetime of a single vehicle.
Definition: engine_type.h:146
RoadStopSpec::cargo_triggers
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
Definition: newgrf_roadstop.h:139
SetEngineGRF
void SetEngineGRF(EngineID engine, const GRFFile *file)
Tie a GRFFile entry to an engine, to allow us to retrieve GRF parameters etc during a game.
Definition: newgrf_engine.cpp:71
OrderSettings::gradual_loading
bool gradual_loading
load vehicles gradually
Definition: settings_type.h:507
Action5Type::min_sprites
uint16_t min_sprites
If the Action5 contains less sprites, the whole block will be ignored.
Definition: newgrf.cpp:6402
GCF_STATIC
@ GCF_STATIC
GRF file is used statically (can be used in any MP game)
Definition: newgrf_config.h:25
NewGRFSpriteLayout::Allocate
void Allocate(uint num_sprites)
Allocate a spritelayout for num_sprites building sprites.
Definition: newgrf_commons.cpp:603
IndustryLifeType
IndustryLifeType
Available types of industry lifetimes.
Definition: industrytype.h:26
GRFFile
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:107
ObjectSpec::cls_id
ObjectClassID cls_id
The class to which this spec belongs.
Definition: newgrf_object.h:64
PROP_TRAIN_USER_DATA
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
Definition: newgrf_properties.h:29
ShipVehicleInfo::ocean_speed_frac
byte ocean_speed_frac
Fraction of maximum speed for ocean tiles.
Definition: engine_type.h:77
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:56
IgnoreIndustryTileProperty
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
Ignore an industry tile property.
Definition: newgrf.cpp:3191
StationSpec::blocked
byte blocked
Bitmask of base tiles (0 - 7) which are blocked to trains.
Definition: newgrf_station.h:163
debug.h
OverrideManagerBase::GetID
virtual uint16_t GetID(uint16_t grf_local_id, uint32_t grfid) const
Return the ID (if ever available) of a previously inserted entity.
Definition: newgrf_commons.cpp:90
_grm_engines
static uint32_t _grm_engines[256]
Contains the GRF ID of the owner of a vehicle if it has been reserved.
Definition: newgrf.cpp:357
TileLayoutSpriteGroup
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition: newgrf_spritegroup.h:259
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:98
BridgeSpec::max_length
uint16_t max_length
the maximum length (not counting start and end tile)
Definition: bridge.h:45
PROP_ROADVEH_WEIGHT
@ PROP_ROADVEH_WEIGHT
Weight in 1/4 t.
Definition: newgrf_properties.h:37
SPR_TRAMWAY_BASE
static const SpriteID SPR_TRAMWAY_BASE
Tramway sprites.
Definition: sprites.h:272
engine_func.h
AddGenericCallback
void AddGenericCallback(uint8_t feature, const GRFFile *file, const SpriteGroup *group)
Add a generic feature callback sprite group to the appropriate feature list.
Definition: newgrf_generic.cpp:108
AirportTileSpec::animation
AnimationInfo animation
Information about the animation.
Definition: newgrf_airporttiles.h:69
EC_MONORAIL
@ EC_MONORAIL
Mono rail engine.
Definition: engine_type.h:37
GRFError::data
std::string data
Additional data for message and custom_message.
Definition: newgrf_config.h:113
WaterFeature::group
const SpriteGroup * group
Sprite group to start resolving.
Definition: newgrf_canal.h:23
CargoSpec::classes
uint16_t classes
Classes of this cargo type.
Definition: cargotype.h:75
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition: timer_game_calendar.h:32
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition: rail_type.h:34
DrawTileSeqStruct
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition: sprite.h:25
TileLayoutRegisters::palette_var10
uint8_t palette_var10
Value for variable 10 when resolving the palette.
Definition: newgrf_commons.h:102
ObjectSpec::flags
ObjectFlags flags
Flags/settings related to the object.
Definition: newgrf_object.h:73
RoadTypeChangeInfo
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
Define properties for roadtypes.
Definition: newgrf.cpp:4467
HouseOverrideManager::SetEntitySpec
void SetEntitySpec(const HouseSpec *hs)
Install the specs into the HouseSpecs array It will find itself the proper slot on which it will go.
Definition: newgrf_commons.cpp:159
ObjectSpec::views
uint8_t views
The number of views.
Definition: newgrf_object.h:76
StringIDMapping::grfid
uint32_t grfid
Source NewGRF.
Definition: newgrf.cpp:461
GRFFile::grf_features
uint32_t grf_features
Bitset of GrfSpecFeature the grf uses.
Definition: newgrf.h:148
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
SNOW_LINE_MONTHS
static const uint SNOW_LINE_MONTHS
Number of months in the snow line table.
Definition: landscape.h:16
CargoSpec::town_acceptance_effect
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:80
ReadSpriteLayoutRegisters
static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
Preprocess the TileLayoutFlags and read register modifiers from the GRF.
Definition: newgrf.cpp:795
GRFP_BLT_MASK
@ GRFP_BLT_MASK
Bitmask to only get the blitter information.
Definition: newgrf_config.h:78
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition: bitmath_func.hpp:194
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103