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