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