newgrf.cpp

Go to the documentation of this file.
00001 /* $Id: newgrf.cpp 15428 2009-02-09 02:57:15Z rubidium $ */
00002 
00005 #include "stdafx.h"
00006 
00007 #include <stdarg.h>
00008 
00009 #include "openttd.h"
00010 #include "debug.h"
00011 #include "fileio_func.h"
00012 #include "engine_func.h"
00013 #include "engine_base.h"
00014 #include "spritecache.h"
00015 #include "variables.h"
00016 #include "bridge.h"
00017 #include "town.h"
00018 #include "newgrf_engine.h"
00019 #include "newgrf_text.h"
00020 #include "fontcache.h"
00021 #include "currency.h"
00022 #include "landscape.h"
00023 #include "newgrf_house.h"
00024 #include "newgrf_sound.h"
00025 #include "newgrf_station.h"
00026 #include "industry.h"
00027 #include "newgrf_canal.h"
00028 #include "newgrf_commons.h"
00029 #include "newgrf_townname.h"
00030 #include "newgrf_industries.h"
00031 #include "rev.h"
00032 #include "fios.h"
00033 #include "rail.h"
00034 #include "strings_func.h"
00035 #include "gfx_func.h"
00036 #include "date_func.h"
00037 #include "vehicle_func.h"
00038 #include "sound_func.h"
00039 #include "string_func.h"
00040 #include "network/network.h"
00041 #include "map_func.h"
00042 #include <map>
00043 
00044 #include "table/strings.h"
00045 #include "table/build_industry.h"
00046 
00047 /* TTDPatch extended GRF format codec
00048  * (c) Petr Baudis 2004 (GPL'd)
00049  * Changes by Florian octo Forster are (c) by the OpenTTD development team.
00050  *
00051  * Contains portions of documentation by TTDPatch team.
00052  * Thanks especially to Josef Drexler for the documentation as well as a lot
00053  * of help at #tycoon. Also thanks to Michael Blunck for is GRF files which
00054  * served as subject to the initial testing of this codec. */
00055 
00056 
00057 static int _skip_sprites; // XXX
00058 static uint _file_index; // XXX
00059 
00060 static GRFFile *_cur_grffile;
00061 GRFFile *_first_grffile;
00062 static SpriteID _cur_spriteid;
00063 static GrfLoadingStage _cur_stage;
00064 static uint32 _nfo_line;
00065 
00066 static GRFConfig *_cur_grfconfig;
00067 
00068 /* Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E */
00069 static byte _misc_grf_features = 0;
00070 
00071 /* 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */
00072 static uint32 _ttdpatch_flags[8];
00073 
00074 /* Indicates which are the newgrf features currently loaded ingame */
00075 GRFLoadedFeatures _loaded_newgrf_features;
00076 
00077 enum GrfDataType {
00078   GDT_SOUND,
00079 };
00080 
00081 static byte _grf_data_blocks;
00082 static GrfDataType _grf_data_type;
00083 
00084 
00085 typedef void (*SpecialSpriteHandler)(byte *buf, size_t len);
00086 
00087 enum {
00088   MAX_STATIONS = 256,
00089 };
00090 
00091 /* Temporary data used when loading only */
00092 struct GRFTempEngineData {
00093   uint16 cargo_allowed;
00094   uint16 cargo_disallowed;
00095   uint8 rv_max_speed;      
00096 };
00097 
00098 static GRFTempEngineData *_gted;
00099 
00100 /* Contains the GRF ID of the owner of a vehicle if it has been reserved.
00101  * GRM for vehicles is only used if dynamic engine allocation is disabled,
00102  * so 256 is the number of original engines. */
00103 static uint32 _grm_engines[256];
00104 
00105 /* Contains the GRF ID of the owner of a cargo if it has been reserved */
00106 static uint32 _grm_cargos[NUM_CARGO * 2];
00107 
00108 struct GRFLocation {
00109   uint32 grfid;
00110   uint32 nfoline;
00111 
00112   GRFLocation(uint32 grfid, uint32 nfoline) : grfid(grfid), nfoline(nfoline) { }
00113 
00114   bool operator<(const GRFLocation &other) const
00115   {
00116     return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
00117   }
00118 
00119   bool operator==(const GRFLocation &other) const
00120   {
00121     return this->grfid == other.grfid && this->nfoline == other.nfoline;
00122   }
00123 };
00124 
00125 static std::map<GRFLocation, SpriteID> _grm_sprites;
00126 typedef std::map<GRFLocation, byte*> GRFLineToSpriteOverride;
00127 GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
00128 
00137 void CDECL grfmsg(int severity, const char *str, ...)
00138 {
00139   char buf[1024];
00140   va_list va;
00141 
00142   va_start(va, str);
00143   vsnprintf(buf, sizeof(buf), str, va);
00144   va_end(va);
00145 
00146   DEBUG(grf, severity, "[%s:%d] %s", _cur_grfconfig->filename, _nfo_line, buf);
00147 }
00148 
00149 static inline bool check_length(size_t real, size_t wanted, const char *str)
00150 {
00151   if (real >= wanted) return true;
00152   grfmsg(0, "%s: Invalid pseudo sprite length %d (expected %d)!", str, real, wanted);
00153   return false;
00154 }
00155 
00156 static inline byte grf_load_byte(byte **buf)
00157 {
00158   return *(*buf)++;
00159 }
00160 
00161 static uint16 grf_load_word(byte **buf)
00162 {
00163   uint16 val = grf_load_byte(buf);
00164   return val | (grf_load_byte(buf) << 8);
00165 }
00166 
00167 static uint16 grf_load_extended(byte** buf)
00168 {
00169   uint16 val;
00170   val = grf_load_byte(buf);
00171   if (val == 0xFF) val = grf_load_word(buf);
00172   return val;
00173 }
00174 
00175 static uint32 grf_load_dword(byte **buf)
00176 {
00177   uint32 val = grf_load_word(buf);
00178   return val | (grf_load_word(buf) << 16);
00179 }
00180 
00181 static uint32 grf_load_var(byte size, byte **buf)
00182 {
00183   switch (size) {
00184     case 1: return grf_load_byte(buf);
00185     case 2: return grf_load_word(buf);
00186     case 4: return grf_load_dword(buf);
00187     default:
00188       NOT_REACHED();
00189       return 0;
00190   }
00191 }
00192 
00193 static const char *grf_load_string(byte **buf, size_t max_len)
00194 {
00195   const char *string   = *(const char **)buf;
00196   size_t string_length = ttd_strnlen(string, max_len);
00197 
00198   if (string_length == max_len) {
00199     /* String was not NUL terminated, so make sure it is now. */
00200     (*buf)[string_length - 1] = '\0';
00201     grfmsg(7, "String was not terminated with a zero byte.");
00202   } else {
00203     /* Increase the string length to include the NUL byte. */
00204     string_length++;
00205   }
00206   *buf += string_length;
00207 
00208   return string;
00209 }
00210 
00211 static GRFFile *GetFileByGRFID(uint32 grfid)
00212 {
00213   GRFFile *file;
00214 
00215   for (file = _first_grffile; file != NULL; file = file->next) {
00216     if (file->grfid == grfid) break;
00217   }
00218   return file;
00219 }
00220 
00221 static GRFFile *GetFileByFilename(const char *filename)
00222 {
00223   GRFFile *file;
00224 
00225   for (file = _first_grffile; file != NULL; file = file->next) {
00226     if (strcmp(file->filename, filename) == 0) break;
00227   }
00228   return file;
00229 }
00230 
00232 static void ClearTemporaryNewGRFData(GRFFile *gf)
00233 {
00234   /* Clear the GOTO labels used for GRF processing */
00235   for (GRFLabel *l = gf->label; l != NULL;) {
00236     GRFLabel *l2 = l->next;
00237     free(l);
00238     l = l2;
00239   }
00240   gf->label = NULL;
00241 
00242   /* Clear the list of spritegroups */
00243   free(gf->spritegroups);
00244   gf->spritegroups = NULL;
00245   gf->spritegroups_count = 0;
00246 }
00247 
00248 
00249 typedef std::map<StringID *, uint32> StringIDToGRFIDMapping;
00250 StringIDToGRFIDMapping _string_to_grf_mapping;
00251 
00258 StringID MapGRFStringID(uint32 grfid, StringID str)
00259 {
00260   /* StringID table for TextIDs 0x4E->0x6D */
00261   static StringID units_volume[] = {
00262     STR_NOTHING,    STR_PASSENGERS, STR_TONS,       STR_BAGS,
00263     STR_LITERS,     STR_ITEMS,      STR_CRATES,     STR_TONS,
00264     STR_TONS,       STR_TONS,       STR_TONS,       STR_BAGS,
00265     STR_TONS,       STR_TONS,       STR_TONS,       STR_BAGS,
00266     STR_TONS,       STR_TONS,       STR_BAGS,       STR_LITERS,
00267     STR_TONS,       STR_LITERS,     STR_TONS,       STR_NOTHING,
00268     STR_BAGS,       STR_LITERS,     STR_TONS,       STR_NOTHING,
00269     STR_TONS,       STR_NOTHING,    STR_LITERS,     STR_NOTHING
00270   };
00271 
00272   /* 0xD0 and 0xDC stand for all the TextIDs in the range
00273    * of 0xD000 (misc graphics texts) and 0xDC00 (misc persistent texts).
00274    * These strings are unique to each grf file, and thus require to be used with the
00275    * grfid in which they are declared */
00276   switch (GB(str, 8, 8)) {
00277     case 0xD0: case 0xD1: case 0xD2: case 0xD3:
00278     case 0xDC:
00279       return GetGRFStringID(grfid, str);
00280 
00281     case 0xD4: case 0xD5: case 0xD6: case 0xD7:
00282       /* Strings embedded via 0x81 have 0x400 added to them (no real
00283        * explanation why...) */
00284       return GetGRFStringID(grfid, str - 0x400);
00285 
00286     default: break;
00287   }
00288 
00289 #define TEXID_TO_STRINGID(begin, end, stringid) if (str >= begin && str <= end) return str + (stringid - begin)
00290   /* We have some changes in our cargo strings, resulting in some missing. */
00291   TEXID_TO_STRINGID(0x000E, 0x002D, STR_000E);
00292   TEXID_TO_STRINGID(0x002E, 0x004D, STR_002E);
00293   if (str >= 0x004E && str <= 0x006D) str = units_volume[str - 0x004E];
00294   TEXID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING);
00295   TEXID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING);
00296 
00297   /* Map building names according to our lang file changes. There are several
00298    * ranges of house ids, all of which need to be remapped to allow newgrfs
00299    * to use original house names. */
00300   TEXID_TO_STRINGID(0x200F, 0x201F, STR_200F_TALL_OFFICE_BLOCK);
00301   TEXID_TO_STRINGID(0x2036, 0x2041, STR_2036_COTTAGES);
00302   TEXID_TO_STRINGID(0x2059, 0x205C, STR_2059_IGLOO);
00303 
00304   /* Same thing for industries, since the introduction of 4 new strings above STR_482A_PRODUCTION_LAST_MONTH */
00305   TEXID_TO_STRINGID(0x482A, 0x483B, STR_482A_PRODUCTION_LAST_MONTH);
00306 #undef TEXTID_TO_STRINGID
00307 
00308   if (str == STR_NULL) return STR_EMPTY;
00309 
00310   return str;
00311 }
00312 
00313 static inline uint8 MapDOSColour(uint8 colour)
00314 {
00315   extern const byte _palmap_d2w[];
00316   return (_use_palette == PAL_DOS ? colour : _palmap_d2w[colour]);
00317 }
00318 
00319 static std::map<uint32, uint32> _grf_id_overrides;
00320 
00321 static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
00322 {
00323   _grf_id_overrides[source_grfid] = target_grfid;
00324   grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
00325 }
00326 
00327 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id)
00328 {
00329   /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
00330    * them use the same engine slots. */
00331   const GRFFile *grf_match = NULL;
00332   if (_settings_game.vehicle.dynamic_engines) {
00333     uint32 override = _grf_id_overrides[file->grfid];
00334     if (override != 0) {
00335       grf_match = GetFileByGRFID(override);
00336       if (grf_match == NULL) {
00337         grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
00338       } else {
00339         grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
00340       }
00341     }
00342   }
00343 
00344   /* Check if this vehicle is already defined... */
00345   Engine *e = NULL;
00346   FOR_ALL_ENGINES(e) {
00347     if (_settings_game.vehicle.dynamic_engines && e->grffile != NULL && e->grffile != file && e->grffile != grf_match) continue;
00348     if (e->type != type) continue;
00349     if (e->internal_id != internal_id) continue;
00350 
00351     if (e->grffile == NULL) {
00352       e->grffile = file;
00353       grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
00354     }
00355     return e;
00356   }
00357 
00358   uint engine_pool_size = GetEnginePoolSize();
00359 
00360   /* ... it's not, so create a new one based off an existing engine */
00361   e = new Engine(type, internal_id);
00362   e->grffile = file;
00363 
00364   if (engine_pool_size != GetEnginePoolSize()) {
00365     /* Resize temporary engine data ... */
00366     _gted = ReallocT(_gted, GetEnginePoolSize());
00367 
00368     /* and blank the new block. */
00369     size_t len = (GetEnginePoolSize() - engine_pool_size) * sizeof(*_gted);
00370     memset(_gted + engine_pool_size, 0, len);
00371   }
00372 
00373   grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
00374 
00375   return e;
00376 }
00377 
00378 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
00379 {
00380   extern uint32 GetNewGRFOverride(uint32 grfid);
00381 
00382   const GRFFile *grf_match = NULL;
00383   if (_settings_game.vehicle.dynamic_engines) {
00384     uint32 override = _grf_id_overrides[file->grfid];
00385     if (override != 0) grf_match = GetFileByGRFID(override);
00386   }
00387 
00388   const Engine *e = NULL;
00389   FOR_ALL_ENGINES(e) {
00390     if (_settings_game.vehicle.dynamic_engines && e->grffile != file && (grf_match == NULL || e->grffile != grf_match)) continue;
00391     if (e->type != type) continue;
00392     if (e->internal_id != internal_id) continue;
00393 
00394     return e->index;
00395   }
00396 
00397   return INVALID_ENGINE;
00398 }
00399 
00403 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
00404 {
00405   if (HasBit(grf_sprite->pal, 14)) {
00406     ClrBit(grf_sprite->pal, 14);
00407     SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
00408   }
00409 
00410   if (HasBit(grf_sprite->sprite, 14)) {
00411     ClrBit(grf_sprite->sprite, 14);
00412     SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
00413   }
00414 
00415   if (HasBit(grf_sprite->sprite, 15)) {
00416     ClrBit(grf_sprite->sprite, 15);
00417     SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
00418   }
00419 }
00420 
00421 enum ChangeInfoResult {
00422   CIR_SUCCESS,    
00423   CIR_UNHANDLED,  
00424   CIR_UNKNOWN,    
00425   CIR_INVALID_ID, 
00426 };
00427 
00428 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, byte **buf, int len);
00429 
00430 static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, byte **buf)
00431 {
00432   switch (prop) {
00433     case 0x00: // Introduction date
00434       ei->base_intro = grf_load_word(buf) + DAYS_TILL_ORIGINAL_BASE_YEAR;
00435       break;
00436 
00437     case 0x02: // Decay speed
00438       ei->decay_speed = grf_load_byte(buf);
00439       break;
00440 
00441     case 0x03: // Vehicle life
00442       ei->lifelength = grf_load_byte(buf);
00443       break;
00444 
00445     case 0x04: // Model life
00446       ei->base_life = grf_load_byte(buf);
00447       break;
00448 
00449     case 0x06: // Climates available
00450       ei->climates = grf_load_byte(buf);
00451       /* Sometimes a GRF wants hidden vehicles. Setting climates to
00452        * zero may cause the ID to be reallocated. */
00453       if (ei->climates == 0) ei->climates = 0x80;
00454       break;
00455 
00456     case 0x07: // Loading speed
00457       /* Amount of cargo loaded during a vehicle's "loading tick" */
00458       ei->load_amount = grf_load_byte(buf);
00459       break;
00460 
00461     default:
00462       return CIR_UNKNOWN;
00463   }
00464 
00465   return CIR_SUCCESS;
00466 }
00467 
00468 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
00469 {
00470   byte *buf = *bufp;
00471   ChangeInfoResult ret = CIR_SUCCESS;
00472 
00473   for (int i = 0; i < numinfo; i++) {
00474     Engine *e = GetNewEngine(_cur_grffile, VEH_TRAIN, engine + i);
00475     EngineInfo *ei = &e->info;
00476     RailVehicleInfo *rvi = &e->u.rail;
00477 
00478     switch (prop) {
00479       case 0x05: { // Track type
00480         uint8 tracktype = grf_load_byte(&buf);
00481 
00482         if (tracktype < _cur_grffile->railtype_max) {
00483           RailType railtype = GetRailTypeByLabel(_cur_grffile->railtype_list[tracktype]);
00484           if (railtype == INVALID_RAILTYPE) {
00485             /* Rail type is not available, so disable this engine */
00486             ei[i].climates = 0x80;
00487           } else {
00488             rvi[i].railtype = railtype;
00489           }
00490           break;
00491         }
00492 
00493         switch (tracktype) {
00494           case 0: rvi->railtype = rvi->engclass >= 2 ? RAILTYPE_ELECTRIC : RAILTYPE_RAIL; break;
00495           case 1: rvi->railtype = RAILTYPE_MONO; break;
00496           case 2: rvi->railtype = RAILTYPE_MAGLEV; break;
00497           default:
00498             grfmsg(1, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring", tracktype);
00499             break;
00500         }
00501       } break;
00502 
00503       case 0x08: // AI passenger service
00504         /* Tells the AI that this engine is designed for
00505          * passenger services and shouldn't be used for freight. */
00506         rvi->ai_passenger_only = grf_load_byte(&buf);
00507         break;
00508 
00509       case 0x09: { // Speed (1 unit is 1 kmh)
00510         uint16 speed = grf_load_word(&buf);
00511         if (speed == 0xFFFF) speed = 0;
00512 
00513         rvi->max_speed = speed;
00514       } break;
00515 
00516       case 0x0B: // Power
00517         rvi->power = grf_load_word(&buf);
00518 
00519         /* Set engine / wagon state based on power */
00520         if (rvi->power != 0) {
00521           if (rvi->railveh_type == RAILVEH_WAGON) {
00522             rvi->railveh_type = RAILVEH_SINGLEHEAD;
00523           }
00524         } else {
00525           rvi->railveh_type = RAILVEH_WAGON;
00526         }
00527         break;
00528 
00529       case 0x0D: // Running cost factor
00530         rvi->running_cost = grf_load_byte(&buf);
00531         break;
00532 
00533       case 0x0E: { // Running cost base
00534         uint32 base = grf_load_dword(&buf);
00535 
00536         /* These magic numbers are used in GRFs to specify the base cost:
00537          * http://wiki.ttdpatch.net/tiki-index.php?page=BaseCosts
00538          */
00539         if (base == 0) {
00540           rvi->running_cost_class = 0xFF;
00541         } else if (base < 0x4B34 || base > 0x4C54 || (base - 0x4B34) % 6 != 0) {
00542           grfmsg(1, "RailVehicleChangeInfo: Unsupported running cost base 0x%04X, ignoring", base);
00543         } else {
00544           /* Convert the magic number to an index into the price data */
00545           rvi->running_cost_class = (base - 0x4B34) / 6;
00546         }
00547       } break;
00548 
00549       case 0x12: { // Sprite ID
00550         uint8 spriteid = grf_load_byte(&buf);
00551 
00552         /* TTD sprite IDs point to a location in a 16bit array, but we use it
00553          * as an array index, so we need it to be half the original value. */
00554         if (spriteid < 0xFD) spriteid >>= 1;
00555 
00556         rvi->image_index = spriteid;
00557       } break;
00558 
00559       case 0x13: { // Dual-headed
00560         uint8 dual = grf_load_byte(&buf);
00561 
00562         if (dual != 0) {
00563           rvi->railveh_type = RAILVEH_MULTIHEAD;
00564         } else {
00565           rvi->railveh_type = rvi->power == 0 ?
00566             RAILVEH_WAGON : RAILVEH_SINGLEHEAD;
00567         }
00568       } break;
00569 
00570       case 0x14: // Cargo capacity
00571         rvi->capacity = grf_load_byte(&buf);
00572         break;
00573 
00574       case 0x15: { // Cargo type
00575         uint8 ctype = grf_load_byte(&buf);
00576 
00577         if (ctype < NUM_CARGO && HasBit(_cargo_mask, ctype)) {
00578           rvi->cargo_type = ctype;
00579         } else if (ctype == 0xFF) {
00580           /* 0xFF is specified as 'use first refittable' */
00581           rvi->cargo_type = CT_INVALID;
00582         } else {
00583           rvi->cargo_type = CT_INVALID;
00584           grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
00585         }
00586       } break;
00587 
00588       case 0x16: // Weight
00589         SB(rvi->weight, 0, 8, grf_load_byte(&buf));
00590         break;
00591 
00592       case 0x17: // Cost factor
00593         rvi->cost_factor = grf_load_byte(&buf);
00594         break;
00595 
00596       case 0x18: // AI rank
00597         rvi->ai_rank = grf_load_byte(&buf);
00598         break;
00599 
00600       case 0x19: { // Engine traction type
00601         /* What do the individual numbers mean?
00602          * 0x00 .. 0x07: Steam
00603          * 0x08 .. 0x27: Diesel
00604          * 0x28 .. 0x31: Electric
00605          * 0x32 .. 0x37: Monorail
00606          * 0x38 .. 0x41: Maglev
00607          */
00608         uint8 traction = grf_load_byte(&buf);
00609         EngineClass engclass;
00610 
00611         if (traction <= 0x07) {
00612           engclass = EC_STEAM;
00613         } else if (traction <= 0x27) {
00614           engclass = EC_DIESEL;
00615         } else if (traction <= 0x31) {
00616           engclass = EC_ELECTRIC;
00617         } else if (traction <= 0x37) {
00618           engclass = EC_MONORAIL;
00619         } else if (traction <= 0x41) {
00620           engclass = EC_MAGLEV;
00621         } else {
00622           break;
00623         }
00624 
00625         if (_cur_grffile->railtype_max == 0) {
00626           /* Use traction type to select between normal and electrified
00627            * rail only when no translation list is in place. */
00628           if (rvi->railtype == RAILTYPE_RAIL     && engclass >= EC_ELECTRIC) rvi->railtype = RAILTYPE_ELECTRIC;
00629           if (rvi->railtype == RAILTYPE_ELECTRIC && engclass  < EC_ELECTRIC) rvi->railtype = RAILTYPE_RAIL;
00630         }
00631 
00632         rvi->engclass = engclass;
00633       } break;
00634 
00635       case 0x1A: // Alter purchase list sort order
00636         AlterVehicleListOrder(e->index, grf_load_extended(&buf));
00637         break;
00638 
00639       case 0x1B: // Powered wagons power bonus
00640         rvi->pow_wag_power = grf_load_word(&buf);
00641         break;
00642 
00643       case 0x1C: // Refit cost
00644         ei->refit_cost = grf_load_byte(&buf);
00645         break;
00646 
00647       case 0x1D: // Refit cargo
00648         ei->refit_mask = grf_load_dword(&buf);
00649         break;
00650 
00651       case 0x1E: // Callback
00652         ei->callbackmask = grf_load_byte(&buf);
00653         break;
00654 
00655       case 0x1F: // Tractive effort coefficient
00656         rvi->tractive_effort = grf_load_byte(&buf);
00657         break;
00658 
00659       case 0x20: // Air drag
00661         grf_load_byte(&buf);
00662         ret = CIR_UNHANDLED;
00663         break;
00664 
00665       case 0x21: // Shorter vehicle
00666         rvi->shorten_factor = grf_load_byte(&buf);
00667         break;
00668 
00669       case 0x22: // Visual effect
00671         rvi->visual_effect = grf_load_byte(&buf);
00672         break;
00673 
00674       case 0x23: // Powered wagons weight bonus
00675         rvi->pow_wag_weight = grf_load_byte(&buf);
00676         break;
00677 
00678       case 0x24: { // High byte of vehicle weight
00679         byte weight = grf_load_byte(&buf);
00680 
00681         if (weight > 4) {
00682           grfmsg(2, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring", weight << 8);
00683         } else {
00684           SB(rvi->weight, 8, 8, weight);
00685         }
00686       } break;
00687 
00688       case 0x25: // User-defined bit mask to set when checking veh. var. 42
00689         rvi->user_def_data = grf_load_byte(&buf);
00690         break;
00691 
00692       case 0x26: // Retire vehicle early
00693         ei->retire_early = grf_load_byte(&buf);
00694         break;
00695 
00696       case 0x27: // Miscellaneous flags
00697         ei->misc_flags = grf_load_byte(&buf);
00698         _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
00699         break;
00700 
00701       case 0x28: // Cargo classes allowed
00702         _gted[e->index].cargo_allowed = grf_load_word(&buf);
00703         break;
00704 
00705       case 0x29: // Cargo classes disallowed
00706         _gted[e->index].cargo_disallowed = grf_load_word(&buf);
00707         break;
00708 
00709       case 0x2A: // Long format introduction date (days since year 0)
00710         ei->base_intro = grf_load_dword(&buf);
00711         break;
00712 
00713       default:
00714         ret = CommonVehicleChangeInfo(ei, prop, &buf);
00715         break;
00716     }
00717   }
00718 
00719   *bufp = buf;
00720   return ret;
00721 }
00722 
00723 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
00724 {
00725   byte *buf = *bufp;
00726   ChangeInfoResult ret = CIR_SUCCESS;
00727 
00728   for (int i = 0; i < numinfo; i++) {
00729     Engine *e = GetNewEngine(_cur_grffile, VEH_ROAD, engine + i);
00730     EngineInfo *ei = &e->info;
00731     RoadVehicleInfo *rvi = &e->u.road;
00732 
00733     switch (prop) {
00734       case 0x08: // Speed (1 unit is 0.5 kmh)
00735         rvi->max_speed = grf_load_byte(&buf);
00736         break;
00737 
00738       case 0x09: // Running cost factor
00739         rvi->running_cost = grf_load_byte(&buf);
00740         break;
00741 
00742       case 0x0A: { // Running cost base
00743         uint32 base = grf_load_dword(&buf);
00744 
00745         /* These magic numbers are used in GRFs to specify the base cost:
00746          * http://wiki.ttdpatch.net/tiki-index.php?page=BaseCosts
00747          */
00748         if (base == 0) {
00749           rvi->running_cost_class = 0xFF;
00750         } else if (base < 0x4B34 || base > 0x4C54 || (base - 0x4B34) % 6 != 0) {
00751           grfmsg(1, "RailVehicleChangeInfo: Unsupported running cost base 0x%04X, ignoring", base);
00752         } else {
00753           /* Convert the magic number to an index into the price data */
00754           rvi->running_cost_class = (base - 0x4B34) / 6;
00755         }
00756 
00757         break;
00758       }
00759 
00760       case 0x0E: { // Sprite ID
00761         uint8 spriteid = grf_load_byte(&buf);
00762 
00763         /* cars have different custom id in the GRF file */
00764         if (spriteid == 0xFF) spriteid = 0xFD;
00765 
00766         if (spriteid < 0xFD) spriteid >>= 1;
00767 
00768         rvi->image_index = spriteid;
00769       } break;
00770 
00771       case 0x0F: // Cargo capacity
00772         rvi->capacity = grf_load_byte(&buf);
00773         break;
00774 
00775       case 0x10: { // Cargo type
00776         uint8 cargo = grf_load_byte(&buf);
00777 
00778         if (cargo < NUM_CARGO && HasBit(_cargo_mask, cargo)) {
00779           rvi->cargo_type = cargo;
00780         } else if (cargo == 0xFF) {
00781           rvi->cargo_type = CT_INVALID;
00782         } else {
00783           rvi->cargo_type = CT_INVALID;
00784           grfmsg(2, "RoadVehicleChangeInfo: Invalid cargo type %d, using first refittable", cargo);
00785         }
00786       } break;
00787 
00788       case 0x11: // Cost factor
00789         rvi->cost_factor = grf_load_byte(&buf);
00790         break;
00791 
00792       case 0x12: // SFX
00793         rvi->sfx = (SoundFx)grf_load_byte(&buf);
00794         break;
00795 
00796       case 0x13: // Power in 10hp
00797         rvi->power = grf_load_byte(&buf);
00798         break;
00799 
00800       case 0x14: // Weight in 1/4 tons
00801         rvi->weight = grf_load_byte(&buf);
00802         break;
00803 
00804       case 0x15: // Speed in mph/0.8
00805         _gted[e->index].rv_max_speed = grf_load_byte(&buf);
00806         break;
00807 
00808       case 0x16: // Cargos available for refitting
00809         ei->refit_mask = grf_load_dword(&buf);
00810         break;
00811 
00812       case 0x17: // Callback mask
00813         ei->callbackmask = grf_load_byte(&buf);
00814         break;
00815 
00816       case 0x18: // Tractive effort
00817         rvi->tractive_effort = grf_load_byte(&buf);
00818         break;
00819 
00820       case 0x19: // Air drag
00821         rvi->air_drag = grf_load_byte(&buf);
00822         break;
00823 
00824       case 0x1A: // Refit cost
00825         ei->refit_cost = grf_load_byte(&buf);
00826         break;
00827 
00828       case 0x1B: // Retire vehicle early
00829         ei->retire_early = grf_load_byte(&buf);
00830         break;
00831 
00832       case 0x1C: // Miscellaneous flags
00833         ei->misc_flags = grf_load_byte(&buf);
00834         _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
00835         break;
00836 
00837       case 0x1D: // Cargo classes allowed
00838         _gted[e->index].cargo_allowed = grf_load_word(&buf);
00839         break;
00840 
00841       case 0x1E: // Cargo classes disallowed
00842         _gted[e->index].cargo_disallowed = grf_load_word(&buf);
00843         break;
00844 
00845       case 0x1F: // Long format introduction date (days since year 0)
00846         ei->base_intro = grf_load_dword(&buf);
00847         break;
00848 
00849       case 0x20: // Alter purchase list sort order
00850         AlterVehicleListOrder(e->index, grf_load_extended(&buf));
00851         break;
00852 
00853       default:
00854         ret = CommonVehicleChangeInfo(ei, prop, &buf);
00855         break;
00856     }
00857   }
00858 
00859   *bufp = buf;
00860   return ret;
00861 }
00862 
00863 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
00864 {
00865   byte *buf = *bufp;
00866   ChangeInfoResult ret = CIR_SUCCESS;
00867 
00868   for (int i = 0; i < numinfo; i++) {
00869     Engine *e = GetNewEngine(_cur_grffile, VEH_SHIP, engine + i);
00870     EngineInfo *ei = &e->info;
00871     ShipVehicleInfo *svi = &e->u.ship;
00872 
00873     switch (prop) {
00874       case 0x08: { // Sprite ID
00875         uint8 spriteid = grf_load_byte(&buf);
00876 
00877         /* ships have different custom id in the GRF file */
00878         if (spriteid == 0xFF) spriteid = 0xFD;
00879 
00880         if (spriteid < 0xFD) spriteid >>= 1;
00881 
00882         svi->image_index = spriteid;
00883       } break;
00884 
00885       case 0x09: // Refittable
00886         svi->refittable = (grf_load_byte(&buf) != 0);
00887         break;
00888 
00889       case 0x0A: // Cost factor
00890         svi->cost_factor = grf_load_byte(&buf);
00891         break;
00892 
00893       case 0x0B: // Speed (1 unit is 0.5 kmh)
00894         svi->max_speed = grf_load_byte(&buf);
00895         break;
00896 
00897       case 0x0C: { // Cargo type
00898         uint8 cargo = grf_load_byte(&buf);
00899 
00900         if (cargo < NUM_CARGO && HasBit(_cargo_mask, cargo)) {
00901           svi->cargo_type = cargo;
00902         } else if (cargo == 0xFF) {
00903           svi->cargo_type = CT_INVALID;
00904         } else {
00905           svi->cargo_type = CT_INVALID;
00906           grfmsg(2, "ShipVehicleChangeInfo: Invalid cargo type %d, using first refittable", cargo);
00907         }
00908       } break;
00909 
00910       case 0x0D: // Cargo capacity
00911         svi->capacity = grf_load_word(&buf);
00912         break;
00913 
00914       case 0x0F: // Running cost factor
00915         svi->running_cost = grf_load_byte(&buf);
00916         break;
00917 
00918       case 0x10: // SFX
00919         svi->sfx = (SoundFx)grf_load_byte(&buf);
00920         break;
00921 
00922       case 0x11: // Cargos available for refitting
00923         ei->refit_mask = grf_load_dword(&buf);
00924         break;
00925 
00926       case 0x12: // Callback mask
00927         ei->callbackmask = grf_load_byte(&buf);
00928         break;
00929 
00930       case 0x13: // Refit cost
00931         ei->refit_cost = grf_load_byte(&buf);
00932         break;
00933 
00934       case 0x14: // Ocean speed fraction
00935       case 0x15: // Canal speed fraction
00937         grf_load_byte(&buf);
00938         ret = CIR_UNHANDLED;
00939         break;
00940 
00941       case 0x16: // Retire vehicle early
00942         ei->retire_early = grf_load_byte(&buf);
00943         break;
00944 
00945       case 0x17: // Miscellaneous flags
00946         ei->misc_flags = grf_load_byte(&buf);
00947         _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
00948         break;
00949 
00950       case 0x18: // Cargo classes allowed
00951         _gted[e->index].cargo_allowed = grf_load_word(&buf);
00952         break;
00953 
00954       case 0x19: // Cargo classes disallowed
00955         _gted[e->index].cargo_disallowed = grf_load_word(&buf);
00956         break;
00957 
00958       case 0x1A: // Long format introduction date (days since year 0)
00959         ei->base_intro = grf_load_dword(&buf);
00960         break;
00961 
00962       case 0x1B: // Alter purchase list sort order
00963         AlterVehicleListOrder(e->index, grf_load_extended(&buf));
00964         break;
00965 
00966       default:
00967         ret = CommonVehicleChangeInfo(ei, prop, &buf);
00968         break;
00969     }
00970   }
00971 
00972   *bufp = buf;
00973   return ret;
00974 }
00975 
00976 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, byte **bufp, int len)
00977 {
00978   byte *buf = *bufp;
00979   ChangeInfoResult ret = CIR_SUCCESS;
00980 
00981   for (int i = 0; i < numinfo; i++) {
00982     Engine *e = GetNewEngine(_cur_grffile, VEH_AIRCRAFT, engine + i);
00983     EngineInfo *ei = &e->info;
00984     AircraftVehicleInfo *avi = &e->u.air;
00985 
00986     switch (prop) {
00987       case 0x08: { // Sprite ID
00988         uint8 spriteid = grf_load_byte(&buf);
00989 
00990         /* aircraft have different custom id in the GRF file */
00991         if (spriteid == 0xFF) spriteid = 0xFD;
00992 
00993         if (spriteid < 0xFD) spriteid >>= 1;
00994 
00995         avi->image_index = spriteid;
00996       } break;
00997 
00998       case 0x09: // Helicopter
00999         if (grf_load_byte(&buf) == 0) {
01000           avi->subtype = AIR_HELI;
01001         } else {
01002           SB(avi->subtype, 0, 1, 1); // AIR_CTOL
01003         }
01004         break;
01005 
01006       case 0x0A: // Large
01007         SB(avi->subtype, 1, 1, (grf_load_byte(&buf) != 0 ? 1 : 0)); // AIR_FAST
01008         break;
01009 
01010       case 0x0B: // Cost factor
01011         avi->cost_factor = grf_load_byte(&buf);
01012         break;
01013 
01014       case 0x0C: // Speed (1 unit is 8 mph, we translate to 1 unit is 1 km/h)
01015         avi->max_speed = (grf_load_byte(&buf) * 129) / 10;
01016         break;
01017 
01018       case 0x0D: // Acceleration
01019         avi->acceleration = (grf_load_byte(&buf) * 129) / 10;
01020         break;
01021 
01022       case 0x0E: // Running cost factor
01023         avi->running_cost = grf_load_byte(&buf);
01024         break;
01025 
01026       case 0x0F: // Passenger capacity
01027         avi->passenger_capacity = grf_load_word(&buf);
01028         break;
01029 
01030       case 0x11: // Mail capacity
01031         avi->mail_capacity = grf_load_byte(&buf);
01032         break;
01033 
01034       case 0x12: // SFX
01035         avi->sfx = (SoundFx)grf_load_byte(&buf);
01036         break;
01037 
01038       case 0x13: // Cargos available for refitting
01039         ei->refit_mask = grf_load_dword(&buf);
01040         break;
01041 
01042       case 0x14: // Callback mask
01043         ei->callbackmask = grf_load_byte(&buf);
01044         break;
01045 
01046       case 0x15: // Refit cost
01047         ei->refit_cost = grf_load_byte(&buf);
01048         break;
01049 
01050       case 0x16: // Retire vehicle early
01051         ei->retire_early = grf_load_byte(&buf);
01052         break;
01053 
01054       case 0x17: // Miscellaneous flags
01055         ei->misc_flags = grf_load_byte(&buf);
01056         _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
01057         break;
01058 
01059       case 0x18: // Cargo classes allowed
01060         _gted[e->index].cargo_allowed = grf_load_word(&buf);
01061         break;
01062 
01063       case 0x19: // Cargo classes disallowed
01064         _gted[e->index].cargo_disallowed = grf_load_word(&buf);
01065         break;
01066 
01067       case 0x1A: // Long format introduction date (days since year 0)
01068         ei->base_intro = grf_load_dword(&buf);
01069         break;
01070 
01071       case 0x1B: // Alter purchase list sort order
01072         AlterVehicleListOrder(e->index, grf_load_extended(&buf));
01073         break;
01074 
01075       default:
01076         ret = CommonVehicleChangeInfo(ei, prop, &buf);
01077         break;
01078     }
01079   }
01080 
01081   *bufp = buf;
01082   return ret;
01083 }
01084 
01085 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, byte **bufp, int len)
01086 {
01087   byte *buf = *bufp;
01088   ChangeInfoResult ret = CIR_SUCCESS;
01089 
01090   if (stid + numinfo > MAX_STATIONS) {
01091     grfmsg(1, "StationChangeInfo: Station %u is invalid, max %u, ignoring", stid + numinfo, MAX_STATIONS);
01092     return CIR_INVALID_ID;
01093   }
01094 
01095   /* Allocate station specs if necessary */
01096   if (_cur_grffile->stations == NULL) _cur_grffile->stations = CallocT<StationSpec*>(MAX_STATIONS);
01097 
01098   for (int i = 0; i < numinfo; i++) {
01099     StationSpec *statspec = _cur_grffile->stations[stid + i];
01100 
01101     /* Check that the station we are modifying is defined. */
01102     if (statspec == NULL && prop != 0x08) {
01103       grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
01104       return CIR_INVALID_ID;
01105     }
01106 
01107     switch (prop) {
01108       case 0x08: { // Class ID
01109         StationSpec **spec = &_cur_grffile->stations[stid + i];
01110 
01111         /* Property 0x08 is special; it is where the station is allocated */
01112         if (*spec == NULL) *spec = CallocT<StationSpec>(1);
01113 
01114         /* Swap classid because we read it in BE meaning WAYP or DFLT */
01115         uint32 classid = grf_load_dword(&buf);
01116         (*spec)->sclass = AllocateStationClass(BSWAP32(classid));
01117       } break;
01118 
01119       case 0x09: // Define sprite layout
01120         statspec->tiles = grf_load_extended(&buf);
01121         statspec->renderdata = CallocT<DrawTileSprites>(statspec->tiles);
01122         statspec->copied_renderdata = false;
01123 
01124         for (uint t = 0; t < statspec->tiles; t++) {
01125           DrawTileSprites *dts = &statspec->renderdata[t];
01126           uint seq_count = 0;
01127 
01128           dts->seq = NULL;
01129           dts->ground.sprite = grf_load_word(&buf);
01130           dts->ground.pal = grf_load_word(&buf);
01131           if (dts->ground.sprite == 0) continue;
01132           if (HasBit(dts->ground.pal, 15)) {
01133             ClrBit(dts->ground.pal, 15);
01134             SetBit(dts->ground.sprite, SPRITE_MODIFIER_USE_OFFSET);
01135           }
01136 
01137           MapSpriteMappingRecolour(&dts->ground);
01138 
01139           while (buf < *bufp + len) {
01140             DrawTileSeqStruct *dtss;
01141 
01142             /* no relative bounding box support */
01143             dts->seq = ReallocT((DrawTileSeqStruct*)dts->seq, ++seq_count);
01144             dtss = (DrawTileSeqStruct*) &dts->seq[seq_count - 1];
01145 
01146             dtss->delta_x = grf_load_byte(&buf);
01147             if ((byte) dtss->delta_x == 0x80) break;
01148             dtss->delta_y = grf_load_byte(&buf);
01149             dtss->delta_z = grf_load_byte(&buf);
01150             dtss->size_x = grf_load_byte(&buf);
01151             dtss->size_y = grf_load_byte(&buf);
01152             dtss->size_z = grf_load_byte(&buf);
01153             dtss->image.sprite = grf_load_word(&buf);
01154             dtss->image.pal = grf_load_word(&buf);
01155 
01156             /* Remap flags as ours collide */
01157             if (HasBit(dtss->image.pal, 15)) {
01158               ClrBit(dtss->image.pal, 15);
01159               SetBit(dtss->image.sprite, SPRITE_MODIFIER_USE_OFFSET);
01160             }
01161 
01162             MapSpriteMappingRecolour(&dtss->image);
01163           }
01164         }
01165         break;
01166 
01167       case 0x0A: { // Copy sprite layout
01168         byte srcid = grf_load_byte(&buf);
01169         const StationSpec *srcstatspec = _cur_grffile->stations[srcid];
01170 
01171         statspec->tiles = srcstatspec->tiles;
01172         statspec->renderdata = srcstatspec->renderdata;
01173         statspec->copied_renderdata = true;
01174       } break;
01175 
01176       case 0x0B: // Callback mask
01177         statspec->callbackmask = grf_load_byte(&buf);
01178         break;
01179 
01180       case 0x0C: // Disallowed number of platforms
01181         statspec->disallowed_platforms = grf_load_byte(&buf);
01182         break;
01183 
01184       case 0x0D: // Disallowed platform lengths
01185         statspec->disallowed_lengths = grf_load_byte(&buf);
01186         break;
01187 
01188       case 0x0E: // Define custom layout
01189         statspec->copied_layouts = false;
01190 
01191         while (buf < *bufp + len) {
01192           byte length = grf_load_byte(&buf);
01193           byte number = grf_load_byte(&buf);
01194           StationLayout layout;
01195           uint l, p;
01196 
01197           if (length == 0 || number == 0) break;
01198 
01199           //debug("l %d > %d ?", length, stat->lengths);
01200           if (length > statspec->lengths) {
01201             statspec->platforms = ReallocT(statspec->platforms, length);
01202             memset(statspec->platforms + statspec->lengths, 0, length - statspec->lengths);
01203 
01204             statspec->layouts = ReallocT(statspec->layouts, length);
01205             memset(statspec->layouts + statspec->lengths, 0,
01206                    (length - statspec->lengths) * sizeof(*statspec->layouts));
01207 
01208             statspec->lengths = length;
01209           }
01210           l = length - 1; // index is zero-based
01211 
01212           //debug("p %d > %d ?", number, stat->platforms[l]);
01213           if (number > statspec->platforms[l]) {
01214             statspec->layouts[l] = ReallocT(statspec->layouts[l], number);
01215             /* We expect NULL being 0 here, but C99 guarantees that. */
01216             memset(statspec->layouts[l] + statspec->platforms[l], 0,
01217                    (number - statspec->platforms[l]) * sizeof(**statspec->layouts));
01218 
01219             statspec->platforms[l] = number;
01220           }
01221 
01222           p = 0;
01223           layout = MallocT<byte>(length * number);
01224           for (l = 0; l < length; l++) {
01225             for (p = 0; p < number; p++) {
01226               layout[l * number + p] = grf_load_byte(&buf);
01227             }
01228           }
01229 
01230           l--;
01231           p--;
01232           free(statspec->layouts[l][p]);
01233           statspec->layouts[l][p] = layout;
01234         }
01235         break;
01236 
01237       case 0x0F: { // Copy custom layout
01238         byte srcid = grf_load_byte(&buf);
01239         const StationSpec *srcstatspec = _cur_grffile->stations[srcid];
01240 
01241         statspec->lengths   = srcstatspec->lengths;
01242         statspec->platforms = srcstatspec->platforms;
01243         statspec->layouts   = srcstatspec->layouts;
01244         statspec->copied_layouts = true;
01245       } break;
01246 
01247       case 0x10: // Little/lots cargo threshold
01248         statspec->cargo_threshold = grf_load_word(&buf);
01249         break;
01250 
01251       case 0x11: // Pylon placement
01252         statspec->pylons = grf_load_byte(&buf);
01253         break;
01254 
01255       case 0x12: // Cargo types for random triggers
01256         statspec->cargo_triggers = grf_load_dword(&buf);
01257         break;
01258 
01259       case 0x13: // General flags
01260         statspec->flags = grf_load_byte(&buf);
01261         break;
01262 
01263       case 0x14: // Overhead wire placement
01264         statspec->wires = grf_load_byte(&buf);
01265         break;
01266 
01267       case 0x15: // Blocked tiles
01268         statspec->blocked = grf_load_byte(&buf);
01269         break;
01270 
01271       case 0x16: // Animation info
01272         statspec->anim_frames = grf_load_byte(&buf);
01273         statspec->anim_status = grf_load_byte(&buf);
01274         break;
01275 
01276       case 0x17: // Animation speed
01277         statspec->anim_speed = grf_load_byte(&buf);
01278         break;
01279 
01280       case 0x18: // Animation triggers
01281         statspec->anim_triggers = grf_load_word(&buf);
01282         break;
01283 
01284       default:
01285         ret = CIR_UNKNOWN;
01286         break;
01287     }
01288   }
01289 
01290   *bufp = buf;
01291   return ret;
01292 }
01293 
01294 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, byte **bufp, int len)
01295 {
01296   byte *buf = *bufp;
01297   ChangeInfoResult ret = CIR_SUCCESS;
01298 
01299   if (id + numinfo > CF_END) {
01300     grfmsg(1, "CanalChangeInfo: Canal feature %u is invalid, max %u, ignoreing", id + numinfo, CF_END);
01301     return CIR_INVALID_ID;
01302   }
01303 
01304   for (int i = 0; i < numinfo; i++) {
01305     WaterFeature *wf = &_water_feature[id + i];
01306 
01307     switch (prop) {
01308       case 0x08:
01309         wf->callbackmask = grf_load_byte(&buf);
01310         break;
01311 
01312       case 0x09:
01313         wf->flags = grf_load_byte(&buf);
01314         break;
01315 
01316       default:
01317         ret = CIR_UNKNOWN;
01318         break;
01319     }
01320   }
01321 
01322   *bufp = buf;
01323   return ret;
01324 }
01325 
01326 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, byte **bufp, int len)
01327 {
01328   byte *buf = *bufp;
01329   ChangeInfoResult ret = CIR_SUCCESS;
01330 
01331   if (brid + numinfo > MAX_BRIDGES) {
01332     grfmsg(1, "BridgeChangeInfo: Bridge %u is invalid, max %u, ignoring", brid + numinfo, MAX_BRIDGES);
01333     return CIR_INVALID_ID;
01334   }
01335 
01336   for (int i = 0; i < numinfo; i++) {
01337     BridgeSpec *bridge = &_bridge[brid + i];
01338 
01339     switch (prop) {
01340       case 0x08: // Year of availability
01341         bridge->avail_year = ORIGINAL_BASE_YEAR + grf_load_byte(&buf);
01342         break;
01343 
01344       case 0x09: // Minimum length
01345         bridge->min_length = grf_load_byte(&buf);
01346         break;
01347 
01348       case 0x0A: // Maximum length
01349         bridge->max_length = grf_load_byte(&buf);
01350         break;
01351 
01352       case 0x0B: // Cost factor
01353         bridge->price = grf_load_byte(&buf);
01354         break;
01355 
01356       case 0x0C: // Maximum speed
01357         bridge->speed = grf_load_word(&buf);
01358         break;
01359 
01360       case 0x0D: { // Bridge sprite tables
01361         byte tableid = grf_load_byte(&buf);
01362         byte numtables = grf_load_byte(&buf);
01363 
01364         if (bridge->sprite_table == NULL) {
01365           /* Allocate memory for sprite table pointers and zero out */
01366           bridge->sprite_table = CallocT<PalSpriteID*>(7);
01367         }
01368 
01369         for (; numtables-- != 0; tableid++) {
01370           if (tableid >= 7) { // skip invalid data
01371             grfmsg(1, "BridgeChangeInfo: Table %d >= 7, skipping", tableid);
01372             for (byte sprite = 0; sprite < 32; sprite++) grf_load_dword(&buf);
01373             continue;
01374           }
01375 
01376           if (bridge->sprite_table[tableid] == NULL) {
01377             bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
01378           }
01379 
01380           for (byte sprite = 0; sprite < 32; sprite++) {
01381             SpriteID image = grf_load_word(&buf);
01382             SpriteID pal   = grf_load_word(&buf);
01383 
01384             bridge->sprite_table[tableid][sprite].sprite = image;
01385             bridge->sprite_table[tableid][sprite].pal    = pal;
01386 
01387             MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
01388           }
01389         }
01390       } break;
01391 
01392       case 0x0E: // Flags; bit 0 - disable far pillars
01393         bridge->flags = grf_load_byte(&buf);
01394         break;
01395 
01396       case 0x0F: // Long format year of availability (year since year 0)
01397         bridge->avail_year = Clamp(grf_load_dword(&buf), MIN_YEAR, MAX_YEAR);
01398         break;
01399 
01400       case 0x10: { // purchase string
01401         StringID newone = GetGRFStringID(_cur_grffile->grfid, grf_load_word(&buf));
01402         if (newone != STR_UNDEFINED) bridge->material = newone;
01403         } break;
01404 
01405       case 0x11: // description of bridge with rails or roads
01406       case 0x12: {
01407         StringID newone = GetGRFStringID(_cur_grffile->grfid, grf_load_word(&buf));
01408         if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
01409         } break;
01410 
01411       case 0x13: // 16 bits cost multiplier
01412         bridge->price = grf_load_word(&buf);
01413         break;
01414 
01415       default:
01416         ret = CIR_UNKNOWN;
01417         break;
01418     }
01419   }
01420 
01421   *bufp = buf;
01422   return ret;
01423 }
01424 
01425 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, byte **bufp, int len)
01426 {
01427   byte *buf = *bufp;
01428   ChangeInfoResult ret = CIR_SUCCESS;
01429 
01430   if (hid + numinfo > HOUSE_MAX) {
01431     grfmsg(1, "TownHouseChangeInfo: Too many houses loaded (%u), max (%u). Ignoring.", hid + numinfo, HOUSE_MAX);
01432     return CIR_INVALID_ID;
01433   }
01434 
01435   /* Allocate house specs if they haven't been allocated already. */
01436   if (_cur_grffile->housespec == NULL) {
01437     _cur_grffile->housespec = CallocT<HouseSpec*>(HOUSE_MAX);
01438   }
01439 
01440   for (int i = 0; i < numinfo; i++) {
01441     HouseSpec *housespec = _cur_grffile->housespec[hid + i];
01442 
01443     if (prop != 0x08 && housespec == NULL) {
01444       grfmsg(2, "TownHouseChangeInfo: Attempt to modify undefined house %u. Ignoring.", hid + i);
01445       return CIR_INVALID_ID;
01446     }
01447 
01448     switch (prop) {
01449       case 0x08: { // Substitute building type, and definition of a new house
01450         HouseSpec **house = &_cur_grffile->housespec[hid + i];
01451         byte subs_id = grf_load_byte(&buf);
01452 
01453         if (subs_id == 0xFF) {
01454           /* Instead of defining a new house, a substitute house id
01455            * of 0xFF disables the old house with the current id. */
01456           _house_specs[hid + i].enabled = false;
01457           continue;
01458         } else if (subs_id >= NEW_HOUSE_OFFSET) {
01459           /* The substitute id must be one of the original houses. */
01460           grfmsg(2, "TownHouseChangeInfo: Attempt to use new house %u as substitute house for %u. Ignoring.", subs_id, hid + i);
01461           continue;
01462         }
01463 
01464         /* Allocate space for this house. */
01465         if (*house == NULL) *house = CallocT<HouseSpec>(1);
01466 
01467         housespec = *house;
01468 
01469         memcpy(housespec, &_house_specs[subs_id], sizeof(_house_specs[subs_id]));
01470 
01471         housespec->enabled = true;
01472         housespec->local_id = hid + i;
01473         housespec->substitute_id = subs_id;
01474         housespec->grffile = _cur_grffile;
01475         housespec->random_colour[0] = 0x04;  // those 4 random colours are the base colour
01476         housespec->random_colour[1] = 0x08;  // for all new houses
01477         housespec->random_colour[2] = 0x0C;  // they stand for red, blue, orange and green
01478         housespec->random_colour[3] = 0x06;
01479 
01480         /* Make sure that the third cargo type is valid in this
01481          * climate. This can cause problems when copying the properties
01482          * of a house that accepts food, where the new house is valid
01483          * in the temperate climate. */
01484         if (!GetCargo(housespec->accepts_cargo[2])->IsValid()) {
01485           housespec->cargo_acceptance[2] = 0;
01486         }
01487 
01493         if (housespec->min_year < 1930) housespec->min_year = 1930;
01494 
01495         _loaded_newgrf_features.has_newhouses = true;
01496       } break;
01497 
01498       case 0x09: // Building flags
01499         housespec->building_flags = (BuildingFlags)grf_load_byte(&buf);
01500         break;
01501 
01502       case 0x0A: { // Availability years
01503         uint16 years = grf_load_word(&buf);
01504         housespec->min_year = GB(years, 0, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 0, 8);
01505         housespec->max_year = GB(years, 8, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 8, 8);
01506       } break;
01507 
01508       case 0x0B: // Population
01509         housespec->population = grf_load_byte(&buf);
01510         break;
01511 
01512       case 0x0C: // Mail generation multiplier
01513         housespec->mail_generation = grf_load_byte(&buf);
01514         break;
01515 
01516       case 0x0D: // Passenger acceptance
01517       case 0x0E: // Mail acceptance
01518         housespec->cargo_acceptance[prop - 0x0D] = grf_load_byte(&buf);
01519         break;
01520 
01521       case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
01522         int8 goods = grf_load_byte(&buf);
01523 
01524         /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
01525          * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
01526         CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_CANDY : CT_GOODS) :
01527             ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_FIZZY_DRINKS : CT_FOOD);
01528 
01529         /* Make sure the cargo type is valid in this climate. */
01530         if (!GetCargo(cid)->IsValid()) goods = 0;
01531 
01532         housespec->accepts_cargo[2] = cid;
01533         housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
01534       } break;
01535 
01536       case 0x10: // Local authority rating decrease on removal
01537         housespec->remove_rating_decrease = grf_load_word(&buf);
01538         break;
01539 
01540       case 0x11: // Removal cost multiplier
01541         housespec->removal_cost = grf_load_byte(&buf);
01542         break;
01543 
01544       case 0x12: // Building name ID
01545         housespec->building_name = grf_load_word(&buf);
01546         _string_to_grf_mapping[&housespec->building_name] = _cur_grffile->grfid;
01547         break;
01548 
01549       case 0x13: // Building availability mask
01550         housespec->building_availability = (HouseZones)grf_load_word(&buf);
01551         break;
01552 
01553       case 0x14: // House callback flags
01554         housespec->callback_mask = grf_load_byte(&buf);
01555         break;
01556 
01557       case 0x15: { // House override byte
01558         byte override = grf_load_byte(&buf);
01559 
01560         /* The house being overridden must be an original house. */
01561         if (override >= NEW_HOUSE_OFFSET) {
01562           grfmsg(2, "TownHouseChangeInfo: Attempt to override new house %u with house id %u. Ignoring.", override, hid + i);
01563           continue;
01564         }
01565 
01566         _house_mngr.Add(hid + i, _cur_grffile->grfid, override);
01567       } break;
01568 
01569       case 0x16: // Periodic refresh multiplier
01570         housespec->processing_time = grf_load_byte(&buf);
01571         break;
01572 
01573       case 0x17: // Four random colours to use
01574         for (uint j = 0; j < 4; j++) housespec->random_colour[j] = grf_load_byte(&buf);
01575         break;
01576 
01577       case 0x18: // Relative probability of appearing
01578         housespec->probability = grf_load_byte(&buf);
01579         break;
01580 
01581       case 0x19: // Extra flags
01582         housespec->extra_flags = (HouseExtraFlags)grf_load_byte(&buf);
01583         break;
01584 
01585       case 0x1A: // Animation frames
01586         housespec->animation_frames = grf_load_byte(&buf);
01587         break;
01588 
01589       case 0x1B: // Animation speed
01590         housespec->animation_speed = Clamp(grf_load_byte(&buf), 2, 16);
01591         break;
01592 
01593       case 0x1C: // Class of the building type
01594         housespec->class_id = AllocateHouseClassID(grf_load_byte(&buf), _cur_grffile->grfid);
01595         break;
01596 
01597       case 0x1D: // Callback flags 2
01598         housespec->callback_mask |= (grf_load_byte(&buf) << 8);
01599         break;
01600 
01601       case 0x1E: { // Accepted cargo types
01602         uint32 cargotypes = grf_load_dword(&buf);
01603 
01604         /* Check if the cargo types should not be changed */
01605         if (cargotypes == 0xFFFFFFFF) break;
01606 
01607         for (uint j = 0; j < 3; j++) {
01608           /* Get the cargo number from the 'list' */
01609           uint8 cargo_part = GB(cargotypes, 8 * j, 8);
01610           CargoID cargo = GetCargoTranslation(cargo_part, _cur_grffile);
01611 
01612           if (cargo == CT_INVALID) {
01613             /* Disable acceptance of invalid cargo type */
01614             housespec->cargo_acceptance[j] = 0;
01615           } else {
01616             housespec->accepts_cargo[j] = cargo;
01617           }
01618         }
01619       } break;
01620 
01621       case 0x1F: // Minimum life span
01622         housespec->minimum_life = grf_load_byte(&buf);
01623         break;
01624 
01625       case 0x20: { // @todo Cargo acceptance watch list
01626         byte count = grf_load_byte(&buf);
01627         for (byte j = 0; j < count; j++) grf_load_byte(&buf);
01628         ret = CIR_UNHANDLED;
01629       } break;
01630 
01631       case 0x21: // long introduction year
01632         housespec->min_year = grf_load_word(&buf);
01633         break;
01634 
01635       case 0x22: // long maximum year
01636         housespec->max_year = grf_load_word(&buf);
01637         break;
01638 
01639       default:
01640         ret = CIR_UNKNOWN;
01641         break;
01642     }
01643   }
01644 
01645   *bufp = buf;
01646   return ret;
01647 }
01648 
01649 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, byte **bufp, int len)
01650 {
01651   byte *buf = *bufp;
01652   ChangeInfoResult ret = CIR_SUCCESS;
01653 
01654   for (int i = 0; i < numinfo; i++) {
01655     switch (prop) {
01656       case 0x08: { // Cost base factor
01657         byte factor = grf_load_byte(&buf);
01658         uint price = gvid + i;
01659 
01660         if (price < NUM_PRICES) {
01661           SetPriceBaseMultiplier(price, factor);
01662         } else {
01663           grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
01664         }
01665       } break;
01666 
01667       case 0x09: // Cargo translation table
01668         /* This is loaded during the reservation stage, so just skip it here. */
01669         /* Each entry is 4 bytes. */
01670         buf += 4;
01671         break;
01672 
01673       case 0x0A: { // Currency display names
01674         uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
01675         StringID newone = GetGRFStringID(_cur_grffile->grfid, grf_load_word(&buf));
01676 
01677         if ((newone != STR_UNDEFINED) && (curidx < NUM_CURRENCY)) {
01678           _currency_specs[curidx].name = newone;
01679         }
01680       } break;
01681 
01682       case 0x0B: { // Currency multipliers
01683         uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
01684         uint32 rate = grf_load_dword(&buf);
01685 
01686         if (curidx < NUM_CURRENCY) {
01687           /* TTDPatch uses a multiple of 1000 for its conversion calculations,
01688            * which OTTD does not. For this reason, divide grf value by 1000,
01689            * to be compatible */
01690           _currency_specs[curidx].rate = rate / 1000;
01691         } else {
01692           grfmsg(1, "GlobalVarChangeInfo: Currency multipliers %d out of range, ignoring", curidx);
01693         }
01694       } break;
01695 
01696       case 0x0C: { // Currency options
01697         uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
01698         uint16 options = grf_load_word(&buf);
01699 
01700         if (curidx < NUM_CURRENCY) {
01701           _currency_specs[curidx].separator = GB(options, 0, 8);
01702           /* By specifying only one bit, we prevent errors,
01703            * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
01704           _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
01705         } else {
01706           grfmsg(1, "GlobalVarChangeInfo: Currency option %d out of range, ignoring", curidx);
01707         }
01708       } break;
01709 
01710       case 0x0D: { // Currency prefix symbol
01711         uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
01712         uint32 tempfix = grf_load_dword(&buf);
01713 
01714         if (curidx < NUM_CURRENCY) {
01715           memcpy(_currency_specs[curidx].prefix, &tempfix, 4);
01716           _currency_specs[curidx].prefix[4] = 0;
01717         } else {
01718           grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
01719         }
01720       } break;
01721 
01722       case 0x0E: { // Currency suffix symbol
01723         uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
01724         uint32 tempfix = grf_load_dword(&buf);
01725 
01726         if (curidx < NUM_CURRENCY) {
01727           memcpy(&_currency_specs[curidx].suffix, &tempfix, 4);
01728           _currency_specs[curidx].suffix[4] = 0;
01729         } else {
01730           grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
01731         }
01732       } break;
01733 
01734       case 0x0F: { //  Euro introduction dates
01735         uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
01736         Year year_euro = grf_load_word(&buf);
01737 
01738         if (curidx < NUM_CURRENCY) {
01739           _currency_specs[curidx].to_euro = year_euro;
01740         } else {
01741           grfmsg(1, "GlobalVarChangeInfo: Euro intro date %d out of range, ignoring", curidx);
01742         }
01743       } break;
01744 
01745       case 0x10: // Snow line height table
01746         if (numinfo > 1 || IsSnowLineSet()) {
01747           grfmsg(1, "GlobalVarChangeInfo: The snowline can only be set once (%d)", numinfo);
01748         } else if (len < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
01749           grfmsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table (%d)", len);
01750         } else {
01751           byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
01752 
01753           for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
01754             for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
01755               table[i][j] = grf_load_byte(&buf);
01756             }
01757           }
01758           SetSnowLine(table);
01759         }
01760         break;
01761 
01762       case 0x11: // GRF match for engine allocation
01763         /* This is loaded during the reservation stage, so just skip it here. */
01764         /* Each entry is 8 bytes. */
01765         buf += 8;
01766         break;
01767 
01768       case 0x12: // Rail type translation table
01769         /* This is loaded during the reservation stage, so just skip it here. */
01770         /* Each entry is 4 bytes. */
01771         buf += 4;
01772         break;
01773 
01774       default:
01775         ret = CIR_UNKNOWN;
01776         break;
01777     }
01778   }
01779 
01780   *bufp = buf;
01781   return ret;
01782 }
01783 
01784 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, byte **bufp, int len)
01785 {
01786   byte *buf = *bufp;
01787   ChangeInfoResult ret = CIR_SUCCESS;
01788 
01789   for (int i = 0; i < numinfo; i++) {
01790     switch (prop) {
01791       case 0x08: // Cost base factor
01792         grf_load_byte(&buf);
01793         break;
01794 
01795       case 0x09: { // Cargo Translation Table
01796         if (i == 0) {
01797           if (gvid != 0) {
01798             grfmsg(1, "ReserveChangeInfo: Cargo translation table must start at zero");
01799             return CIR_INVALID_ID;
01800           }
01801 
01802           free(_cur_grffile->cargo_list);
01803           _cur_grffile->cargo_max = numinfo;
01804           _cur_grffile->cargo_list = MallocT<CargoLabel>(numinfo);
01805         }
01806 
01807         CargoLabel cl = grf_load_dword(&buf);
01808         _cur_grffile->cargo_list[i] = BSWAP32(cl);
01809         break;
01810       }
01811 
01812       case 0x0A: // Currency display names
01813       case 0x0C: // Currency options
01814       case 0x0F: // Euro introduction dates
01815         grf_load_word(&buf);
01816         break;
01817 
01818       case 0x0B: // Currency multipliers
01819       case 0x0D: // Currency prefix symbol
01820       case 0x0E: // Currency suffix symbol
01821         grf_load_dword(&buf);
01822         break;
01823 
01824       case 0x10: // Snow line height table
01825         buf += SNOW_LINE_MONTHS * SNOW_LINE_DAYS;
01826         break;
01827 
01828       case 0x11: { // GRF match for engine allocation
01829         uint32 s = grf_load_dword(&buf);
01830         uint32 t = grf_load_dword(&buf);
01831         SetNewGRFOverride(s, t);
01832         break;
01833       }
01834 
01835       case 0x12: { // Rail type translation table
01836         if (i == 0) {
01837           if (gvid != 0) {
01838             grfmsg(1, "ReserveChangeInfo: Rail type translation table must start at zero");
01839             return CIR_INVALID_ID;
01840           }
01841 
01842           free(_cur_grffile->railtype_list);
01843           _cur_grffile->railtype_max = numinfo;
01844           _cur_grffile->railtype_list = MallocT<RailTypeLabel>(numinfo);
01845         }
01846 
01847         RailTypeLabel rtl = grf_load_dword(&buf);
01848         _cur_grffile->railtype_list[i] = BSWAP32(rtl);
01849         break;
01850       }
01851 
01852       default:
01853         ret = CIR_UNKNOWN;
01854         break;
01855     }
01856   }
01857 
01858   *bufp = buf;
01859   return ret;
01860 }
01861 
01862 
01863 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, byte **bufp, int len)
01864 {
01865   byte *buf = *bufp;
01866   ChangeInfoResult ret = CIR_SUCCESS;
01867 
01868   if (cid + numinfo > NUM_CARGO) {
01869     grfmsg(2, "CargoChangeInfo: Cargo type %d out of range (max %d)", cid + numinfo, NUM_CARGO - 1);
01870     return CIR_INVALID_ID;
01871   }
01872 
01873   for (int i = 0; i < numinfo; i++) {
01874     CargoSpec *cs = &_cargo[cid + i];
01875 
01876     switch (prop) {
01877       case 0x08: /* Bit number of cargo */
01878         cs->bitnum = grf_load_byte(&buf);
01879         if (cs->IsValid()) {
01880           cs->grffile = _cur_grffile;
01881           SetBit(_cargo_mask, cid + i);
01882         } else {
01883           ClrBit(_cargo_mask, cid + i);
01884         }
01885         break;
01886 
01887       case 0x09: /* String ID for cargo type name */
01888         cs->name = grf_load_word(&buf);
01889         _string_to_grf_mapping[&cs->name] = _cur_grffile->grfid;
01890         break;
01891 
01892       case 0x0A: /* String for 1 unit of cargo */
01893         cs->name_single = grf_load_word(&buf);
01894         _string_to_grf_mapping[&cs->name_single] = _cur_grffile->grfid;
01895         break;
01896 
01897       case 0x0B:
01898         /* String for units of cargo. This is different in OpenTTD to TTDPatch
01899          * (e.g. 10 tonnes of coal) */
01900         cs->units_volume = grf_load_word(&buf);
01901         _string_to_grf_mapping[&cs->units_volume] = _cur_grffile->grfid;
01902         break;
01903 
01904       case 0x0C: /* String for quantity of cargo (e.g. 10 tonnes of coal) */
01905         cs->quantifier = grf_load_word(&buf);
01906         _string_to_grf_mapping[&cs->quantifier] = _cur_grffile->grfid;
01907         break;
01908 
01909       case 0x0D: /* String for two letter cargo abbreviation */
01910         cs->abbrev = grf_load_word(&buf);
01911         _string_to_grf_mapping[&cs->abbrev] = _cur_grffile->grfid;
01912         break;
01913 
01914       case 0x0E: /* Sprite ID for cargo icon */
01915         cs->sprite = grf_load_word(&buf);
01916         break;
01917 
01918       case 0x0F: /* Weight of one unit of cargo */
01919         cs->weight = grf_load_byte(&buf);
01920         break;
01921 
01922       case 0x10: /* Used for payment calculation */
01923         cs->transit_days[0] = grf_load_byte(&buf);
01924         break;
01925 
01926       case 0x11: /* Used for payment calculation */
01927         cs->transit_days[1] = grf_load_byte(&buf);
01928         break;
01929 
01930       case 0x12: /* Base cargo price */
01931         cs->initial_payment = grf_load_dword(&buf);
01932         break;
01933 
01934       case 0x13: /* Colour for station rating bars */
01935         cs->rating_colour = MapDOSColour(grf_load_byte(&buf));
01936         break;
01937 
01938       case 0x14: /* Colour for cargo graph */
01939         cs->legend_colour = MapDOSColour(grf_load_byte(&buf));
01940         break;
01941 
01942       case 0x15: /* Freight status */
01943         cs->is_freight = (grf_load_byte(&buf) != 0);
01944         break;
01945 
01946       case 0x16: /* Cargo classes */
01947         cs->classes = grf_load_word(&buf);
01948         break;
01949 
01950       case 0x17: /* Cargo label */
01951         cs->label = grf_load_dword(&buf);
01952         cs->label = BSWAP32(cs->label);
01953         break;
01954 
01955       case 0x18: { /* Town growth substitute type */
01956         uint8 substitute_type = grf_load_byte(&buf);
01957 
01958         switch (substitute_type) {
01959           case 0x00: cs->town_effect = TE_PASSENGERS; break;
01960           case 0x02: cs->town_effect = TE_MAIL; break;
01961           case 0x05: cs->town_effect = TE_GOODS; break;
01962           case 0x09: cs->town_effect = TE_WATER; break;
01963           case 0x0B: cs->town_effect = TE_FOOD; break;
01964           default:
01965             grfmsg(1, "CargoChangeInfo: Unknown town growth substitute value %d, setting to none.", substitute_type);
01966           case 0xFF: cs->town_effect = TE_NONE; break;
01967         }
01968       } break;
01969 
01970       case 0x19: /* Town growth coefficient */
01971         cs->multipliertowngrowth = grf_load_word(&buf);
01972         break;
01973 
01974       case 0x1A: /* Bitmask of callbacks to use */
01975         cs->callback_mask = grf_load_byte(&buf);
01976         break;
01977 
01978       default:
01979         ret = CIR_UNKNOWN;
01980         break;
01981     }
01982   }
01983 
01984   *bufp = buf;
01985   return ret;
01986 }
01987 
01988 
01989 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, byte **bufp, int len)
01990 {
01991   byte *buf = *bufp;
01992   ChangeInfoResult ret = CIR_SUCCESS;
01993 
01994   if (_cur_grffile->sound_offset == 0) {
01995     grfmsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
01996     return CIR_INVALID_ID;
01997   }
01998 
01999   for (int i = 0; i < numinfo; i++) {
02000     uint sound = sid + i + _cur_grffile->sound_offset - GetNumOriginalSounds();
02001 
02002     if (sound >= GetNumSounds()) {
02003       grfmsg(1, "SoundEffectChangeInfo: Sound %d not defined (max %d)", sound, GetNumSounds());
02004       return CIR_INVALID_ID;
02005     }
02006 
02007     switch (prop) {
02008       case 0x08: // Relative volume
02009         GetSound(sound)->volume = grf_load_byte(&buf);
02010         break;
02011 
02012       case 0x09: // Priority
02013         GetSound(sound)->priority = grf_load_byte(&buf);
02014         break;
02015 
02016       case 0x0A: { // Override old sound
02017         uint orig_sound = grf_load_byte(&buf);
02018 
02019         if (orig_sound >= GetNumSounds()) {
02020           grfmsg(1, "SoundEffectChangeInfo: Original sound %d not defined (max %d)", orig_sound, GetNumSounds());
02021         } else {
02022           FileEntry *newfe = GetSound(sound);
02023           FileEntry *oldfe = GetSound(orig_sound);
02024 
02025           /* Literally copy the data of the new sound over the original */
02026           *oldfe = *newfe;
02027         }
02028       } break;
02029 
02030       default:
02031         ret = CIR_UNKNOWN;
02032         break;
02033     }
02034   }
02035 
02036   *bufp = buf;
02037   return ret;
02038 }
02039 
02040 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, byte **bufp, int len)
02041 {
02042   byte *buf = *bufp;
02043   ChangeInfoResult ret = CIR_SUCCESS;
02044 
02045   if (indtid + numinfo > NUM_INDUSTRYTILES) {
02046     grfmsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded (%u), max (%u). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES);
02047     return CIR_INVALID_ID;
02048   }
02049 
02050   /* Allocate industry tile specs if they haven't been allocated already. */
02051   if (_cur_grffile->indtspec == NULL) {
02052     _cur_grffile->indtspec = CallocT<IndustryTileSpec*>(NUM_INDUSTRYTILES);
02053   }
02054 
02055   for (int i = 0; i < numinfo; i++) {
02056     IndustryTileSpec *tsp = _cur_grffile->indtspec[indtid + i];
02057 
02058     if (prop != 0x08 && tsp == NULL) {
02059       grfmsg(2, "IndustryTilesChangeInfo: Attempt to modify undefined industry tile %u. Ignoring.", indtid + i);
02060       return CIR_INVALID_ID;
02061     }
02062 
02063     switch (prop) {
02064       case 0x08: { // Substitute industry tile type
02065         IndustryTileSpec **tilespec = &_cur_grffile->indtspec[indtid + i];
02066         byte subs_id = grf_load_byte(&buf);
02067 
02068         if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
02069           /* The substitute id must be one of the original industry tile. */
02070           grfmsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile %u as substitute industry tile for %u. Ignoring.", subs_id, indtid + i);
02071           continue;
02072         }
02073 
02074         /* Allocate space for this industry. */
02075         if (*tilespec == NULL) {
02076           int tempid;
02077           *tilespec = CallocT<IndustryTileSpec>(1);
02078           tsp = *tilespec;
02079 
02080           memcpy(tsp, &_industry_tile_specs[subs_id], sizeof(_industry_tile_specs[subs_id]));
02081           tsp->enabled = true;
02082 
02083           /* A copied tile should not have the animation infos copied too.
02084            * The anim_state should be left untouched, though
02085            * It is up to the author to animate them himself */
02086           tsp->anim_production = INDUSTRYTILE_NOANIM;
02087           tsp->anim_next = INDUSTRYTILE_NOANIM;
02088 
02089           tsp->grf_prop.local_id = indtid + i;
02090           tsp->grf_prop.subst_id = subs_id;
02091           tsp->grf_prop.grffile = _cur_grffile;
02092           tempid = _industile_mngr.AddEntityID(indtid + i, _cur_grffile->grfid, subs_id); // pre-reserve the tile slot
02093         }
02094       } break;
02095 
02096       case 0x09: { // Industry tile override
02097         byte ovrid = grf_load_byte(&buf);
02098 
02099         /* The industry being overridden must be an original industry. */
02100         if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
02101           grfmsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile %u with industry tile id %u. Ignoring.", ovrid, indtid + i);
02102           continue;
02103         }
02104 
02105         _industile_mngr.Add(indtid + i, _cur_grffile->grfid, ovrid);
02106       } break;
02107 
02108       case 0x0A: // Tile acceptance
02109       case 0x0B:
02110       case 0x0C: {
02111         uint16 acctp = grf_load_word(&buf);
02112         tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur_grffile);
02113         tsp->acceptance[prop - 0x0A] = GB(acctp, 8, 8);
02114       } break;
02115 
02116       case 0x0D: // Land shape flags
02117         tsp->slopes_refused = (Slope)grf_load_byte(&buf);
02118         break;
02119 
02120       case 0x0E: // Callback flags
02121         tsp->callback_flags = grf_load_byte(&buf);
02122         break;
02123 
02124       case 0x0F: // Animation information
02125         tsp->animation_info = grf_load_word(&buf);
02126         break;
02127 
02128       case 0x10: // Animation speed
02129         tsp->animation_speed = grf_load_byte(&buf);
02130         break;
02131 
02132       case 0x11: // Triggers for callback 25
02133         tsp->animation_triggers = grf_load_byte(&buf);
02134         break;
02135 
02136       case 0x12: // Special flags
02137         tsp->animation_special_flags = grf_load_byte(&buf);
02138         break;
02139 
02140       default:
02141         ret = CIR_UNKNOWN;
02142         break;
02143     }
02144   }
02145 
02146   *bufp = buf;
02147   return ret;
02148 }
02149 
02150 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, byte **bufp, int len)
02151 {
02152   byte *buf = *bufp;
02153   ChangeInfoResult ret = CIR_SUCCESS;
02154 
02155   if (indid + numinfo > NUM_INDUSTRYTYPES) {
02156     grfmsg(1, "IndustriesChangeInfo: Too many industries loaded (%u), max (%u). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES);
02157     return CIR_INVALID_ID;
02158   }
02159 
02160   grfmsg(1, "IndustriesChangeInfo: newid %u", indid);
02161 
02162   /* Allocate industry specs if they haven't been allocated already. */
02163   if (_cur_grffile->industryspec == NULL) {
02164     _cur_grffile->industryspec = CallocT<IndustrySpec*>(NUM_INDUSTRYTYPES);
02165   }
02166 
02167   for (int i = 0; i < numinfo; i++) {
02168     IndustrySpec *indsp = _cur_grffile->industryspec[indid + i];
02169 
02170     if (prop != 0x08 && indsp == NULL) {
02171       grfmsg(2, "IndustriesChangeInfo: Attempt to modify undefined industry %u. Ignoring.", indid + i);
02172       return CIR_INVALID_ID;
02173     }
02174 
02175     switch (prop) {
02176       case 0x08: { // Substitute industry type
02177         IndustrySpec **indspec = &_cur_grffile->industryspec[indid + i];
02178         byte subs_id = grf_load_byte(&buf);
02179 
02180         if (subs_id == 0xFF) {
02181           /* Instead of defining a new industry, a substitute industry id
02182            * of 0xFF disables the old industry with the current id. */
02183           _industry_specs[indid + i].enabled = false;
02184           continue;
02185         } else if (subs_id >= NEW_INDUSTRYOFFSET) {
02186           /* The substitute id must be one of the original industry. */
02187           grfmsg(2, "_industry_specs: Attempt to use new industry %u as substitute industry for %u. Ignoring.", subs_id, indid + i);
02188           continue;
02189         }
02190 
02191         /* Allocate space for this industry.
02192          * Only need to do it once. If ever it is called again, it should not
02193          * do anything */
02194         if (*indspec == NULL) {
02195           *indspec = CallocT<IndustrySpec>(1);
02196           indsp = *indspec;
02197 
02198           memcpy(indsp, &_origin_industry_specs[subs_id], sizeof(_industry_specs[subs_id]));
02199           indsp->enabled = true;
02200           indsp->grf_prop.local_id = indid + i;
02201           indsp->grf_prop.subst_id = subs_id;
02202           indsp->grf_prop.grffile = _cur_grffile;
02203           /* If the grf industry needs to check its surounding upon creation, it should
02204            * rely on callbacks, not on the original placement functions */
02205           indsp->check_proc = CHECK_NOTHING;
02206         }
02207       } break;
02208 
02209       case 0x09: { // Industry type override
02210         byte ovrid = grf_load_byte(&buf);
02211 
02212         /* The industry being overridden must be an original industry. */
02213         if (ovrid >= NEW_INDUSTRYOFFSET) {
02214           grfmsg(2, "IndustriesChangeInfo: Attempt to override new industry %u with industry id %u. Ignoring.", ovrid, indid + i);
02215           continue;
02216         }
02217         indsp->grf_prop.override = ovrid;
02218         _industry_mngr.Add(indid + i, _cur_grffile->grfid, ovrid);
02219       } break;
02220 
02221       case 0x0A: { // Set industry layout(s)
02222         indsp->num_table = grf_load_byte(&buf); // Number of layaouts
02223         uint32 defsize = grf_load_dword(&buf);  // Total size of the definition
02224         IndustryTileTable **tile_table = CallocT<IndustryTileTable*>(indsp->num_table); // Table with tiles to compose an industry
02225         IndustryTileTable *itt = CallocT<IndustryTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
02226         int size;
02227         IndustryTileTable *copy_from;
02228 
02229         for (byte j = 0; j < indsp->num_table; j++) {
02230           for (int k = 0;; k++) {
02231             itt[k].ti.x = grf_load_byte(&buf); // Offsets from northermost tile
02232 
02233             if (itt[k].ti.x == 0xFE && k == 0) {
02234               /* This means we have to borrow the layout from an old industry */
02235               IndustryType type = grf_load_byte(&buf);  //industry holding required layout
02236               byte laynbr = grf_load_byte(&buf);        //layout number to borrow
02237 
02238               copy_from = (IndustryTileTable*)_origin_industry_specs[type].table[laynbr];
02239               for (size = 1;; size++) {
02240                 if (copy_from[size - 1].ti.x == -0x80 && copy_from[size - 1].ti.y == 0) break;
02241               }
02242               break;
02243             }
02244 
02245             itt[k].ti.y = grf_load_byte(&buf); // Or table definition finalisation
02246 
02247             if (itt[k].ti.x == 0 && itt[k].ti.y == 0x80) {
02248               /*  Not the same terminator.  The one we are using is rather
02249                x= -80, y = x .  So, adjust it. */
02250               itt[k].ti.x = -0x80;
02251               itt[k].ti.y =  0;
02252               itt[k].gfx  =  0;
02253 
02254               size = k + 1;
02255               copy_from = itt;
02256               break;
02257             }
02258 
02259             itt[k].gfx = grf_load_byte(&buf);
02260 
02261             if (itt[k].gfx == 0xFE) {
02262               /* Use a new tile from this GRF */
02263               int local_tile_id = grf_load_word(&buf);
02264 
02265               /* Read the ID from the _industile_mngr. */
02266               int tempid = _industile_mngr.GetID(local_tile_id, _cur_grffile->grfid);
02267 
02268               if (tempid == INVALID_INDUSTRYTILE) {
02269                 grfmsg(2, "IndustriesChangeInfo: Attempt to use industry tile %u with industry id %u, not yet defined. Ignoring.", local_tile_id, indid);
02270               } else {
02271                 /* Declared as been valid, can be used */
02272                 itt[k].gfx = tempid;
02273                 size = k + 1;
02274                 copy_from = itt;
02275               }
02276             } else if (itt[k].gfx == 0xFF) {
02277               itt[k].ti.x = (int8)GB(itt[k].ti.x, 0, 8);
02278               itt[k].ti.y = (int8)GB(itt[k].ti.y, 0, 8);
02279             }
02280           }
02281           tile_table[j] = CallocT<IndustryTileTable>(size);
02282           memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
02283         }
02284         /* Install final layout construction in the industry spec */
02285         indsp->table = tile_table;
02286         SetBit(indsp->cleanup_flag, 1);
02287         free(itt);
02288       } break;
02289 
02290       case 0x0B: // Industry production flags
02291         indsp->life_type = (IndustryLifeType)grf_load_byte(&buf);
02292         break;
02293 
02294       case 0x0C: // Industry closure message
02295         indsp->closure_text = grf_load_word(&buf);
02296         _string_to_grf_mapping[&indsp->closure_text] = _cur_grffile->grfid;
02297         break;
02298 
02299       case 0x0D: // Production increase message
02300         indsp->production_up_text = grf_load_word(&buf);
02301         _string_to_grf_mapping[&indsp->production_up_text] = _cur_grffile->grfid;
02302         break;
02303 
02304       case 0x0E: // Production decrease message
02305         indsp->production_down_text = grf_load_word(&buf);
02306         _string_to_grf_mapping[&indsp->production_down_text] = _cur_grffile->grfid;
02307         break;
02308 
02309       case 0x0F: // Fund cost multiplier
02310         indsp->cost_multiplier = grf_load_byte(&buf);
02311         break;
02312 
02313       case 0x10: // Production cargo types
02314         for (byte j = 0; j < 2; j++) {
02315           indsp->produced_cargo[j] = GetCargoTranslation(grf_load_byte(&buf), _cur_grffile);
02316         }
02317         break;
02318 
02319       case 0x11: // Acceptance cargo types
02320         for (byte j = 0; j < 3; j++) {
02321           indsp->accepts_cargo[j] = GetCargoTranslation(grf_load_byte(&buf), _cur_grffile);
02322         }
02323         grf_load_byte(&buf); // Unnused, eat it up
02324         break;
02325 
02326       case 0x12: // Production multipliers
02327       case 0x13:
02328         indsp->production_rate[prop - 0x12] = grf_load_byte(&buf);
02329         break;
02330 
02331       case 0x14: // Minimal amount of cargo distributed
02332         indsp->minimal_cargo = grf_load_byte(&buf);
02333         break;
02334 
02335       case 0x15: { // Random sound effects
02336         indsp->number_of_sounds = grf_load_byte(&buf);
02337         uint8 *sounds = MallocT<uint8>(indsp->number_of_sounds);
02338 
02339         for (uint8 j = 0; j < indsp->number_of_sounds; j++) sounds[j] = grf_load_byte(&buf);
02340         indsp->random_sounds = sounds;
02341         SetBit(indsp->cleanup_flag, 0);
02342       } break;
02343 
02344       case 0x16: // Conflicting industry types
02345         for (byte j = 0; j < 3; j++) indsp->conflicting[j] = grf_load_byte(&buf);
02346         break;
02347 
02348       case 0x17: // Probability in random game
02349         indsp->appear_creation[_settings_game.game_creation.landscape] = grf_load_byte(&buf);
02350         break;
02351 
02352       case 0x18: // Probability during gameplay
02353         indsp->appear_ingame[_settings_game.game_creation.landscape] = grf_load_byte(&buf);
02354         break;
02355 
02356       case 0x19: // Map colour
02357         indsp->map_colour = MapDOSColour(grf_load_byte(&buf));
02358         break;
02359 
02360       case 0x1A: // Special industry flags to define special behavior
02361         indsp->behaviour = (IndustryBehaviour)grf_load_dword(&buf);
02362         break;
02363 
02364       case 0x1B: // New industry text ID
02365         indsp->new_industry_text = grf_load_word(&buf);
02366         _string_to_grf_mapping[&indsp->new_industry_text] = _cur_grffile->grfid;
02367         break;
02368 
02369       case 0x1C: // Input cargo multipliers for the three input cargo types
02370       case 0x1D:
02371       case 0x1E: {
02372           uint32 multiples = grf_load_dword(&buf);
02373           indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
02374           indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
02375         } break;
02376 
02377       case 0x1F: // Industry name
02378         indsp->name = grf_load_word(&buf);
02379         _string_to_grf_mapping[&indsp->name] = _cur_grffile->grfid;
02380         break;
02381 
02382       case 0x20: // Prospecting success chance
02383         indsp->prospecting_chance = grf_load_dword(&buf);
02384         break;
02385 
02386       case 0x21:   // Callback flags
02387       case 0x22: { // Callback additional flags
02388         byte aflag = grf_load_byte(&buf);
02389         SB(indsp->callback_flags, (prop - 0x21) * 8, 8, aflag);
02390       } break;
02391 
02392       case 0x23: // removal cost multiplier
02393         indsp->removal_cost_multiplier = grf_load_dword(&buf);
02394         break;
02395 
02396       case 0x24: // name for nearby station
02397         indsp->station_name = grf_load_word(&buf);
02398         _string_to_grf_mapping[&indsp->station_name] = _cur_grffile->grfid;
02399         break;
02400 
02401       default:
02402         ret = CIR_UNKNOWN;
02403         break;
02404     }
02405   }
02406 
02407   *bufp = buf;
02408   return ret;
02409 }
02410 
02411 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8 feature, uint8 property)
02412 {
02413   switch (cir) {
02414     default: NOT_REACHED();
02415 
02416     case CIR_SUCCESS:
02417       return false;
02418 
02419     case CIR_UNHANDLED:
02420       grfmsg(1, "%s: Ignoring property 0x%02X of feature 0x%02X (not implemented)", caller, property, feature);
02421       return false;
02422 
02423     case CIR_UNKNOWN:
02424       grfmsg(0, "%s: Unknown property 0x%02X of feature 0x%02X, disabling", caller, property, feature);
02425       /* Fall through */
02426 
02427     case CIR_INVALID_ID:
02428       /* No debug message for an invalid ID, as it has already been output */
02429       _skip_sprites = -1;
02430       _cur_grfconfig->status = GCS_DISABLED;
02431       _cur_grfconfig->error  = CallocT<GRFError>(1);
02432       _cur_grfconfig->error->severity = STR_NEWGRF_ERROR_MSG_FATAL;
02433       _cur_grfconfig->error->message  = (cir == CIR_INVALID_ID) ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY;
02434       return true;
02435   }
02436 }
02437 
02438 /* Action 0x00 */
02439 static void FeatureChangeInfo(byte *buf, size_t len)
02440 {
02441   byte *bufend = buf + len;
02442 
02443   /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
02444    *
02445    * B feature       0, 1, 2 or 3 for trains, road vehicles, ships or planes
02446    *                 4 for defining new train station sets
02447    * B num-props     how many properties to change per vehicle/station
02448    * B num-info      how many vehicles/stations to change
02449    * E id            ID of first vehicle/station to change, if num-info is
02450    *                 greater than one, this one and the following
02451    *                 vehicles/stations will be changed
02452    * B property      what property to change, depends on the feature
02453    * V new-info      new bytes of info (variable size; depends on properties) */
02454   /* TODO: Bridges, town houses. */
02455 
02456   static const VCI_Handler handler[] = {
02457     /* GSF_TRAIN */        RailVehicleChangeInfo,
02458     /* GSF_ROAD */         RoadVehicleChangeInfo,
02459     /* GSF_SHIP */         ShipVehicleChangeInfo,
02460     /* GSF_AIRCRAFT */     AircraftVehicleChangeInfo,
02461     /* GSF_STATION */      StationChangeInfo,
02462     /* GSF_CANAL */        CanalChangeInfo,
02463     /* GSF_BRIDGE */       BridgeChangeInfo,
02464     /* GSF_TOWNHOUSE */    TownHouseChangeInfo,
02465     /* GSF_GLOBALVAR */    GlobalVarChangeInfo,
02466     /* GSF_INDUSTRYTILES */IndustrytilesChangeInfo,
02467     /* GSF_INDUSTRIES */   IndustriesChangeInfo,
02468     /* GSF_CARGOS */       NULL, /* Cargo is handled during reservation */
02469     /* GSF_SOUNDFX */      SoundEffectChangeInfo,
02470   };
02471 
02472   if (!check_length(len, 6, "FeatureChangeInfo")) return;
02473   buf++;
02474   uint8 feature  = grf_load_byte(&buf);
02475   uint8 numprops = grf_load_byte(&buf);
02476   uint numinfo  = grf_load_byte(&buf);
02477   uint engine   = grf_load_extended(&buf);
02478 
02479   grfmsg(6, "FeatureChangeInfo: feature %d, %d properties, to apply to %d+%d",
02480                  feature, numprops, engine, numinfo);
02481 
02482   if (feature >= lengthof(handler) || handler[feature] == NULL) {
02483     grfmsg(1, "FeatureChangeInfo: Unsupported feature %d, skipping", feature);
02484     return;
02485   }
02486 
02487   while (numprops-- && buf < bufend) {
02488     uint8 prop = grf_load_byte(&buf);
02489 
02490     ChangeInfoResult cir = handler[feature](engine, numinfo, prop, &buf, bufend - buf);
02491     if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
02492   }
02493 }
02494 
02495 /* Action 0x00 (GLS_SAFETYSCAN) */
02496 static void SafeChangeInfo(byte *buf, size_t len)
02497 {
02498   if (!check_length(len, 6, "SafeChangeInfo")) return;
02499   buf++;
02500   uint8 feature  = grf_load_byte(&buf);
02501   uint8 numprops = grf_load_byte(&buf);
02502   grf_load_byte(&buf);     // num-info
02503   grf_load_extended(&buf); // id
02504 
02505   if (feature == GSF_BRIDGE && numprops == 1) {
02506     uint8 prop = grf_load_byte(&buf);
02507     /* Bridge property 0x0D is redefinition of sprite layout tables, which
02508      * is considered safe. */
02509     if (prop == 0x0D) return;
02510   }
02511 
02512   SetBit(_cur_grfconfig->flags, GCF_UNSAFE);
02513 
02514   /* Skip remainder of GRF */
02515   _skip_sprites = -1;
02516 }
02517 
02518 /* Action 0x00 (GLS_RESERVE) */
02519 static void ReserveChangeInfo(byte *buf, size_t len)
02520 {
02521   byte *bufend = buf + len;
02522 
02523   if (!check_length(len, 6, "ReserveChangeInfo")) return;
02524   buf++;
02525   uint8 feature  = grf_load_byte(&buf);
02526 
02527   if (feature != GSF_CARGOS && feature != GSF_GLOBALVAR) return;
02528 
02529   uint8 numprops = grf_load_byte(&buf);
02530   uint8 numinfo  = grf_load_byte(&buf);
02531   uint8 index    = grf_load_extended(&buf);
02532 
02533   while (numprops-- && buf < bufend) {
02534     uint8 prop = grf_load_byte(&buf);
02535     ChangeInfoResult cir = CIR_SUCCESS;
02536 
02537     switch (feature) {
02538       default: NOT_REACHED();
02539       case GSF_CARGOS:
02540         cir = CargoChangeInfo(index, numinfo, prop, &buf, bufend - buf);
02541         break;
02542 
02543       case GSF_GLOBALVAR:
02544         cir = GlobalVarReserveInfo(index, numinfo, prop, &buf, bufend - buf);
02545         break;
02546     }
02547 
02548     if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
02549   }
02550 }
02551 
02557 static const SpriteGroup *NewCallBackResultSpriteGroup(uint16 value)
02558 {
02559   SpriteGroup *group = AllocateSpriteGroup();
02560 
02561   group->type = SGT_CALLBACK;
02562 
02563   /* Old style callback results have the highest byte 0xFF so signify it is a callback result
02564    * New style ones only have the highest bit set (allows 15-bit results, instead of just 8) */
02565   if ((value >> 8) == 0xFF) {
02566     value &= ~0xFF00;
02567   } else {
02568     value &= ~0x8000;
02569   }
02570 
02571   group->g.callback.result = value;
02572 
02573   return group;
02574 }
02575 
02582 static const SpriteGroup *NewResultSpriteGroup(SpriteID sprite, byte num_sprites)
02583 {
02584   SpriteGroup *group = AllocateSpriteGroup();
02585   group->type = SGT_RESULT;
02586   group->g.result.sprite = sprite;
02587   group->g.result.num_sprites = num_sprites;
02588   return group;
02589 }
02590 
02591 /* Action 0x01 */
02592 static void NewSpriteSet(byte *buf, size_t len)
02593 {
02594   /* <01> <feature> <num-sets> <num-ent>
02595    *
02596    * B feature       feature to define sprites for
02597    *                 0, 1, 2, 3: veh-type, 4: train stations
02598    * B num-sets      number of sprite sets
02599    * E num-ent       how many entries per sprite set
02600    *                 For vehicles, this is the number of different
02601    *                         vehicle directions in each sprite set
02602    *                         Set num-dirs=8, unless your sprites are symmetric.
02603    *                         In that case, use num-dirs=4.
02604    */
02605 
02606   if (!check_length(len, 4, "NewSpriteSet")) return;
02607   buf++;
02608   uint8 feature   = grf_load_byte(&buf);
02609   uint8 num_sets  = grf_load_byte(&buf);
02610   uint16 num_ents = grf_load_extended(&buf);
02611 
02612   _cur_grffile->spriteset_start = _cur_spriteid;
02613   _cur_grffile->spriteset_feature = feature;
02614   _cur_grffile->spriteset_numsets = num_sets;
02615   _cur_grffile->spriteset_numents = num_ents;
02616 
02617   grfmsg(7, "New sprite set at %d of type %d, consisting of %d sets with %d views each (total %d)",
02618     _cur_spriteid, feature, num_sets, num_ents, num_sets * num_ents
02619   );
02620 
02621   for (int i = 0; i < num_sets * num_ents; i++) {
02622     _nfo_line++;
02623     LoadNextSprite(_cur_spriteid++, _file_index, _nfo_line);
02624   }
02625 }
02626 
02627 /* Action 0x01 (SKIP) */
02628 static void SkipAct1(byte *buf, size_t len)
02629 {
02630   if (!check_length(len, 4, "SkipAct1")) return;
02631   buf++;
02632   grf_load_byte(&buf);
02633   uint8 num_sets  = grf_load_byte(&buf);
02634   uint16 num_ents = grf_load_extended(&buf);
02635 
02636   _skip_sprites = num_sets * num_ents;
02637 
02638   grfmsg(3, "SkipAct1: Skipping %d sprites", _skip_sprites);
02639 }
02640 
02641 /* Helper function to either create a callback or link to a previously
02642  * defined spritegroup. */
02643 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 groupid)
02644 {
02645   if (HasBit(groupid, 15)) return NewCallBackResultSpriteGroup(groupid);
02646 
02647   if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
02648     grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
02649     return NULL;
02650   }
02651 
02652   return _cur_grffile->spritegroups[groupid];
02653 }
02654 
02655 /* Helper function to either create a callback or a result sprite group. */
02656 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid, uint16 num_sprites)
02657 {
02658   if (HasBit(spriteid, 15)) return NewCallBackResultSpriteGroup(spriteid);
02659 
02660   if (spriteid >= _cur_grffile->spriteset_numsets) {
02661     grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid, max %u", setid, type, spriteid, _cur_grffile->spriteset_numsets);
02662     return NULL;
02663   }
02664 
02665   /* Check if the sprite is within range. This can fail if the Action 0x01
02666    * is skipped, as TTDPatch mandates that Action 0x02s must be processed.
02667    * We don't have that rule, but must live by the Patch... */
02668   if (_cur_grffile->spriteset_start + spriteid * num_sprites + num_sprites > _cur_spriteid) {
02669     grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Real Sprite IDs 0x%04X - 0x%04X do not (all) exist (max 0x%04X), leaving empty",
02670         setid, type,
02671         _cur_grffile->spriteset_start + spriteid * num_sprites,
02672         _cur_grffile->spriteset_start + spriteid * num_sprites + num_sprites - 1, _cur_spriteid - 1);
02673     return NULL;
02674   }
02675 
02676   if (feature != _cur_grffile->spriteset_feature) {
02677     grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set feature 0x%02X does not match action feature 0x%02X, skipping",
02678         setid, type,
02679         _cur_grffile->spriteset_feature, feature);
02680     return NULL;
02681   }
02682 
02683   return NewResultSpriteGroup(_cur_grffile->spriteset_start + spriteid * num_sprites, num_sprites);
02684 }
02685 
02686 /* Action 0x02 */
02687 static void NewSpriteGroup(byte *buf, size_t len)
02688 {
02689   /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
02690    *
02691    * B feature       see action 1
02692    * B set-id        ID of this particular definition
02693    * B type/num-entries
02694    *                 if 80 or greater, this is a randomized or variational
02695    *                 list definition, see below
02696    *                 otherwise it specifies a number of entries, the exact
02697    *                 meaning depends on the feature
02698    * V feature-specific-data (huge mess, don't even look it up --pasky) */
02699   SpriteGroup *group = NULL;
02700   byte *bufend = buf + len;
02701 
02702   if (!check_length(len, 5, "NewSpriteGroup")) return;
02703   buf++;
02704 
02705   uint8 feature = grf_load_byte(&buf);
02706   uint8 setid   = grf_load_byte(&buf);
02707   uint8 type    = grf_load_byte(&buf);
02708 
02709   if (setid >= _cur_grffile->spritegroups_count) {
02710     /* Allocate memory for new sprite group references. */
02711     _cur_grffile->spritegroups = ReallocT(_cur_grffile->spritegroups, setid + 1);
02712     /* Initialise new space to NULL */
02713     for (; _cur_grffile->spritegroups_count < (setid + 1); _cur_grffile->spritegroups_count++)
02714       _cur_grffile->spritegroups[_cur_grffile->spritegroups_count] = NULL;
02715   }
02716 
02717   switch (type) {
02718     /* Deterministic Sprite Group */
02719     case 0x81: // Self scope, byte
02720     case 0x82: // Parent scope, byte
02721     case 0x85: // Self scope, word
02722     case 0x86: // Parent scope, word
02723     case 0x89: // Self scope, dword
02724     case 0x8A: // Parent scope, dword
02725     {
02726       byte varadjust;
02727       byte varsize;
02728 
02729       /* Check we can load the var size parameter */
02730       if (!check_length(bufend - buf, 1, "NewSpriteGroup (Deterministic) (1)")) return;
02731 
02732       group = AllocateSpriteGroup();
02733       group->type = SGT_DETERMINISTIC;
02734       group->g.determ.var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
02735 
02736       switch (GB(type, 2, 2)) {
02737         default: NOT_REACHED();
02738         case 0: group->g.determ.size = DSG_SIZE_BYTE;  varsize = 1; break;
02739         case 1: group->g.determ.size = DSG_SIZE_WORD;  varsize = 2; break;
02740         case 2: group->g.determ.size = DSG_SIZE_DWORD; varsize = 4; break;
02741       }
02742 
02743       if (!check_length(bufend - buf, 5 + varsize, "NewSpriteGroup (Deterministic) (2)")) return;
02744 
02745       /* Loop through the var adjusts. Unfortunately we don't know how many we have
02746        * from the outset, so we shall have to keep reallocing. */
02747       do {
02748         DeterministicSpriteGroupAdjust *adjust;
02749 
02750         if (group->g.determ.num_adjusts > 0) {
02751           if (!check_length(bufend - buf, 2 + varsize + 3, "NewSpriteGroup (Deterministic) (3)")) return;
02752         }
02753 
02754         group->g.determ.num_adjusts++;
02755         group->g.determ.adjusts = ReallocT(group->g.determ.adjusts, group->g.determ.num_adjusts);
02756 
02757         adjust = &group->g.determ.adjusts[group->g.determ.num_adjusts - 1];
02758 
02759         /* The first var adjust doesn't have an operation specified, so we set it to add. */
02760         adjust->operation = group->g.determ.num_adjusts == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)grf_load_byte(&buf);
02761         adjust->variable  = grf_load_byte(&buf);
02762         if (adjust->variable == 0x7E) {
02763           /* Link subroutine group */
02764           adjust->subroutine = GetGroupFromGroupID(setid, type, grf_load_byte(&buf));
02765         } else {
02766           adjust->parameter = IsInsideMM(adjust->variable, 0x60, 0x80) ? grf_load_byte(&buf) : 0;
02767         }
02768 
02769         varadjust = grf_load_byte(&buf);
02770         adjust->shift_num = GB(varadjust, 0, 5);
02771         adjust->type      = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
02772         adjust->and_mask  = grf_load_var(varsize, &buf);
02773 
02774         if (adjust->type != DSGA_TYPE_NONE) {
02775           adjust->add_val    = grf_load_var(varsize, &buf);
02776           adjust->divmod_val = grf_load_var(varsize, &buf);
02777         } else {
02778           adjust->add_val    = 0;
02779           adjust->divmod_val = 0;
02780         }
02781 
02782         /* Continue reading var adjusts while bit 5 is set. */
02783       } while (HasBit(varadjust, 5));
02784 
02785       group->g.determ.num_ranges = grf_load_byte(&buf);
02786       if (group->g.determ.num_ranges > 0) group->g.determ.ranges = CallocT<DeterministicSpriteGroupRange>(group->g.determ.num_ranges);
02787 
02788       if (!check_length(bufend - buf, 2 + (2 + 2 * varsize) * group->g.determ.num_ranges, "NewSpriteGroup (Deterministic)")) return;
02789 
02790       for (uint i = 0; i < group->g.determ.num_ranges; i++) {
02791         group->g.determ.ranges[i].group = GetGroupFromGroupID(setid, type, grf_load_word(&buf));
02792         group->g.determ.ranges[i].low   = grf_load_var(varsize, &buf);
02793         group->g.determ.ranges[i].high  = grf_load_var(varsize, &buf);
02794       }
02795 
02796       group->g.determ.default_group = GetGroupFromGroupID(setid, type, grf_load_word(&buf));
02797       break;
02798     }
02799 
02800     /* Randomized Sprite Group */
02801     case 0x80: // Self scope
02802     case 0x83: // Parent scope
02803     case 0x84: // Relative scope
02804     {
02805       if (!check_length(bufend - buf, HasBit(type, 2) ? 8 : 7, "NewSpriteGroup (Randomized) (1)")) return;
02806 
02807       group = AllocateSpriteGroup();
02808       group->type = SGT_RANDOMIZED;
02809       group->g.random.var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
02810 
02811       if (HasBit(type, 2)) {
02812         if (feature <= GSF_AIRCRAFT) group->g.random.var_scope = VSG_SCOPE_RELATIVE;
02813         group->g.random.count = grf_load_byte(&buf);
02814       }
02815 
02816       uint8 triggers = grf_load_byte(&buf);
02817       group->g.random.triggers       = GB(triggers, 0, 7);
02818       group->g.random.cmp_mode       = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
02819       group->g.random.lowest_randbit = grf_load_byte(&buf);
02820       group->g.random.num_groups     = grf_load_byte(&buf);
02821       group->g.random.groups = CallocT<const SpriteGroup*>(group->g.random.num_groups);
02822 
02823       if (!check_length(bufend - buf, 2 * group->g.random.num_groups, "NewSpriteGroup (Randomized) (2)")) return;
02824 
02825       for (uint i = 0; i < group->g.random.num_groups; i++) {
02826         group->g.random.groups[i] = GetGroupFromGroupID(setid, type, grf_load_word(&buf));
02827       }
02828 
02829       break;
02830     }
02831 
02832     /* Neither a variable or randomized sprite group... must be a real group */
02833     default:
02834     {
02835 
02836 
02837       switch (feature) {
02838         case GSF_TRAIN:
02839         case GSF_ROAD:
02840         case GSF_SHIP:
02841         case GSF_AIRCRAFT:
02842         case GSF_STATION:
02843         case GSF_CANAL:
02844         case GSF_CARGOS:
02845         {
02846           byte sprites     = _cur_grffile->spriteset_numents;
02847           byte num_loaded  = type;
02848           byte num_loading = grf_load_byte(&buf);
02849 
02850           if (_cur_grffile->spriteset_start == 0) {
02851             grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
02852             return;
02853           }
02854 
02855           if (!check_length(bufend - buf, 2 * num_loaded + 2 * num_loading, "NewSpriteGroup (Real) (1)")) return;
02856 
02857           group = AllocateSpriteGroup();
02858           group->type = SGT_REAL;
02859 
02860           group->g.real.num_loaded  = num_loaded;
02861           group->g.real.num_loading = num_loading;
02862           if (num_loaded  > 0) group->g.real.loaded = CallocT<const SpriteGroup*>(num_loaded);
02863           if (num_loading > 0) group->g.real.loading = CallocT<const SpriteGroup*>(num_loading);
02864 
02865           grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u views, %u loaded, %u loading",
02866               setid, sprites, num_loaded, num_loading);
02867 
02868           for (uint i = 0; i < num_loaded; i++) {
02869             uint16 spriteid = grf_load_word(&buf);
02870             group->g.real.loaded[i] = CreateGroupFromGroupID(feature, setid, type, spriteid, sprites);
02871             grfmsg(8, "NewSpriteGroup: + rg->loaded[%i]  = subset %u", i, spriteid);
02872           }
02873 
02874           for (uint i = 0; i < num_loading; i++) {
02875             uint16 spriteid = grf_load_word(&buf);
02876             group->g.real.loading[i] = CreateGroupFromGroupID(feature, setid, type, spriteid, sprites);
02877             grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, spriteid);
02878           }
02879 
02880           break;
02881         }
02882 
02883         case GSF_TOWNHOUSE:
02884         case GSF_INDUSTRYTILES: {
02885           byte sprites     = _cur_grffile->spriteset_numents;
02886           byte num_sprites = max((uint8)1, type);
02887           uint i;
02888 
02889           group = AllocateSpriteGroup();
02890           group->type = SGT_TILELAYOUT;
02891           group->g.layout.num_sprites = sprites;
02892           group->g.layout.dts = CallocT<DrawTileSprites>(1);
02893 
02894           /* Groundsprite */
02895           group->g.layout.dts->ground.sprite = grf_load_word(&buf);
02896           group->g.layout.dts->ground.pal    = grf_load_word(&buf);
02897 
02898           /* Remap transparent/colour modifier bits */
02899           MapSpriteMappingRecolour(&group->g.layout.dts->ground);
02900 
02901           if (HasBit(group->g.layout.dts->ground.pal, 15)) {
02902             /* Bit 31 set means this is a custom sprite, so rewrite it to the
02903              * last spriteset defined. */
02904             SpriteID sprite = _cur_grffile->spriteset_start + GB(group->g.layout.dts->ground.sprite, 0, 14) * sprites;
02905             SB(group->g.layout.dts->ground.sprite, 0, SPRITE_WIDTH, sprite);
02906             ClrBit(group->g.layout.dts->ground.pal, 15);
02907           }
02908 
02909           group->g.layout.dts->seq = CallocT<DrawTileSeqStruct>(num_sprites + 1);
02910 
02911           for (i = 0; i < num_sprites; i++) {
02912             DrawTileSeqStruct *seq = (DrawTileSeqStruct*)&group->g.layout.dts->seq[i];
02913 
02914             seq->image.sprite = grf_load_word(&buf);
02915             seq->image.pal   = grf_load_word(&buf);
02916             seq->delta_x = grf_load_byte(&buf);
02917             seq->delta_y = grf_load_byte(&buf);
02918 
02919             MapSpriteMappingRecolour(&seq->image);
02920 
02921             if (HasBit(seq->image.pal, 15)) {
02922               /* Bit 31 set means this is a custom sprite, so rewrite it to the
02923                * last spriteset defined. */
02924               SpriteID sprite = _cur_grffile->spriteset_start + GB(seq->image.sprite, 0, 14) * sprites;
02925               SB(seq->image.sprite, 0, SPRITE_WIDTH, sprite);
02926               ClrBit(seq->image.pal, 15);
02927             }
02928 
02929             if (type > 0) {
02930               seq->delta_z = grf_load_byte(&buf);
02931               if ((byte)seq->delta_z == 0x80) continue;
02932             }
02933 
02934             seq->size_x = grf_load_byte(&buf);
02935             seq->size_y = grf_load_byte(&buf);
02936             seq->size_z = grf_load_byte(&buf);
02937           }
02938 
02939           /* Set the terminator value. */
02940           ((DrawTileSeqStruct*)group->g.layout.dts->seq)[i].delta_x = (byte)0x80;
02941 
02942           break;
02943         }
02944 
02945         case GSF_INDUSTRIES: {
02946           if (type > 1) {
02947             grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
02948             break;
02949           }
02950 
02951           group = AllocateSpriteGroup();
02952           group->type = SGT_INDUSTRY_PRODUCTION;
02953           group->g.indprod.version = type;
02954           if (type == 0) {
02955             for (uint i = 0; i < 3; i++) {
02956               group->g.indprod.substract_input[i] = grf_load_word(&buf);
02957             }
02958             for (uint i = 0; i < 2; i++) {
02959               group->g.indprod.add_output[i] = grf_load_word(&buf);
02960             }
02961             group->g.indprod.again = grf_load_byte(&buf);
02962           } else {
02963             for (uint i = 0; i < 3; i++) {
02964               group->g.indprod.substract_input[i] = grf_load_byte(&buf);
02965             }
02966             for (uint i = 0; i < 2; i++) {
02967               group->g.indprod.add_output[i] = grf_load_byte(&buf);
02968             }
02969             group->g.indprod.again = grf_load_byte(&buf);
02970           }
02971           break;
02972         }
02973 
02974         /* Loading of Tile Layout and Production Callback groups would happen here */
02975         default: grfmsg(1, "NewSpriteGroup: Unsupported feature %d, skipping", feature);
02976       }
02977     }
02978   }
02979 
02980   _cur_grffile->spritegroups[setid] = group;
02981 }
02982 
02983 static CargoID TranslateCargo(uint8 feature, uint8 ctype)
02984 {
02985   /* Special cargo types for purchase list and stations */
02986   if (feature == GSF_STATION && ctype == 0xFE) return CT_DEFAULT_NA;
02987   if (ctype == 0xFF) return CT_PURCHASE;
02988 
02989   if (_cur_grffile->cargo_max == 0) {
02990     /* No cargo table, so use bitnum values */
02991     if (ctype >= 32) {
02992       grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
02993       return CT_INVALID;
02994     }
02995 
02996     for (CargoID c = 0; c < NUM_CARGO; c++) {
02997       const CargoSpec *cs = GetCargo(c);
02998       if (!cs->IsValid()) continue;
02999 
03000       if (cs->bitnum == ctype) {
03001         grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, c);
03002         return c;
03003       }
03004     }
03005 
03006     grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
03007     return CT_INVALID;
03008   }
03009 
03010   /* Check if the cargo type is out of bounds of the cargo translation table */
03011   if (ctype >= _cur_grffile->cargo_max) {
03012     grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, _cur_grffile->cargo_max - 1);
03013     return CT_INVALID;
03014   }
03015 
03016   /* Look up the cargo label from the translation table */
03017   CargoLabel cl = _cur_grffile->cargo_list[ctype];
03018   if (cl == 0) {
03019     grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
03020     return CT_INVALID;
03021   }
03022 
03023   ctype = GetCargoIDByLabel(cl);
03024   if (ctype == CT_INVALID) {
03025     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));
03026     return CT_INVALID;
03027   }
03028 
03029   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);
03030   return ctype;
03031 }
03032 
03033 
03034 static bool IsValidGroupID(uint16 groupid, const char *function)
03035 {
03036   if (groupid >= _cur_grffile->spritegroups_count || _cur_grffile->spritegroups[groupid] == NULL) {
03037     grfmsg(1, "%s: Spriteset 0x%04X out of range (maximum 0x%02X) or empty, skipping.", function, groupid, _cur_grffile->spritegroups_count - 1);
03038     return false;
03039   }
03040 
03041   return true;
03042 }
03043 
03044 static void VehicleMapSpriteGroup(byte *buf, byte feature, uint8 idcount)
03045 {
03046   static EngineID *last_engines;
03047   static uint last_engines_count;
03048   bool wagover = false;
03049 
03050   /* Test for 'wagon override' flag */
03051   if (HasBit(idcount, 7)) {
03052     wagover = true;
03053     /* Strip off the flag */
03054     idcount = GB(idcount, 0, 7);
03055 
03056     if (last_engines_count == 0) {
03057       grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
03058       return;
03059     }
03060 
03061     grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
03062         last_engines_count, idcount);
03063   } else {
03064     if (last_engines_count != idcount) {
03065       last_engines = ReallocT(last_engines, idcount);
03066       last_engines_count = idcount;
03067     }
03068   }
03069 
03070   EngineID *engines = AllocaM(EngineID, idcount);
03071   for (uint i = 0; i < idcount; i++) {
03072     engines[i] = GetNewEngine(_cur_grffile, (VehicleType)feature, grf_load_extended(&buf))->index;
03073     if (!wagover) last_engines[i] = engines[i];
03074   }
03075 
03076   uint8 cidcount = grf_load_byte(&buf);
03077   for (uint c = 0; c < cidcount; c++) {
03078     uint8 ctype = grf_load_byte(&buf);
03079     uint16 groupid = grf_load_word(&buf);
03080     if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
03081 
03082     grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
03083 
03084     ctype = TranslateCargo(feature, ctype);
03085     if (ctype == CT_INVALID) continue;
03086 
03087     for (uint i = 0; i < idcount; i++) {
03088       EngineID engine = engines[i];
03089 
03090       grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
03091 
03092       if (wagover) {
03093         SetWagonOverrideSprites(engine, ctype, _cur_grffile->spritegroups[groupid], last_engines, last_engines_count);
03094       } else {
03095         SetCustomEngineSprites(engine, ctype, _cur_grffile->spritegroups[groupid]);
03096       }
03097     }
03098   }
03099 
03100   uint16 groupid = grf_load_word(&buf);
03101   if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
03102 
03103   grfmsg(8, "-- Default group id 0x%04X", groupid);
03104 
03105   for (uint i = 0; i < idcount; i++) {
03106     EngineID engine = engines[i];
03107 
03108     if (wagover) {
03109       SetWagonOverrideSprites(engine, CT_DEFAULT, _cur_grffile->spritegroups[groupid], last_engines, last_engines_count);
03110     } else {
03111       SetCustomEngineSprites(engine, CT_DEFAULT, _cur_grffile->spritegroups[groupid]);
03112       SetEngineGRF(engine, _cur_grffile);
03113     }
03114   }
03115 }
03116 
03117 
03118 static void CanalMapSpriteGroup(byte *buf, uint8 idcount)
03119 {
03120   CanalFeature *cfs = AllocaM(CanalFeature, idcount);
03121   for (uint i = 0; i < idcount; i++) {
03122     cfs[i] = (CanalFeature)grf_load_byte(&buf);
03123   }
03124 
03125   uint8 cidcount = grf_load_byte(&buf);
03126   buf += cidcount * 3;
03127 
03128   uint16 groupid = grf_load_word(&buf);
03129   if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
03130 
03131   for (uint i = 0; i < idcount; i++) {
03132     CanalFeature cf = cfs[i];
03133 
03134     if (cf >= CF_END) {
03135       grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
03136       continue;
03137     }
03138 
03139     _water_feature[cf].grffile = _cur_grffile;
03140     _water_feature[cf].group = _cur_grffile->spritegroups[groupid];
03141   }
03142 }
03143 
03144 
03145 static void StationMapSpriteGroup(byte *buf, uint8 idcount)
03146 {
03147   uint8 *stations = AllocaM(uint8, idcount);
03148   for (uint i = 0; i < idcount; i++) {
03149     stations[i] = grf_load_byte(&buf);
03150   }
03151 
03152   uint8 cidcount = grf_load_byte(&buf);
03153   for (uint c = 0; c < cidcount; c++) {
03154     uint8 ctype = grf_load_byte(&buf);
03155     uint16 groupid = grf_load_word(&buf);
03156     if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
03157 
03158     ctype = TranslateCargo(GSF_STATION, ctype);
03159     if (ctype == CT_INVALID) continue;
03160 
03161     for (uint i = 0; i < idcount; i++) {
03162       StationSpec *statspec = _cur_grffile->stations[stations[i]];
03163 
03164       if (statspec == NULL) {
03165         grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
03166         continue;
03167       }
03168 
03169       statspec->spritegroup[ctype] = _cur_grffile->spritegroups[groupid];
03170     }
03171   }
03172 
03173   uint16 groupid = grf_load_word(&buf);
03174   if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
03175 
03176   for (uint i = 0; i < idcount; i++) {
03177     StationSpec *statspec = _cur_grffile->stations[stations[i]];
03178 
03179     if (statspec == NULL) {
03180       grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
03181       continue;
03182     }
03183 
03184     statspec->spritegroup[CT_DEFAULT] = _cur_grffile->spritegroups[groupid];
03185     statspec->grffile = _cur_grffile;
03186     statspec->localidx = stations[i];
03187     SetCustomStationSpec(statspec);
03188   }
03189 }
03190 
03191 
03192 static void TownHouseMapSpriteGroup(byte *buf, uint8 idcount)
03193 {
03194   uint8 *houses = AllocaM(uint8, idcount);
03195   for (uint i = 0; i < idcount; i++) {
03196     houses[i] = grf_load_byte(&buf);
03197   }
03198 
03199   /* Skip the cargo type section, we only care about the default group */
03200   uint8 cidcount = grf_load_byte(&buf);
03201   buf += cidcount * 3;
03202 
03203   uint16 groupid = grf_load_word(&buf);
03204   if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
03205 
03206   for (uint i = 0; i < idcount; i++) {
03207     HouseSpec *hs = _cur_grffile->housespec[houses[i]];
03208 
03209     if (hs == NULL) {
03210       grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
03211       continue;
03212     }
03213 
03214     hs->spritegroup = _cur_grffile->spritegroups[groupid];
03215   }
03216 }
03217 
03218 static void IndustryMapSpriteGroup(byte *buf, uint8 idcount)
03219 {
03220   uint8 *industries = AllocaM(uint8, idcount);
03221   for (uint i = 0; i < idcount; i++) {
03222     industries[i] = grf_load_byte(&buf);
03223   }
03224 
03225   /* Skip the cargo type section, we only care about the default group */
03226   uint8 cidcount = grf_load_byte(&buf);
03227   buf += cidcount * 3;
03228 
03229   uint16 groupid = grf_load_word(&buf);
03230   if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
03231 
03232   for (uint i = 0; i < idcount; i++) {
03233     IndustrySpec *indsp = _cur_grffile->industryspec[industries[i]];
03234 
03235     if (indsp == NULL) {
03236       grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
03237       continue;
03238     }
03239 
03240     indsp->grf_prop.spritegroup = _cur_grffile->spritegroups[groupid];
03241   }
03242 }
03243 
03244 static void IndustrytileMapSpriteGroup(byte *buf, uint8 idcount)
03245 {
03246   uint8 *indtiles = AllocaM(uint8, idcount);
03247   for (uint i = 0; i < idcount; i++) {
03248     indtiles[i] = grf_load_byte(&buf);
03249   }
03250 
03251   /* Skip the cargo type section, we only care about the default group */
03252   uint8 cidcount = grf_load_byte(&buf);
03253   buf += cidcount * 3;
03254 
03255   uint16 groupid = grf_load_word(&buf);
03256   if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
03257 
03258   for (uint i = 0; i < idcount; i++) {
03259     IndustryTileSpec *indtsp = _cur_grffile->indtspec[indtiles[i]];
03260 
03261     if (indtsp == NULL) {
03262       grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
03263       continue;
03264     }
03265 
03266     indtsp->grf_prop.spritegroup = _cur_grffile->spritegroups[groupid];
03267   }
03268 }
03269 
03270 static void CargoMapSpriteGroup(byte *buf, uint8 idcount)
03271 {
03272   CargoID *cargos = AllocaM(CargoID, idcount);
03273   for (uint i = 0; i < idcount; i++) {
03274     cargos[i] = grf_load_byte(&buf);
03275   }
03276 
03277   /* Skip the cargo type section, we only care about the default group */
03278   uint8 cidcount = grf_load_byte(&buf);
03279   buf += cidcount * 3;
03280 
03281   uint16 groupid = grf_load_word(&buf);
03282   if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
03283 
03284   for (uint i = 0; i < idcount; i++) {
03285     CargoID cid = cargos[i];
03286 
03287     if (cid >= NUM_CARGO) {
03288       grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
03289       continue;
03290     }
03291 
03292     CargoSpec *cs = &_cargo[cid];
03293     cs->grffile = _cur_grffile;
03294     cs->group = _cur_grffile->spritegroups[groupid];
03295   }
03296 }
03297 
03298 
03299 /* Action 0x03 */
03300 static void FeatureMapSpriteGroup(byte *buf, size_t len)
03301 {
03302   /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
03303    * id-list    := [<id>] [id-list]
03304    * cargo-list := <cargo-type> <cid> [cargo-list]
03305    *
03306    * B feature       see action 0
03307    * B n-id          bits 0-6: how many IDs this definition applies to
03308    *                 bit 7: if set, this is a wagon override definition (see below)
03309    * B ids           the IDs for which this definition applies
03310    * B num-cid       number of cargo IDs (sprite group IDs) in this definition
03311    *                 can be zero, in that case the def-cid is used always
03312    * B cargo-type    type of this cargo type (e.g. mail=2, wood=7, see below)
03313    * W cid           cargo ID (sprite group ID) for this type of cargo
03314    * W def-cid       default cargo ID (sprite group ID) */
03315 
03316   if (_cur_grffile->spritegroups == 0) {
03317     grfmsg(1, "FeatureMapSpriteGroup: No sprite groups to work on! Skipping");
03318     return;
03319   }
03320 
03321   if (!check_length(len, 6, "FeatureMapSpriteGroup")) return;
03322 
03323   buf++;
03324   uint8 feature = grf_load_byte(&buf);
03325   uint8 idcount = grf_load_byte(&buf);
03326 
03327   /* If idcount is zero, this is a feature callback */
03328   if (idcount == 0) {
03329     /* Skip number of cargo ids? */
03330     grf_load_byte(&buf);
03331     uint16 groupid = grf_load_word(&buf);
03332 
03333     grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature %d", feature);
03334 
03335     AddGenericCallback(feature, _cur_grffile, _cur_grffile->spritegroups[groupid]);
03336     return;
03337   }
03338 
03339   grfmsg(6, "FeatureMapSpriteGroup: Feature %d, %d ids", feature, idcount);
03340 
03341   switch (feature) {
03342     case GSF_TRAIN:
03343     case GSF_ROAD:
03344     case GSF_SHIP:
03345     case GSF_AIRCRAFT:
03346       VehicleMapSpriteGroup(buf, feature, idcount);
03347       return;
03348 
03349     case GSF_CANAL:
03350       CanalMapSpriteGroup(buf, idcount);
03351       return;
03352 
03353     case GSF_STATION:
03354       StationMapSpriteGroup(buf, idcount);
03355       return;
03356 
03357     case GSF_TOWNHOUSE:
03358       TownHouseMapSpriteGroup(buf, idcount);
03359       return;
03360 
03361     case GSF_INDUSTRIES:
03362       IndustryMapSpriteGroup(buf, idcount);
03363       return;
03364 
03365     case GSF_INDUSTRYTILES:
03366       IndustrytileMapSpriteGroup(buf, idcount);
03367       return;
03368 
03369     case GSF_CARGOS:
03370       CargoMapSpriteGroup(buf, idcount);
03371       return;
03372 
03373     default:
03374       grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature %d, skipping", feature);
03375       return;
03376   }
03377 }
03378 
03379 /* Action 0x04 */
03380 static void FeatureNewName(byte *buf, size_t len)
03381 {
03382   /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
03383    *
03384    * B veh-type      see action 0 (as 00..07, + 0A
03385    *                 But IF veh-type = 48, then generic text
03386    * B language-id   If bit 6 is set, This is the extended language scheme,
03387                      with up to 64 language.
03388                      Otherwise, it is a mapping where set bits have meaning
03389                      0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
03390                      Bit 7 set means this is a generic text, not a vehicle one (or else)
03391    * B num-veh       number of vehicles which are getting a new name
03392    * B/W offset      number of the first vehicle that gets a new name
03393    *                 Byte : ID of vehicle to change
03394    *                 Word : ID of string to change/add
03395    * S data          new texts, each of them zero-terminated, after
03396    *                 which the next name begins. */
03397 
03398   bool new_scheme = _cur_grffile->grf_version >= 7;
03399 
03400   if (!check_length(len, 6, "FeatureNewName")) return;
03401   buf++;
03402   uint8 feature  = grf_load_byte(&buf);
03403   uint8 lang     = grf_load_byte(&buf);
03404   uint8 num      = grf_load_byte(&buf);
03405   bool generic   = HasBit(lang, 7);
03406   uint16 id;
03407   if (generic) {
03408     id = grf_load_word(&buf);
03409   } else if (feature <= GSF_AIRCRAFT) {
03410     id = grf_load_extended(&buf);
03411   } else {
03412     id = grf_load_byte(&buf);
03413   }
03414 
03415   ClrBit(lang, 7);
03416 
03417   uint16 endid = id + num;
03418 
03419   grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature %d) in language 0x%02X",
03420                  id, endid, feature, lang);
03421 
03422   len -= generic ? 6 : 5;
03423 
03424   for (; id < endid && len > 0; id++) {
03425     const char *name   = grf_load_string(&buf, len);
03426     size_t name_length = strlen(name) + 1;
03427 
03428     len -= (int)name_length;
03429 
03430     grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
03431 
03432     switch (feature) {
03433       case GSF_TRAIN:
03434       case GSF_ROAD:
03435       case GSF_SHIP:
03436       case GSF_AIRCRAFT:
03437         if (!generic) {
03438           Engine *e = GetNewEngine(_cur_grffile, (VehicleType)feature, id);
03439           StringID string = AddGRFString(_cur_grffile->grfid, e->index, lang, new_scheme, name, e->info.string_id);
03440           e->info.string_id = string;
03441         } else {
03442           AddGRFString(_cur_grffile->grfid, id, lang, new_scheme, name, id);
03443         }
03444         break;
03445 
03446       case GSF_INDUSTRIES: {
03447         AddGRFString(_cur_grffile->grfid, id, lang, new_scheme, name, STR_UNDEFINED);
03448         break;
03449       }
03450 
03451       case GSF_TOWNHOUSE:
03452       default:
03453         switch (GB(id, 8, 8)) {
03454           case 0xC4: // Station class name
03455             if (_cur_grffile->stations == NULL || _cur_grffile->stations[GB(id, 0, 8)] == NULL) {
03456               grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
03457             } else {
03458               StationClassID sclass = _cur_grffile->stations[GB(id, 0, 8)]->sclass;
03459               SetStationClassName(sclass, AddGRFString(_cur_grffile->grfid, id, lang, new_scheme, name, STR_UNDEFINED));
03460             }
03461             break;
03462 
03463           case 0xC5: // Station name
03464             if (_cur_grffile->stations == NULL || _cur_grffile->stations[GB(id, 0, 8)] == NULL) {
03465               grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
03466             } else {
03467               _cur_grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur_grffile->grfid, id, lang, new_scheme, name, STR_UNDEFINED);
03468             }
03469             break;
03470 
03471           case 0xC9: // House name
03472             if (_cur_grffile->housespec == NULL || _cur_grffile->housespec[GB(id, 0, 8)] == NULL) {
03473               grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
03474             } else {
03475               _cur_grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur_grffile->grfid, id, lang, new_scheme, name, STR_UNDEFINED);
03476             }
03477             break;
03478 
03479           case 0xD0:
03480           case 0xD1:
03481           case 0xD2:
03482           case 0xD3:
03483           case 0xDC:
03484             AddGRFString(_cur_grffile->grfid, id, lang, new_scheme, name, STR_UNDEFINED);
03485             break;
03486 
03487           default:
03488             grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
03489             break;
03490         }
03491         break;
03492 
03493 #if 0
03494         case GSF_CANAL :
03495         case GSF_BRIDGE :
03496           AddGRFString(_cur_spriteid, id, lang, name);
03497           switch (GB(id, 8, 8)) {
03498             case 0xC9: // House name
03499             default:
03500               grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
03501           }
03502           break;
03503 
03504         default :
03505           grfmsg(7, "FeatureNewName: Unsupported feature (0x%02X)", feature);
03506           break;
03507 #endif
03508     }
03509   }
03510 }
03511 
03520 static uint16 SanitizeSpriteOffset(uint16& num, uint16 offset, int max_sprites, const char *name)
03521 {
03522 
03523   if (offset >= max_sprites) {
03524     grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
03525     uint orig_num = num;
03526     num = 0;
03527     return orig_num;
03528   }
03529 
03530   if (offset + num > max_sprites) {
03531     grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
03532     uint orig_num = num;
03533     num = max(max_sprites - offset, 0);
03534     return orig_num - num;
03535   }
03536 
03537   return 0;
03538 }
03539 
03540 /* Action 0x05 */
03541 static void GraphicsNew(byte *buf, size_t len)
03542 {
03543   /* <05> <graphics-type> <num-sprites> <other data...>
03544    *
03545    * B graphics-type What set of graphics the sprites define.
03546    * E num-sprites   How many sprites are in this set?
03547    * V other data    Graphics type specific data.  Currently unused. */
03548   /* TODO */
03549 
03550   enum Action5BlockType {
03551     A5BLOCK_FIXED,                
03552     A5BLOCK_ALLOW_OFFSET,         
03553     A5BLOCK_INVALID,              
03554   };
03555   struct Action5Type {
03556     Action5BlockType block_type;  
03557     SpriteID sprite_base;         
03558     uint16 min_sprites;           
03559     uint16 max_sprites;           
03560     const char *name;             
03561   };
03562 
03563   static const Action5Type action5_types[] = {
03564     /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
03565     /* 0x00 */ { A5BLOCK_INVALID,      0,                            0, 0,                                           "Type 0x00"             },
03566     /* 0x01 */ { A5BLOCK_INVALID,      0,                            0, 0,                                           "Type 0x01"             },
03567     /* 0x02 */ { A5BLOCK_INVALID,      0,                            0, 0,                                           "Type 0x02"             },
03568     /* 0x03 */ { A5BLOCK_INVALID,      0,                            0, 0,                                           "Type 0x03"             },
03569     /* 0x04 */ { A5BLOCK_FIXED,        SPR_SIGNALS_BASE,            48, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT,    "Signal graphics"       },
03570     /* 0x05 */ { A5BLOCK_FIXED,        SPR_ELRAIL_BASE,             48, ELRAIL_SPRITE_COUNT,                         "Catenary graphics"     },
03571     /* 0x06 */ { A5BLOCK_FIXED,        SPR_SLOPES_BASE,             74, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics"   },
03572     /* 0x07 */ { A5BLOCK_INVALID,      0,                           75, 0,                                           "TTDP GUI graphics"     }, // Not used by OTTD.
03573     /* 0x08 */ { A5BLOCK_FIXED,        SPR_CANALS_BASE,             65, CANALS_SPRITE_COUNT,                         "Canal graphics"        },
03574     /* 0x09 */ { A5BLOCK_FIXED,        SPR_ONEWAY_BASE,              6, ONEWAY_SPRITE_COUNT,                         "One way road graphics" },
03575     /* 0x0A */ { A5BLOCK_FIXED,        SPR_2CCMAP_BASE,            256, TWOCCMAP_SPRITE_COUNT,                       "2CC colour maps"       },
03576     /* 0x0B */ { A5BLOCK_FIXED,        SPR_TRAMWAY_BASE,           113, TRAMWAY_SPRITE_COUNT,                        "Tramway graphics"      },
03577     /* 0x0C */ { A5BLOCK_INVALID,      0,                          133, 0,                                           "Snowy temperate tree"  }, // Not yet used by OTTD.
03578     /* 0x0D */ { A5BLOCK_FIXED,        SPR_SHORE_BASE,              16, SPR_SHORE_SPRITE_COUNT,                      "Shore graphics"        },
03579     /* 0x0E */ { A5BLOCK_INVALID,      0,                            0, 0,                                           "New Signals graphics"  }, // Not yet used by OTTD.
03580     /* 0x0F */ { A5BLOCK_FIXED,        SPR_TRACKS_FOR_SLOPES_BASE,  12, TRACKS_FOR_SLOPES_SPRITE_COUNT,              "Sloped rail track"     },
03581     /* 0x10 */ { A5BLOCK_FIXED,        SPR_AIRPORTX_BASE,           15, AIRPORTX_SPRITE_COUNT,                       "Airport graphics"      },
03582     /* 0x11 */ { A5BLOCK_FIXED,        SPR_ROADSTOP_BASE,            8, ROADSTOP_SPRITE_COUNT,                       "Road stop graphics"    },
03583     /* 0x12 */ { A5BLOCK_FIXED,        SPR_AQUEDUCT_BASE,            8, AQUEDUCT_SPRITE_COUNT,                       "Aqueduct graphics"     },
03584     /* 0x13 */ { A5BLOCK_FIXED,        SPR_AUTORAIL_BASE,           55, AUTORAIL_SPRITE_COUNT,                       "Autorail graphics"     },
03585     /* 0x14 */ { A5BLOCK_ALLOW_OFFSET, SPR_FLAGS_BASE,               1, FLAGS_SPRITE_COUNT,                          "Flag graphics"         },
03586     /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE,             1, OPENTTD_SPRITE_COUNT,                        "OpenTTD GUI graphics"  },
03587   };
03588 
03589   if (!check_length(len, 2, "GraphicsNew")) return;
03590   buf++;
03591   uint8 type = grf_load_byte(&buf);
03592   uint16 num = grf_load_extended(&buf);
03593   uint16 offset = HasBit(type, 7) ? grf_load_extended(&buf) : 0;
03594   ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
03595 
03596   if ((type == 0x0D) && (num == 10) && _cur_grffile->is_ottdfile) {
03597     /* Special not-TTDP-compatible case used in openttd(d/w).grf
03598      * Missing shore sprites and initialisation of SPR_SHORE_BASE */
03599     grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from openttd(d/w).grf.");
03600     LoadNextSprite(SPR_SHORE_BASE +  0, _file_index, _nfo_line++); // SLOPE_STEEP_S
03601     LoadNextSprite(SPR_SHORE_BASE +  5, _file_index, _nfo_line++); // SLOPE_STEEP_W
03602     LoadNextSprite(SPR_SHORE_BASE +  7, _file_index, _nfo_line++); // SLOPE_WSE
03603     LoadNextSprite(SPR_SHORE_BASE + 10, _file_index, _nfo_line++); // SLOPE_STEEP_N
03604     LoadNextSprite(SPR_SHORE_BASE + 11, _file_index, _nfo_line++); // SLOPE_NWS
03605     LoadNextSprite(SPR_SHORE_BASE + 13, _file_index, _nfo_line++); // SLOPE_ENW
03606     LoadNextSprite(SPR_SHORE_BASE + 14, _file_index, _nfo_line++); // SLOPE_SEN
03607     LoadNextSprite(SPR_SHORE_BASE + 15, _file_index, _nfo_line++); // SLOPE_STEEP_E
03608     LoadNextSprite(SPR_SHORE_BASE + 16, _file_index, _nfo_line++); // SLOPE_EW
03609     LoadNextSprite(SPR_SHORE_BASE + 17, _file_index, _nfo_line++); // SLOPE_NS
03610     if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
03611     return;
03612   }
03613 
03614   /* Supported type? */
03615   if ((type >= lengthof(action5_types)) || (action5_types[type].block_type == A5BLOCK_INVALID)) {
03616     grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
03617     _skip_sprites = num;
03618     return;
03619   }
03620 
03621   const Action5Type *action5_type = &action5_types[type];
03622 
03623   /* Ignore offset if not allowed */
03624   if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
03625     grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
03626     offset = 0;
03627   }
03628 
03629   /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
03630    * This does not make sense, if <offset> is allowed */
03631   if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
03632     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);
03633     _skip_sprites = num;
03634     return;
03635   }
03636 
03637   /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extentions) */
03638   uint16 skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
03639   SpriteID replace = action5_type->sprite_base + offset;
03640 
03641   /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
03642   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);
03643 
03644   for (; num > 0; num--) {
03645     _nfo_line++;
03646     LoadNextSprite(replace == 0 ? _cur_spriteid++ : replace++, _file_index, _nfo_line);
03647   }
03648 
03649   if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
03650 
03651   _skip_sprites = skip_num;
03652 }
03653 
03654 /* Action 0x05 (SKIP) */
03655 static void SkipAct5(byte *buf, size_t len)
03656 {
03657   if (!check_length(len, 2, "SkipAct5")) return;
03658   buf++;
03659 
03660   /* Ignore type byte */
03661   grf_load_byte(&buf);
03662 
03663   /* Skip the sprites of this action */
03664   _skip_sprites = grf_load_extended(&buf);
03665 
03666   grfmsg(3, "SkipAct5: Skipping %d sprites", _skip_sprites);
03667 }
03668 
03679 bool GetGlobalVariable(byte param, uint32 *value)
03680 {
03681   switch (param) {
03682     case 0x00: // current date
03683       *value = max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
03684       return true;
03685 
03686     case 0x01: // current year
03687       *value = Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
03688       return true;
03689 
03690     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)
03691       YearMonthDay ymd;
03692       ConvertDateToYMD(_date, &ymd);
03693       Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1);
03694       *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16;
03695       return true;
03696     }
03697 
03698     case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
03699       *value = _settings_game.game_creation.landscape;
03700       return true;
03701 
03702     case 0x06: // road traffic side, bit 4 clear=left, set=right
03703       *value = _settings_game.vehicle.road_side << 4;
03704       return true;
03705 
03706     case 0x09: // date fraction
03707       *value = _date_fract;
03708       return true;
03709 
03710     case 0x0A: // animation counter
03711       *value = _tick_counter;
03712       return true;
03713 
03714     case 0x0B: { // TTDPatch version
03715       uint major    = 2;
03716       uint minor    = 6;
03717       uint revision = 1; // special case: 2.0.1 is 2.0.10
03718       uint build    = 1382;
03719       *value = (major << 24) | (minor << 20) | (revision << 16) | build;
03720       return true;
03721     }
03722 
03723     case 0x0D: // TTD Version, 00=DOS, 01=Windows
03724       *value = _cur_grfconfig->windows_paletted;
03725       return true;
03726 
03727     case 0x0E: // Y-offset for train sprites
03728       *value = _traininfo_vehicle_pitch;
03729       return true;
03730 
03731     case 0x0F: // Rail track type cost factors
03732       *value = 0;
03733       SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
03734       if (_settings_game.vehicle.disable_elrails) {
03735         /* skip elrail multiplier - disabled */
03736         SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
03737       } else {
03738         SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
03739         /* Skip monorail multiplier - no space in result */
03740       }
03741       SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
03742       return true;
03743 
03744     case 0x11: // current rail tool type
03745       *value = 0;
03746       return true;
03747 
03748     case 0x12: // Game mode
03749       *value = _game_mode;
03750       return true;
03751 
03752     /* case 0x13: // Tile refresh offset to left    not implemented */
03753     /* case 0x14: // Tile refresh offset to right   not implemented */
03754     /* case 0x15: // Tile refresh offset upwards    not implemented */
03755     /* case 0x16: // Tile refresh offset downwards  not implemented */
03756     /* case 0x17: // temperate snow line            not implemented */
03757 
03758     case 0x1A: // Always -1
03759       *value = UINT_MAX;
03760       return true;
03761 
03762     case 0x1B: // Display options
03763       *value = GB(_display_opt, 0, 6);
03764       return true;
03765 
03766     case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
03767       *value = 1;
03768       return true;
03769 
03770     case 0x1E: // Miscellaneous GRF features
03771       *value = _misc_grf_features;
03772       return true;
03773 
03774     /* case 0x1F: // locale dependent settings not implemented */
03775 
03776     case 0x20: // snow line height
03777       *value = _settings_game.game_creation.landscape == LT_ARCTIC ? GetSnowLine() : 0xFF;
03778       return true;
03779 
03780     case 0x21: // OpenTTD version
03781       *value = _openttd_newgrf_version;
03782       return true;
03783 
03784     case 0x22: // difficulty level
03785       *value = _settings_game.difficulty.diff_level;
03786       return true;
03787 
03788     case 0x23: // long format date
03789       *value = _date;
03790       return true;
03791 
03792     case 0x24: // long format year
03793       *value = _cur_year;
03794       return true;
03795 
03796     default: return false;
03797   }
03798 }
03799 
03800 static uint32 GetParamVal(byte param, uint32 *cond_val)
03801 {
03802   /* First handle variable common with VarAction2 */
03803   uint32 value;
03804   if (GetGlobalVariable(param - 0x80, &value)) return value;
03805 
03806   /* Non-common variable */
03807   switch (param) {
03808     case 0x84: { // GRF loading stage
03809       uint32 res = 0;
03810 
03811       if (_cur_stage > GLS_INIT) SetBit(res, 0);
03812       if (_cur_stage == GLS_RESERVE) SetBit(res, 8);
03813       if (_cur_stage == GLS_ACTIVATION) SetBit(res, 9);
03814       return res;
03815     }
03816 
03817     case 0x85: // TTDPatch flags, only for bit tests
03818       if (cond_val == NULL) {
03819         /* Supported in Action 0x07 and 0x09, not 0x0D */
03820         return 0;
03821       } else {
03822         uint32 param_val = _ttdpatch_flags[*cond_val / 0x20];
03823         *cond_val %= 0x20;
03824         return param_val;
03825       }
03826 
03827     case 0x88: // GRF ID check
03828       return 0;
03829 
03830     /* case 0x99: Global ID offest not implemented */
03831 
03832     default:
03833       /* GRF Parameter */
03834       if (param < 0x80) return _cur_grffile->param[param];
03835 
03836       /* In-game variable. */
03837       grfmsg(1, "Unsupported in-game variable 0x%02X", param);
03838       return UINT_MAX;
03839   }
03840 }
03841 
03842 /* Action 0x06 */
03843 static void CfgApply(byte *buf, size_t len)
03844 {
03845   /* <06> <param-num> <param-size> <offset> ... <FF>
03846    *
03847    * B param-num     Number of parameter to substitute (First = "zero")
03848    *                 Ignored if that parameter was not specified in newgrf.cfg
03849    * B param-size    How many bytes to replace.  If larger than 4, the
03850    *                 bytes of the following parameter are used.  In that
03851    *                 case, nothing is applied unless *all* parameters
03852    *                 were specified.
03853    * B offset        Offset into data from beginning of next sprite
03854    *                 to place where parameter is to be stored. */
03855 
03856   /* Preload the next sprite */
03857   size_t pos = FioGetPos();
03858   uint16 num = FioReadWord();
03859   uint8 type = FioReadByte();
03860   byte *preload_sprite = NULL;
03861 
03862   /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
03863   if (type == 0xFF) {
03864     preload_sprite = MallocT<byte>(num);
03865     FioReadBlock(preload_sprite, num);
03866   }
03867 
03868   /* Reset the file position to the start of the next sprite */
03869   FioSeekTo(pos, SEEK_SET);
03870 
03871   if (type != 0xFF) {
03872     grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
03873     free(preload_sprite);
03874     return;
03875   }
03876 
03877   GRFLocation location(_cur_grfconfig->grfid, _nfo_line + 1);
03878   GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
03879   if (it != _grf_line_to_action6_sprite_override.end()) {
03880     free(preload_sprite);
03881     preload_sprite = _grf_line_to_action6_sprite_override[location];
03882   } else {
03883     _grf_line_to_action6_sprite_override[location] = preload_sprite;
03884   }
03885 
03886   /* Now perform the Action 0x06 on our data. */
03887   buf++;
03888 
03889   for (;;) {
03890     uint i;
03891     uint param_num;
03892     uint param_size;
03893     uint offset;
03894     bool add_value;
03895 
03896     /* Read the parameter to apply. 0xFF indicates no more data to change. */
03897     param_num = grf_load_byte(&buf);
03898     if (param_num == 0xFF) break;
03899 
03900     /* Get the size of the parameter to use. If the size covers multiple
03901      * double words, sequential parameter values are used. */
03902     param_size = grf_load_byte(&buf);
03903 
03904     /* Bit 7 of param_size indicates we should add to the original value
03905      * instead of replacing it. */
03906     add_value  = HasBit(param_size, 7);
03907     param_size = GB(param_size, 0, 7);
03908 
03909     /* Where to apply the data to within the pseudo sprite data. */
03910     offset     = grf_load_extended(&buf);
03911 
03912     /* If the parameter is a GRF parameter (not an internal variable) check
03913      * if it (and all further sequential parameters) has been defined. */
03914     if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur_grffile->param_end) {
03915       grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
03916       break;
03917     }
03918 
03919     grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
03920 
03921     bool carry = false;
03922     for (i = 0; i < param_size && offset + i < num; i++) {
03923       uint32 value = GetParamVal(param_num + i / 4, NULL);
03924       /* Reset carry flag for each iteration of the variable (only really
03925        * matters if param_size is greater than 4) */
03926       if (i == 0) carry = false;
03927 
03928       if (add_value) {
03929         uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
03930         preload_sprite[offset + i] = GB(new_value, 0, 8);
03931         /* Check if the addition overflowed */
03932         carry = new_value >= 256;
03933       } else {
03934         preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
03935       }
03936     }
03937   }
03938 }
03939 
03949 static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
03950 {
03951   if (c->error != NULL) {
03952     free(c->error->custom_message);
03953     free(c->error->data);
03954     free(c->error);
03955   }
03956   c->status = GCS_DISABLED;
03957   c->error  = CallocT<GRFError>(1);
03958   c->error->data = strdup(_cur_grfconfig->name);
03959   c->error->severity = STR_NEWGRF_ERROR_MSG_FATAL;
03960   c->error->message  = STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC;
03961 
03962   ClearTemporaryNewGRFData(GetFileByGRFID(c->grfid));
03963 }
03964 
03965 /* Action 0x07 */
03966 /* Action 0x09 */
03967 static void SkipIf(byte *buf, size_t len)
03968 {
03969   /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
03970    *
03971    * B param-num
03972    * B param-size
03973    * B condition-type
03974    * V value
03975    * B num-sprites */
03976   /* TODO: More params. More condition types. */
03977   uint32 cond_val = 0;
03978   uint32 mask = 0;
03979   bool result;
03980 
03981   if (!check_length(len, 6, "SkipIf")) return;
03982   buf++;
03983   uint8 param     = grf_load_byte(&buf);
03984   uint8 paramsize = grf_load_byte(&buf);
03985   uint8 condtype  = grf_load_byte(&buf);
03986 
03987   if (condtype < 2) {
03988     /* Always 1 for bit tests, the given value should be ignored. */
03989     paramsize = 1;
03990   }
03991 
03992   switch (paramsize) {
03993     case 8: cond_val = grf_load_dword(&buf); mask = grf_load_dword(&buf); break;
03994     case 4: cond_val = grf_load_dword(&buf); mask = 0xFFFFFFFF; break;
03995     case 2: cond_val = grf_load_word(&buf);  mask = 0x0000FFFF; break;
03996     case 1: cond_val = grf_load_byte(&buf);  mask = 0x000000FF; break;
03997     default: break;
03998   }
03999 
04000   if (param < 0x80 && _cur_grffile->param_end <= param) {
04001     grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
04002     return;
04003   }
04004 
04005   uint32 param_val = GetParamVal(param, &cond_val);
04006 
04007   grfmsg(7, "SkipIf: Test condtype %d, param 0x%08X, condval 0x%08X", condtype, param_val, cond_val);
04008 
04009   /*
04010    * Parameter (variable in specs) 0x88 can only have GRF ID checking
04011    * conditions, except conditions 0x0B and 0x0C (cargo availability)
04012    * as those ignore the parameter. So, when the condition type is
04013    * either of those, the specific variable 0x88 code is skipped, so
04014    * the "general" code for the cargo availability conditions kicks in.
04015    */
04016   if (param == 0x88 && condtype != 0x0B && condtype != 0x0C) {
04017     /* GRF ID checks */
04018 
04019     GRFConfig *c = GetGRFConfig(cond_val, mask);
04020 
04021     if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur_grfconfig->flags, GCF_STATIC) && c->status != GCS_DISABLED && _networking) {
04022       DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
04023       c = NULL;
04024     }
04025 
04026     if (condtype != 10 && c == NULL) {
04027       grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
04028       return;
04029     }
04030 
04031     switch (condtype) {
04032       /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
04033       case 0x06: // Is GRFID active?
04034         result = c->status == GCS_ACTIVATED;
04035         break;
04036 
04037       case 0x07: // Is GRFID non-active?
04038         result = c->status != GCS_ACTIVATED;
04039         break;
04040 
04041       case 0x08: // GRFID is not but will be active?
04042         result = c->status == GCS_INITIALISED;
04043         break;
04044 
04045       case 0x09: // GRFID is or will be active?
04046         result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
04047         break;
04048 
04049       case 0x0A: // GRFID is not nor will be active
04050         /* This is the only condtype that doesn't get ignored if the GRFID is not found */
04051         result = c == NULL || c->flags == GCS_DISABLED || c->status == GCS_NOT_FOUND;
04052         break;
04053 
04054       default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
04055     }
04056   } else {
04057     /* Parameter or variable tests */
04058     switch (condtype) {
04059       case 0x00: result = !!(param_val & (1 << cond_val));
04060         break;
04061       case 0x01: result = !(param_val & (1 << cond_val));
04062         break;
04063       case 0x02: result = (param_val & mask) == cond_val;
04064         break;
04065       case 0x03: result = (param_val & mask) != cond_val;
04066         break;
04067       case 0x04: result = (param_val & mask) < cond_val;
04068         break;
04069       case 0x05: result = (param_val & mask) > cond_val;
04070         break;
04071       case 0x0B: result = GetCargoIDByLabel(BSWAP32(cond_val)) == CT_INVALID;
04072         break;
04073       case 0x0C: result = GetCargoIDByLabel(BSWAP32(cond_val)) != CT_INVALID;
04074         break;
04075       case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
04076         break;
04077       case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
04078         break;
04079 
04080       default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
04081     }
04082   }
04083 
04084   if (!result) {
04085     grfmsg(2, "SkipIf: Not skipping sprites, test was false");
04086     return;
04087   }
04088 
04089   uint8 numsprites = grf_load_byte(&buf);
04090 
04091   /* numsprites can be a GOTO label if it has been defined in the GRF
04092    * file. The jump will always be the first matching label that follows
04093    * the current nfo_line. If no matching label is found, the first matching
04094    * label in the file is used. */
04095   GRFLabel *choice = NULL;
04096   for (GRFLabel *label = _cur_grffile->label; label != NULL; label = label->next) {
04097     if (label->label != numsprites) continue;
04098 
04099     /* Remember a goto before the current line */
04100     if (choice == NULL) choice = label;
04101     /* If we find a label here, this is definitely good */
04102     if (label->nfo_line > _nfo_line) {
04103       choice = label;
04104       break;
04105     }
04106   }
04107 
04108   if (choice != NULL) {
04109     grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
04110     FioSeekTo(choice->pos, SEEK_SET);
04111     _nfo_line = choice->nfo_line;
04112     return;
04113   }
04114 
04115   grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
04116   _skip_sprites = numsprites;
04117   if (_skip_sprites == 0) {
04118     /* Zero means there are no sprites to skip, so
04119      * we use -1 to indicate that all further
04120      * sprites should be skipped. */
04121     _skip_sprites = -1;
04122 
04123     /* If an action 8 hasn't been encountered yet, disable the grf. */
04124     if (_cur_grfconfig->status != GCS_ACTIVATED) {
04125       _cur_grfconfig->status = GCS_DISABLED;
04126       ClearTemporaryNewGRFData(_cur_grffile);
04127     }
04128   }
04129 }
04130 
04131 
04132 /* Action 0x08 (GLS_FILESCAN) */
04133 static void ScanInfo(byte *buf, size_t len)
04134 {
04135   if (!check_length(len, 8, "Info")) return;
04136   buf++;
04137   grf_load_byte(&buf);
04138   uint32 grfid  = grf_load_dword(&buf);
04139 
04140   _cur_grfconfig->grfid = grfid;
04141 
04142   /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
04143   if (GB(grfid, 24, 8) == 0xFF) SetBit(_cur_grfconfig->flags, GCF_SYSTEM);
04144 
04145   len -= 6;
04146   const char *name = grf_load_string(&buf, len);
04147   _cur_grfconfig->name = TranslateTTDPatchCodes(grfid, name);
04148 
04149   len -= strlen(name) + 1;
04150   if (len > 0) {
04151     const char *info = grf_load_string(&buf, len);
04152     _cur_grfconfig->info = TranslateTTDPatchCodes(grfid, info);
04153   }
04154 
04155   /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
04156   _skip_sprites = -1;
04157 }
04158 
04159 /* Action 0x08 */
04160 static void GRFInfo(byte *buf, size_t len)
04161 {
04162   /* <08> <version> <grf-id> <name> <info>
04163    *
04164    * B version       newgrf version, currently 06
04165    * 4*B grf-id      globally unique ID of this .grf file
04166    * S name          name of this .grf set
04167    * S info          string describing the set, and e.g. author and copyright */
04168 
04169   if (!check_length(len, 8, "GRFInfo")) return;
04170   buf++;
04171   uint8 version    = grf_load_byte(&buf);
04172   uint32 grfid     = grf_load_dword(&buf);
04173   const char *name = grf_load_string(&buf, len - 6);
04174 
04175   if (_cur_stage < GLS_RESERVE && _cur_grfconfig->status != GCS_UNKNOWN) {
04176     _cur_grfconfig->status = GCS_DISABLED;
04177     _cur_grfconfig->error  = CallocT<GRFError>(1);
04178     _cur_grfconfig->error->severity = STR_NEWGRF_ERROR_MSG_FATAL;
04179     _cur_grfconfig->error->message  = STR_NEWGRF_ERROR_MULTIPLE_ACTION_8;
04180 
04181     _skip_sprites = -1;
04182     return;
04183   }
04184 
04185   _cur_grffile->grfid = grfid;
04186   _cur_grffile->grf_version = version;
04187   _cur_grfconfig->status = _cur_stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
04188 
04189   /* Do swap the GRFID for displaying purposes since people expect that */
04190   DEBUG(grf, 1, "GRFInfo: Loaded GRFv%d set %08lX - %s (palette: %s)", version, BSWAP32(grfid), name, _cur_grfconfig->windows_paletted ? "Windows" : "DOS");
04191 }
04192 
04193 /* Action 0x0A */
04194 static void SpriteReplace(byte *buf, size_t len)
04195 {
04196   /* <0A> <num-sets> <set1> [<set2> ...]
04197    * <set>: <num-sprites> <first-sprite>
04198    *
04199    * B num-sets      How many sets of sprites to replace.
04200    * Each set:
04201    * B num-sprites   How many sprites are in this set
04202    * W first-sprite  First sprite number to replace */
04203 
04204   buf++; // skip action byte
04205   uint8 num_sets = grf_load_byte(&buf);
04206 
04207   for (uint i = 0; i < num_sets; i++) {
04208     uint8 num_sprites = grf_load_byte(&buf);
04209     uint16 first_sprite = grf_load_word(&buf);
04210 
04211     grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
04212       i, num_sprites, first_sprite
04213     );
04214 
04215     for (uint j = 0; j < num_sprites; j++) {
04216       int load_index = first_sprite + j;
04217       _nfo_line++;
04218       LoadNextSprite(load_index, _file_index, _nfo_line); // XXX
04219 
04220       /* Shore sprites now located at different addresses.
04221        * So detect when the old ones get replaced. */
04222       if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
04223         if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
04224       }
04225     }
04226   }
04227 }
04228 
04229 /* Action 0x0A (SKIP) */
04230 static void SkipActA(byte *buf, size_t len)
04231 {
04232   buf++;
04233   uint8 num_sets = grf_load_byte(&buf);
04234 
04235   for (uint i = 0; i < num_sets; i++) {
04236     /* Skip the sprites this replaces */
04237     _skip_sprites += grf_load_byte(&buf);
04238     /* But ignore where they go */
04239     grf_load_word(&buf);
04240   }
04241 
04242   grfmsg(3, "SkipActA: Skipping %d sprites", _skip_sprites);
04243 }
04244 
04245 /* Action 0x0B */
04246 static void GRFLoadError(byte *buf, size_t len)
04247 {
04248   /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
04249    *
04250    * B severity      00: notice, contine loading grf file
04251    *                 01: warning, continue loading grf file
04252    *                 02: error, but continue loading grf file, and attempt
04253    *                     loading grf again when loading or starting next game
04254    *                 03: error, abort loading and prevent loading again in
04255    *                     the future (only when restarting the patch)
04256    * B language-id   see action 4, use 1F for built-in error messages
04257    * B message-id    message to show, see below
04258    * S message       for custom messages (message-id FF), text of the message
04259    *                 not present for built-in messages.
04260    * V data          additional data for built-in (or custom) messages
04261    * B parnum        parameter numbers to be shown in the message (maximum of 2) */
04262 
04263   static const StringID msgstr[] = {
04264     STR_NEWGRF_ERROR_VERSION_NUMBER,
04265     STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
04266     STR_NEWGRF_ERROR_UNSET_SWITCH,
04267     STR_NEWGRF_ERROR_INVALID_PARAMETER,
04268     STR_NEWGRF_ERROR_LOAD_BEFORE,
04269     STR_NEWGRF_ERROR_LOAD_AFTER,
04270     STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
04271   };
04272 
04273   static const StringID sevstr[] = {
04274     STR_NEWGRF_ERROR_MSG_INFO,
04275     STR_NEWGRF_ERROR_MSG_WARNING,
04276     STR_NEWGRF_ERROR_MSG_ERROR,
04277     STR_NEWGRF_ERROR_MSG_FATAL
04278   };
04279 
04280   if (!check_length(len, 6, "GRFLoadError")) return;
04281 
04282   /* For now we can only show one message per newgrf file. */
04283   if (_cur_grfconfig->error != NULL) return;
04284 
04285   buf++; // Skip the action byte.
04286   byte severity   = grf_load_byte(&buf);
04287   byte lang       = grf_load_byte(&buf);
04288   byte message_id = grf_load_byte(&buf);
04289   len -= 4;
04290 
04291   /* Skip the error if it isn't valid for the current language. */
04292   if (!CheckGrfLangID(lang, _cur_grffile->grf_version)) return;
04293 
04294   /* Skip the error until the activation stage unless bit 7 of the severity
04295    * is set. */
04296   if (!HasBit(severity, 7) && _cur_stage == GLS_INIT) {
04297     grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur_stage);
04298     return;
04299   }
04300   ClrBit(severity, 7);
04301 
04302   if (severity >= lengthof(sevstr)) {
04303     grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
04304     severity = 2;
04305   } else if (severity == 3) {
04306     /* This is a fatal error, so make sure the GRF is deactivated and no
04307      * more of it gets loaded. */
04308     _cur_grfconfig->status = GCS_DISABLED;
04309     ClearTemporaryNewGRFData(_cur_grffile);
04310     _skip_sprites = -1;
04311   }
04312 
04313   if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
04314     grfmsg(7, "GRFLoadError: Invalid message id.");
04315     return;
04316   }
04317 
04318   if (len <= 1) {
04319     grfmsg(7, "GRFLoadError: No message data supplied.");
04320     return;
04321   }
04322 
04323   GRFError *error = CallocT<GRFError>(1);
04324 
04325   error->severity = sevstr[severity];
04326 
04327   if (message_id == 0xFF) {
04328     /* This is a custom error message. */
04329     const char *message = grf_load_string(&buf, len);
04330     len -= (strlen(message) + 1);
04331 
04332     error->custom_message = TranslateTTDPatchCodes(_cur_grffile->grfid, message);
04333   } else {
04334     error->message = msgstr[message_id];
04335   }
04336 
04337   if (len > 0) {
04338     const char *data = grf_load_string(&buf, len);
04339     len -= (strlen(data) + 1);
04340 
04341     error->data = TranslateTTDPatchCodes(_cur_grffile->grfid, data);
04342   }
04343 
04344   /* Only two parameter numbers can be used in the string. */
04345   uint i = 0;
04346   for (; i < 2 && len > 0; i++) {
04347     error->param_number[i] = grf_load_byte(&buf);
04348     len--;
04349   }
04350   error->num_params = i;
04351 
04352   _cur_grfconfig->error = error;
04353 }
04354 
04355 /* Action 0x0C */
04356 static void GRFComment(byte *buf, size_t len)
04357 {
04358   /* <0C> [<ignored...>]
04359    *
04360    * V ignored       Anything following the 0C is ignored */
04361 
04362   if (len == 1) return;
04363 
04364   size_t text_len = len - 1;
04365   const char *text = (const char*)(buf + 1);
04366   grfmsg(2, "GRFComment: %.*s", text_len, text);
04367 }
04368 
04369 /* Action 0x0D (GLS_SAFETYSCAN) */
04370 static void SafeParamSet(byte *buf, size_t len)
04371 {
04372   if (!check_length(len, 5, "SafeParamSet")) return;
04373   buf++;
04374   uint8 target = grf_load_byte(&buf);
04375 
04376   /* Only writing GRF parameters is considered safe */
04377   if (target < 0x80) return;
04378 
04379   /* GRM could be unsafe, but as here it can only happen after other GRFs
04380    * are loaded, it should be okay. If the GRF tried to use the slots it
04381    * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
04382    * sprites  is considered safe. */
04383 
04384   SetBit(_cur_grfconfig->flags, GCF_UNSAFE);
04385 
04386   /* Skip remainder of GRF */
04387   _skip_sprites = -1;
04388 }
04389 
04390 
04391 static uint32 GetPatchVariable(uint8 param)
04392 {
04393   switch (param) {
04394     /* start year - 1920 */
04395     case 0x0B: return max(_settings_game.game_creation.starting_year, ORIGINAL_BASE_YEAR) - ORIGINAL_BASE_YEAR;
04396 
04397     /* freight trains weight factor */
04398     case 0x0E: return _settings_game.vehicle.freight_trains;
04399 
04400     /* empty wagon speed increase */
04401     case 0x0F: return 0;
04402 
04403     /* plane speed factor; our patch option is reversed from TTDPatch's,
04404      * the following is good for 1x, 2x and 4x (most common?) and...
04405      * well not really for 3x. */
04406     case 0x10:
04407       switch (_settings_game.vehicle.plane_speed) {
04408         default:
04409         case 4: return 1;
04410         case 3: return 2;
04411         case 2: return 2;
04412         case 1: return 4;
04413       }
04414 
04415 
04416     /* 2CC colourmap base sprite */
04417     case 0x11: return SPR_2CCMAP_BASE;
04418 
04419     /* map size: format = -MABXYSS
04420      * M  : the type of map
04421      *       bit 0 : set   : squared map. Bit 1 is now not relevant
04422      *               clear : rectangle map. Bit 1 will indicate the bigger edge of the map
04423      *       bit 1 : set   : Y is the bigger edge. Bit 0 is clear
04424      *               clear : X is the bigger edge.
04425      * A  : minimum edge(log2) of the map
04426      * B  : maximum edge(log2) of the map
04427      * XY : edges(log2) of each side of the map.
04428      * SS : combination of both X and Y, thus giving the size(log2) of the map
04429      */
04430     case 0x13: {
04431       byte map_bits = 0;
04432       byte log_X = MapLogX() - 6; // substraction is required to make the minimal size (64) zero based
04433       byte log_Y = MapLogY() - 6;
04434       byte max_edge = max(log_X, log_Y);
04435 
04436       if (log_X == log_Y) { // we have a squared map, since both edges are identical
04437         SetBit(map_bits ,0);
04438       } else {
04439         if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
04440       }
04441 
04442       return (map_bits << 24) | (min(log_X, log_Y) << 20) | (max_edge << 16) |
04443         (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
04444     }
04445 
04446     default:
04447       grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
04448       return 0;
04449   }
04450 }
04451 
04452 
04453 static uint32 PerformGRM(uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
04454 {
04455   uint start = 0;
04456   uint size  = 0;
04457 
04458   if (op == 6) {
04459     /* Return GRFID of set that reserved ID */
04460     return grm[_cur_grffile->param[target]];
04461   }
04462 
04463   /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
04464   if (op == 2 || op == 3) start = _cur_grffile->param[target];
04465 
04466   for (uint i = start; i < num_ids; i++) {
04467     if (grm[i] == 0) {
04468       size++;
04469     } else {
04470       if (op == 2 || op == 3) break;
04471       start = i + 1;
04472       size = 0;
04473     }
04474 
04475     if (size == count) break;
04476   }
04477 
04478   if (size == count) {
04479     /* Got the slot... */
04480     if (op == 0 || op == 3) {
04481       grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
04482       for (uint i = 0; i < count; i++) grm[start + i] = _cur_grffile->grfid;
04483     }
04484     return start;
04485   }
04486 
04487   /* Unable to allocate */
04488   if (op != 4 && op != 5) {
04489     /* Deactivate GRF */
04490     grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
04491     _cur_grfconfig->status = GCS_DISABLED;
04492     ClearTemporaryNewGRFData(_cur_grffile);
04493     _skip_sprites = -1;
04494     return UINT_MAX;
04495   }
04496 
04497   grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
04498   return UINT_MAX;
04499 }
04500 
04501 
04502 /* Action 0x0D */
04503 static void ParamSet(byte *buf, size_t len)
04504 {
04505   /* <0D> <target> <operation> <source1> <source2> [<data>]
04506    *
04507    * B target        parameter number where result is stored
04508    * B operation     operation to perform, see below
04509    * B source1       first source operand
04510    * B source2       second source operand
04511    * D data          data to use in the calculation, not necessary
04512    *                 if both source1 and source2 refer to actual parameters
04513    *
04514    * Operations
04515    * 00      Set parameter equal to source1
04516    * 01      Addition, source1 + source2
04517    * 02      Subtraction, source1 - source2
04518    * 03      Unsigned multiplication, source1 * source2 (both unsigned)
04519    * 04      Signed multiplication, source1 * source2 (both signed)
04520    * 05      Unsigned bit shift, source1 by source2 (source2 taken to be a
04521    *         signed quantity; left shift if positive and right shift if
04522    *         negative, source1 is unsigned)
04523    * 06      Signed bit shift, source1 by source2
04524    *         (source2 like in 05, and source1 as well)
04525    */
04526 
04527   if (!check_length(len, 5, "ParamSet")) return;
04528   buf++;
04529   uint8 target = grf_load_byte(&buf);
04530   uint8 oper   = grf_load_byte(&buf);
04531   uint32 src1  = grf_load_byte(&buf);
04532   uint32 src2  = grf_load_byte(&buf);
04533 
04534   uint32 data = 0;
04535   if (len >= 8) data = grf_load_dword(&buf);
04536 
04537   /* You can add 80 to the operation to make it apply only if the target
04538    * is not defined yet.  In this respect, a parameter is taken to be
04539    * defined if any of the following applies:
04540    * - it has been set to any value in the newgrf(w).cfg parameter list
04541    * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
04542    *   an earlier action D */
04543   if (HasBit(oper, 7)) {
04544     if (target < 0x80 && target < _cur_grffile->param_end) {
04545       grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
04546       return;
04547     }
04548 
04549     oper = GB(oper, 0, 7);
04550   }
04551 
04552   if (src2 == 0xFE) {
04553     if (GB(data, 0, 8) == 0xFF) {
04554       if (data == 0x0000FFFF) {
04555         /* Patch variables */
04556         src1 = GetPatchVariable(src1);
04557       } else {
04558         /* GRF Resource Management */
04559         uint8  op      = src1;
04560         uint8  feature = GB(data, 8, 8);
04561         uint16 count   = GB(data, 16, 16);
04562 
04563         if (_cur_stage == GLS_RESERVE) {
04564           if (feature == 0x08) {
04565             /* General sprites */
04566             if (op == 0) {
04567               /* Check if the allocated sprites will fit below the original sprite limit */
04568               if (_cur_spriteid + count >= 16384) {
04569                 grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
04570                 _cur_grfconfig->status = GCS_DISABLED;
04571                 ClearTemporaryNewGRFData(_cur_grffile);
04572                 _skip_sprites = -1;
04573                 return;
04574               }
04575 
04576               /* Reserve space at the current sprite ID */
04577               grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur_spriteid);
04578               _grm_sprites[GRFLocation(_cur_grffile->grfid, _nfo_line)] = _cur_spriteid;
04579               _cur_spriteid += count;
04580             }
04581           }
04582           /* Ignore GRM result during reservation */
04583           src1 = 0;
04584         } else if (_cur_stage == GLS_ACTIVATION) {
04585           switch (feature) {
04586             case 0x00: // Trains
04587             case 0x01: // Road Vehicles
04588             case 0x02: // Ships
04589             case 0x03: // Aircraft
04590               if (!_settings_game.vehicle.dynamic_engines) {
04591                 src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
04592                 if (_skip_sprites == -1) return;
04593               } else {
04594                 // GRM does not apply for dynamic engine allocation.
04595                 switch (op) {
04596                   case 2:
04597                   case 3:
04598                     src1 = _cur_grffile->param[target];
04599                     break;
04600 
04601                   default:
04602                     src1 = 0;
04603                     break;
04604                 }
04605               }
04606               break;
04607 
04608             case 0x08: // General sprites
04609               switch (op) {
04610                 case 0:
04611                   /* Return space reserved during reservation stage */
04612                   src1 = _grm_sprites[GRFLocation(_cur_grffile->grfid, _nfo_line)];
04613                   grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
04614                   break;
04615 
04616                 case 1:
04617                   src1 = _cur_spriteid;
04618                   break;
04619 
04620                 default:
04621                   grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
04622                   return;
04623               }
04624               break;
04625 
04626             case 0x0B: // Cargo
04627               /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
04628               src1 = PerformGRM(_grm_cargos, NUM_CARGO * 2, count, op, target, "cargos");
04629               if (_skip_sprites == -1) return;
04630               break;
04631 
04632             default: grfmsg(1, "ParamSet: GRM: Unsupported feature 0x%X", feature); return;
04633           }
04634         } else {
04635           /* Ignore GRM during initialization */
04636           src1 = 0;
04637         }
04638       }
04639     } else {
04640       /* Read another GRF File's parameter */
04641       const GRFFile *file = GetFileByGRFID(data);
04642       GRFConfig *c = GetGRFConfig(data);
04643       if (c != NULL && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur_grfconfig->flags, GCF_STATIC) && _networking) {
04644         /* Disable the read GRF if it is a static NewGRF. */
04645         DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
04646         src1 = 0;
04647       } else if (file == NULL || src1 >= file->param_end || (c != NULL && c->status == GCS_DISABLED)) {
04648         src1 = 0;
04649       } else {
04650         src1 = file->param[src1];
04651       }
04652     }
04653   } else {
04654     /* The source1 and source2 operands refer to the grf parameter number
04655      * like in action 6 and 7.  In addition, they can refer to the special
04656      * variables available in action 7, or they can be FF to use the value
04657      * of <data>.  If referring to parameters that are undefined, a value
04658      * of 0 is used instead.  */
04659     src1 = (src1 == 0xFF) ? data : GetParamVal(src1, NULL);
04660     src2 = (src2 == 0xFF) ? data : GetParamVal(src2, NULL);
04661   }
04662 
04663   /* TODO: You can access the parameters of another GRF file by using
04664    * source2=FE, source1=the other GRF's parameter number and data=GRF
04665    * ID.  This is only valid with operation 00 (set).  If the GRF ID
04666    * cannot be found, a value of 0 is used for the parameter value
04667    * instead. */
04668 
04669   uint32 res;
04670   switch (oper) {
04671     case 0x00:
04672       res = src1;
04673       break;
04674 
04675     case 0x01:
04676       res = src1 + src2;
04677       break;
04678 
04679     case 0x02:
04680       res = src1 - src2;
04681       break;
04682 
04683     case 0x03:
04684       res = src1 * src2;
04685       break;
04686 
04687     case 0x04:
04688       res = (int32)src1 * (int32)src2;
04689       break;
04690 
04691     case 0x05:
04692       if ((int32)src2 < 0) {
04693         res = src1 >> -(int32)src2;
04694       } else {
04695         res = src1 << src2;
04696       }
04697       break;
04698 
04699     case 0x06:
04700       if ((int32)src2 < 0) {
04701         res = (int32)src1 >> -(int32)src2;
04702       } else {
04703         res = (int32)src1 << src2;
04704       }
04705       break;
04706 
04707     case 0x07: // Bitwise AND
04708       res = src1 & src2;
04709       break;
04710 
04711     case 0x08: // Bitwise OR
04712       res = src1 | src2;
04713       break;
04714 
04715     case 0x09: // Unsigned division
04716       if (src2 == 0) {
04717         res = src1;
04718       } else {
04719         res = src1 / src2;
04720       }
04721       break;
04722 
04723     case 0x0A: // Signed divison
04724       if (src2 == 0) {
04725         res = src1;
04726       } else {
04727         res = (int32)src1 / (int32)src2;
04728       }
04729       break;
04730 
04731     case 0x0B: // Unsigned modulo
04732       if (src2 == 0) {
04733         res = src1;
04734       } else {
04735         res = src1 % src2;
04736       }
04737       break;
04738 
04739     case 0x0C: // Signed modulo
04740       if (src2 == 0) {
04741         res = src1;
04742       } else {
04743         res = (int32)src1 % (int32)src2;
04744       }
04745       break;
04746 
04747     default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
04748   }
04749 
04750   switch (target) {
04751     case 0x8E: // Y-Offset for train sprites
04752       _traininfo_vehicle_pitch = res;
04753       break;
04754 
04755     case 0x8F: { // Rail track type cost factors
04756       extern RailtypeInfo _railtypes[RAILTYPE_END];
04757       _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
04758       if (_settings_game.vehicle.disable_elrails) {
04759         _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
04760         _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
04761       } else {
04762         _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
04763         _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
04764       }
04765       _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
04766       break;
04767     }
04768 
04769     /* @todo implement */
04770     case 0x93: // Tile refresh offset to left
04771     case 0x94: // Tile refresh offset to right
04772     case 0x95: // Tile refresh offset upwards
04773     case 0x96: // Tile refresh offset downwards
04774     case 0x97: // Snow line height
04775     case 0x99: // Global ID offset
04776       grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
04777       break;
04778 
04779     case 0x9E: // Miscellaneous GRF features
04780       _misc_grf_features = res;
04781       /* Set train list engine width */
04782       _traininfo_vehicle_width = HasGrfMiscBit(GMB_TRAIN_WIDTH_32_PIXELS) ? 32 : 29;
04783       break;
04784 
04785     case 0x9F: // locale-dependent settings
04786       grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
04787       break;
04788 
04789     default:
04790       if (target < 0x80) {
04791         _cur_grffile->param[target] = res;
04792         if (target + 1U > _cur_grffile->param_end) _cur_grffile->param_end = target + 1;
04793       } else {
04794         grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
04795       }
04796       break;
04797   }
04798 }
04799 
04800 /* Action 0x0E (GLS_SAFETYSCAN) */
04801 static void SafeGRFInhibit(byte *buf, size_t len)
04802 {
04803   /* <0E> <num> <grfids...>
04804    *
04805    * B num           Number of GRFIDs that follow
04806    * D grfids        GRFIDs of the files to deactivate */
04807 
04808   if (!check_length(len, 2, "GRFInhibit")) return;
04809   buf++;
04810   uint8 num = grf_load_byte(&buf);
04811   if (!check_length(len, 2 + 4 * num, "GRFInhibit")) return;
04812 
04813   for (uint i = 0; i < num; i++) {
04814     uint32 grfid = grf_load_dword(&buf);
04815 
04816     /* GRF is unsafe it if tries to deactivate other GRFs */
04817     if (grfid != _cur_grfconfig->grfid) {
04818       SetBit(_cur_grfconfig->flags, GCF_UNSAFE);
04819 
04820       /* Skip remainder of GRF */
04821       _skip_sprites = -1;
04822 
04823       return;
04824     }
04825   }
04826 }
04827 
04828 /* Action 0x0E */
04829 static void GRFInhibit(byte *buf, size_t len)
04830 {
04831   /* <0E> <num> <grfids...>
04832    *
04833    * B num           Number of GRFIDs that follow
04834    * D grfids        GRFIDs of the files to deactivate */
04835 
04836   if (!check_length(len, 2, "GRFInhibit")) return;
04837   buf++;
04838   uint8 num = grf_load_byte(&buf);
04839   if (!check_length(len, 2 + 4 * num, "GRFInhibit")) return;
04840 
04841   for (uint i = 0; i < num; i++) {
04842     uint32 grfid = grf_load_dword(&buf);
04843     GRFConfig *file = GetGRFConfig(grfid);
04844 
04845     /* Unset activation flag */
04846     if (file != NULL && file != _cur_grfconfig) {
04847       grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
04848       file->status = GCS_DISABLED;
04849     }
04850   }
04851 }
04852 
04853 /* Action 0x0F */
04854 static void FeatureTownName(byte *buf, size_t len)
04855 {
04856   /* <0F> <id> <style-name> <num-parts> <parts>
04857    *
04858    * B id          ID of this definition in bottom 7 bits (final definition if bit 7 set)
04859    * V style-name  Name of the style (only for final definition)
04860    * B num-parts   Number of parts in this definition
04861    * V parts       The parts */
04862 
04863   if (!check_length(len, 1, "FeatureTownName: definition ID")) return;
04864   buf++; len--;
04865 
04866   uint32 grfid = _cur_grffile->grfid;
04867 
04868   GRFTownName *townname = AddGRFTownName(grfid);
04869 
04870   byte id = grf_load_byte(&buf);
04871   len--;
04872   grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
04873 
04874   if (HasBit(id, 7)) {
04875     /* Final definition */
04876     ClrBit(id, 7);
04877     bool new_scheme = _cur_grffile->grf_version >= 7;
04878 
04879     if (!check_length(len, 1, "FeatureTownName: lang_id")) return;
04880     byte lang = grf_load_byte(&buf);
04881     len--;
04882 
04883     byte nb_gen = townname->nb_gen;
04884     do {
04885       ClrBit(lang, 7);
04886 
04887       if (!check_length(len, 1, "FeatureTownName: style name")) return;
04888       const char *name = grf_load_string(&buf, len);
04889       len -= strlen(name) + 1;
04890 
04891       char *lang_name = TranslateTTDPatchCodes(grfid, name);
04892       grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name);
04893       free(lang_name);
04894 
04895       townname->name[nb_gen] = AddGRFString(grfid, id, lang, new_scheme, name, STR_UNDEFINED);
04896 
04897       if (!check_length(len, 1, "FeatureTownName: lang_id")) return;
04898       lang = grf_load_byte(&buf);
04899       len--;
04900     } while (lang != 0);
04901     townname->id[nb_gen] = id;
04902     townname->nb_gen++;
04903   }
04904 
04905   if (!check_length(len, 1, "FeatureTownName: number of parts")) return;
04906   byte nb = grf_load_byte(&buf);
04907   len--;
04908   grfmsg(6, "FeatureTownName: %d parts", nb, nb);
04909 
04910   townname->nbparts[id] = nb;
04911   townname->partlist[id] = CallocT<NamePartList>(nb);
04912 
04913   for (int i = 0; i < nb; i++) {
04914     if (!check_length(len, 3, "FeatureTownName: parts header")) return;
04915     byte nbtext =  grf_load_byte(&buf);
04916     townname->partlist[id][i].bitstart  = grf_load_byte(&buf);
04917     townname->partlist[id][i].bitcount  = grf_load_byte(&buf);
04918     townname->partlist[id][i].maxprob   = 0;
04919     townname->partlist[id][i].partcount = nbtext;
04920     townname->partlist[id][i].parts     = CallocT<NamePart>(nbtext);
04921     len -= 3;
04922     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);
04923 
04924     for (int j = 0; j < nbtext; j++) {
04925       if (!check_length(len, 2, "FeatureTownName: part")) return;
04926       byte prob = grf_load_byte(&buf);
04927       len--;
04928 
04929       if (HasBit(prob, 7)) {
04930         byte ref_id = grf_load_byte(&buf);
04931         len--;
04932 
04933         if (townname->nbparts[ref_id] == 0) {
04934           grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
04935           DelGRFTownName(grfid);
04936           _cur_grfconfig->status = GCS_DISABLED;
04937           ClearTemporaryNewGRFData(_cur_grffile);
04938           _skip_sprites = -1;
04939           return;
04940         }
04941 
04942         grfmsg(6, "FeatureTownName: part %d, text %d, uses intermediate definition 0x%02X (with probability %d)", i, j, ref_id, prob & 0x7F);
04943         townname->partlist[id][i].parts[j].data.id = ref_id;
04944       } else {
04945         const char *text = grf_load_string(&buf, len);
04946         len -= strlen(text) + 1;
04947         townname->partlist[id][i].parts[j].data.text = TranslateTTDPatchCodes(grfid, text);
04948         grfmsg(6, "FeatureTownName: part %d, text %d, '%s' (with probability %d)", i, j, townname->partlist[id][i].parts[j].data.text, prob);
04949       }
04950       townname->partlist[id][i].parts[j].prob = prob;
04951       townname->partlist[id][i].maxprob += GB(prob, 0, 7);
04952     }
04953     grfmsg(6, "FeatureTownName: part %d, total probability %d", i, townname->partlist[id][i].maxprob);
04954   }
04955 }
04956 
04957 /* Action 0x10 */
04958 static void DefineGotoLabel(byte *buf, size_t len)
04959 {
04960   /* <10> <label> [<comment>]
04961    *
04962    * B label      The label to define
04963    * V comment    Optional comment - ignored */
04964 
04965   if (!check_length(len, 1, "DefineGotoLabel")) return;
04966   buf++; len--;
04967 
04968   GRFLabel *label = MallocT<GRFLabel>(1);
04969   label->label    = grf_load_byte(&buf);
04970   label->nfo_line = _nfo_line;
04971   label->pos      = FioGetPos();
04972   label->next     = NULL;
04973 
04974   /* Set up a linked list of goto targets which we will search in an Action 0x7/0x9 */
04975   if (_cur_grffile->label == NULL) {
04976     _cur_grffile->label = label;
04977   } else {
04978     /* Attach the label to the end of the list */
04979     GRFLabel *l;
04980     for (l = _cur_grffile->label; l->next != NULL; l = l->next) {}
04981     l->next = label;
04982   }
04983 
04984   grfmsg(2, "DefineGotoLabel: GOTO target with label 0x%02X", label->label);
04985 }
04986 
04987 /* Action 0x11 */
04988 static void GRFSound(byte *buf, size_t len)
04989 {
04990   /* <11> <num>
04991    *
04992    * W num      Number of sound files that follow */
04993 
04994   if (!check_length(len, 1, "GRFSound")) return;
04995   buf++;
04996   uint16 num = grf_load_word(&buf);
04997 
04998   _grf_data_blocks = num;
04999   _grf_data_type   = GDT_SOUND;
05000 
05001   if (_cur_grffile->sound_offset == 0) _cur_grffile->sound_offset = GetNumSounds();
05002 }
05003 
05004 /* Action 0x11 (SKIP) */
05005 static void SkipAct11(byte *buf, size_t len)
05006 {
05007   /* <11> <num>
05008    *
05009    * W num      Number of sound files that follow */
05010 
05011   if (!check_length(len, 1, "SkipAct11")) return;
05012   buf++;
05013   _skip_sprites = grf_load_word(&buf);
05014 
05015   grfmsg(3, "SkipAct11: Skipping %d sprites", _skip_sprites);
05016 }
05017 
05018 static void ImportGRFSound(byte *buf, int len)
05019 {
05020   const GRFFile *file;
05021   FileEntry *se = AllocateFileEntry();
05022   uint32 grfid = grf_load_dword(&buf);
05023   uint16 sound = grf_load_word(&buf);
05024 
05025   file = GetFileByGRFID(grfid);
05026   if (file == NULL || file->sound_offset == 0) {
05027     grfmsg(1, "ImportGRFSound: Source file not available");
05028     return;
05029   }
05030 
05031   if (file->sound_offset + sound >= GetNumSounds()) {
05032     grfmsg(1, "ImportGRFSound: Sound effect %d is invalid", sound);
05033     return;
05034   }
05035 
05036   grfmsg(2, "ImportGRFSound: Copying sound %d (%d) from file %X", sound, file->sound_offset + sound, grfid);
05037 
05038   *se = *GetSound(file->sound_offset + sound);
05039 
05040   /* Reset volume and priority, which TTDPatch doesn't copy */
05041   se->volume   = 128;
05042   se->priority = 0;
05043 }
05044 
05045 /* 'Action 0xFE' */
05046 static void GRFImportBlock(byte *buf, int len)
05047 {
05048   if (_grf_data_blocks == 0) {
05049     grfmsg(2, "GRFImportBlock: Unexpected import block, skipping");
05050     return;
05051   }
05052 
05053   buf++;
05054 
05055   _grf_data_blocks--;
05056 
05057   /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
05058    * importing sounds, so this is probably all wrong... */
05059   if (grf_load_byte(&buf) != _grf_data_type) {
05060     grfmsg(1, "GRFImportBlock: Import type mismatch");
05061   }
05062 
05063   switch (_grf_data_type) {
05064     case GDT_SOUND: ImportGRFSound(buf, len - 1); break;
05065     default: NOT_REACHED(); break;
05066   }
05067 }
05068 
05069 static void LoadGRFSound(byte *buf, int len)
05070 {
05071   byte *buf_start = buf;
05072 
05073   /* Allocate a sound entry. This is done even if the data is not loaded
05074    * so that the indices used elsewhere are still correct. */
05075   FileEntry *se = AllocateFileEntry();
05076 
05077   if (grf_load_dword(&buf) != BSWAP32('RIFF')) {
05078     grfmsg(1, "LoadGRFSound: Missing RIFF header");
05079     return;
05080   }
05081 
05082   /* Size of file -- we ignore this */
05083   grf_load_dword(&buf);
05084 
05085   if (grf_load_dword(&buf) != BSWAP32('WAVE')) {
05086     grfmsg(1, "LoadGRFSound: Invalid RIFF type");
05087     return;
05088   }
05089 
05090   for (;;) {
05091     uint32 tag  = grf_load_dword(&buf);
05092     uint32 size = grf_load_dword(&buf);
05093 
05094     switch (tag) {
05095       case ' tmf': // 'fmt '
05096         /* Audio format, must be 1 (PCM) */
05097         if (grf_load_word(&buf) != 1) {
05098           grfmsg(1, "LoadGRFSound: Invalid audio format");
05099           return;
05100         }
05101         se->channels = grf_load_word(&buf);
05102         se->rate = grf_load_dword(&buf);
05103         grf_load_dword(&buf);
05104         grf_load_word(&buf);
05105         se->bits_per_sample = grf_load_word(&buf);
05106 
05107         /* Consume any extra bytes */
05108         for (; size > 16; size--) grf_load_byte(&buf);
05109         break;
05110 
05111       case 'atad': // 'data'
05112         se->file_size   = size;
05113         se->file_offset = FioGetPos() - (len - (buf - buf_start)) + 1;
05114         se->file_slot   = _file_index;
05115 
05116         /* Set default volume and priority */
05117         se->volume = 0x80;
05118         se->priority = 0;
05119 
05120         grfmsg(2, "LoadGRFSound: channels %u, sample rate %u, bits per sample %u, length %u", se->channels, se->rate, se->bits_per_sample, size);
05121         return;
05122 
05123       default:
05124         se->file_size = 0;
05125         return;
05126     }
05127   }
05128 }
05129 
05130 /* Action 0x12 */
05131 static void LoadFontGlyph(byte *buf, size_t len)
05132 {
05133   /* <12> <num_def> <font_size> <num_char> <base_char>
05134    *
05135    * B num_def      Number of definitions
05136    * B font_size    Size of font (0 = normal, 1 = small, 2 = large)
05137    * B num_char     Number of consecutive glyphs
05138    * W base_char    First character index */
05139 
05140   buf++; len--;
05141   if (!check_length(len, 1, "LoadFontGlyph")) return;
05142 
05143   uint8 num_def = grf_load_byte(&buf);
05144 
05145   if (!check_length(len, 1 + num_def * 4, "LoadFontGlyph")) return;
05146 
05147   for (uint i = 0; i < num_def; i++) {
05148     FontSize size    = (FontSize)grf_load_byte(&buf);
05149     uint8  num_char  = grf_load_byte(&buf);
05150     uint16 base_char = grf_load_word(&buf);
05151 
05152     grfmsg(7, "LoadFontGlyph: Loading %u glyph(s) at 0x%04X for size %u", num_char, base_char, size);
05153 
05154     for (uint c = 0; c < num_char; c++) {
05155       SetUnicodeGlyph(size, base_char + c, _cur_spriteid);
05156       _nfo_line++;
05157       LoadNextSprite(_cur_spriteid++, _file_index, _nfo_line);
05158     }
05159   }
05160 }
05161 
05162 /* Action 0x12 (SKIP) */
05163 static void SkipAct12(byte *buf, size_t len)
05164 {
05165   /* <12> <num_def> <font_size> <num_char> <base_char>
05166    *
05167    * B num_def      Number of definitions
05168    * B font_size    Size of font (0 = normal, 1 = small, 2 = large)
05169    * B num_char     Number of consecutive glyphs
05170    * W base_char    First character index */
05171 
05172   buf++; len--;
05173   if (!check_length(len, 1, "SkipAct12")) return;
05174   uint8 num_def = grf_load_byte(&buf);
05175 
05176   if (!check_length(len, 1 + num_def * 4, "SkipAct12")) return;
05177 
05178   for (uint i = 0; i < num_def; i++) {
05179     /* Ignore 'size' byte */
05180     grf_load_byte(&buf);
05181 
05182     /* Sum up number of characters */
05183     _skip_sprites += grf_load_byte(&buf);
05184 
05185     /* Ignore 'base_char' word */
05186     grf_load_word(&buf);
05187   }
05188 
05189   grfmsg(3, "SkipAct12: Skipping %d sprites", _skip_sprites);
05190 }
05191 
05192 /* Action 0x13 */
05193 static void TranslateGRFStrings(byte *buf, size_t len)
05194 {
05195   /* <13> <grfid> <num-ent> <offset> <text...>
05196    *
05197    * 4*B grfid     The GRFID of the file whose texts are to be translated
05198    * B   num-ent   Number of strings
05199    * W   offset    First text ID
05200    * S   text...   Zero-terminated strings */
05201 
05202   buf++; len--;
05203   if (!check_length(len, 7, "TranslateGRFString")) return;
05204 
05205   uint32 grfid = grf_load_dword(&buf);
05206   const GRFConfig *c = GetGRFConfig(grfid);
05207   if (c == NULL || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
05208     grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
05209     return;
05210   }
05211 
05212   if (c->status == GCS_INITIALISED) {
05213     /* If the file is not active but will be activated later, give an error
05214      * and disable this file. */
05215     GRFError *error = CallocT<GRFError>(1);
05216 
05217     char tmp[256];
05218     GetString(tmp, STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE, lastof(tmp));
05219     error->data = strdup(tmp);
05220 
05221     error->message  = STR_NEWGRF_ERROR_LOAD_AFTER;
05222     error->severity = STR_NEWGRF_ERROR_MSG_FATAL;
05223 
05224     if (_cur_grfconfig->error != NULL) free(_cur_grfconfig->error);
05225     _cur_grfconfig->error = error;
05226 
05227     _cur_grfconfig->status = GCS_DISABLED;
05228     ClearTemporaryNewGRFData(_cur_grffile);
05229     _skip_sprites = -1;
05230     return;
05231   }
05232 
05233   byte num_strings = grf_load_byte(&buf);
05234   uint16 first_id  = grf_load_word(&buf);
05235 
05236   if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD3FF) || (first_id >= 0xDC00 && first_id + num_strings <= 0xDCFF))) {
05237     grfmsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x%4X, number: 0x%2X)", first_id, num_strings);
05238     return;
05239   }
05240 
05241   len -= 7;
05242 
05243   for (uint i = 0; i < num_strings && len > 0; i++) {
05244     const char *string   = grf_load_string(&buf, len);
05245     size_t string_length = strlen(string) + 1;
05246 
05247     len -= (int)string_length;
05248 
05249     if (string_length == 1) {
05250       grfmsg(7, "TranslateGRFString: Ignoring empty string.");
05251       continue;
05252     }
05253 
05254     /* Since no language id is supplied this string has to be added as a
05255      * generic string, thus the language id of 0x7F. For this to work
05256      * new_scheme has to be true as well. A language id of 0x7F will be
05257      * overridden by a non-generic id, so this will not change anything if
05258      * a string has been provided specifically for this language. */
05259     AddGRFString(grfid, first_id + i, 0x7F, true, string, STR_UNDEFINED);
05260   }
05261 }
05262 
05263 /* 'Action 0xFF' */
05264 static void GRFDataBlock(byte *buf, int len)
05265 {
05266   if (_grf_data_blocks == 0) {
05267     grfmsg(2, "GRFDataBlock: unexpected data block, skipping");
05268     return;
05269   }
05270 
05271   buf++;
05272   uint8 name_len = grf_load_byte(&buf);
05273   const char *name = (const char *)buf;
05274   buf += name_len + 1;
05275 
05276   grfmsg(2, "GRFDataBlock: block name '%s'...", name);
05277 
05278   _grf_data_blocks--;
05279 
05280   switch (_grf_data_type) {
05281     case GDT_SOUND: LoadGRFSound(buf, len - name_len - 2); break;
05282     default: NOT_REACHED(); break;
05283   }
05284 }
05285 
05286 
05287 /* Used during safety scan on unsafe actions */
05288 static void GRFUnsafe(byte *buf, size_t len)
05289 {
05290   SetBit(_cur_grfconfig->flags, GCF_UNSAFE);
05291 
05292   /* Skip remainder of GRF */
05293   _skip_sprites = -1;
05294 }
05295 
05296 
05297 static void InitializeGRFSpecial()
05298 {
05299   _ttdpatch_flags[0] =  ((_settings_game.station.always_small_airport ? 1 : 0) << 0x0C)  // keepsmallairport
05300                      |                                                 (1 << 0x0D)  // newairports
05301                      |                                                 (1 << 0x0E)  // largestations
05302                      |      ((_settings_game.construction.longbridges ? 1 : 0) << 0x0F)  // longbridges
05303                      |                                                 (0 << 0x10)  // loadtime
05304                      |                                                 (1 << 0x12)  // presignals
05305                      |                                                 (1 << 0x13)  // extpresignals
05306                      | ((_settings_game.vehicle.never_expire_vehicles ? 1 : 0) << 0x16)  // enginespersist
05307                      |                                                 (1 << 0x1B)  // multihead
05308                      |                                                 (1 << 0x1D)  // lowmemory
05309                      |                                                 (1 << 0x1E); // generalfixes
05310 
05311   _ttdpatch_flags[1] =   ((_settings_game.economy.station_noise_level ? 1 : 0) << 0x07)  // moreairports - based on units of noise
05312                      |        ((_settings_game.vehicle.mammoth_trains ? 1 : 0) << 0x08)  // mammothtrains
05313                      |                                                 (1 << 0x09)  // trainrefit
05314                      |                                                 (0 << 0x0B)  // subsidiaries
05315                      |         ((_settings_game.order.gradual_loading ? 1 : 0) << 0x0C)  // gradualloading
05316                      |                                                 (1 << 0x12)  // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
05317                      |                                                 (1 << 0x13)  // unifiedmaglevmode - set bit 1 mode
05318                      |                                                 (1 << 0x14)  // bridgespeedlimits
05319                      |                                                 (1 << 0x16)  // eternalgame
05320                      |                                                 (1 << 0x17)  // newtrains
05321                      |                                                 (1 << 0x18)  // newrvs
05322                      |                                                 (1 << 0x19)  // newships
05323                      |                                                 (1 << 0x1A)  // newplanes
05324                      |      ((_settings_game.construction.signal_side ? 1 : 0) << 0x1B)  // signalsontrafficside
05325                      |       ((_settings_game.vehicle.disable_elrails ? 0 : 1) << 0x1C); // electrifiedrailway
05326 
05327   _ttdpatch_flags[2] =                                                 (1 << 0x01)  // loadallgraphics - obsolote
05328                      |                                                 (1 << 0x03)  // semaphores
05329                      |                                                 (0 << 0x0B)  // enhancedgui
05330                      |                                                 (0 << 0x0C)  // newagerating
05331                      |  ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x0D)  // buildonslopes
05332                      |                                                 (1 << 0x0E)  // fullloadany
05333                      |                                                 (1 << 0x0F)  // planespeed
05334                      |                                                 (0 << 0x10)  // moreindustriesperclimate - obsolete
05335                      |                                                 (0 << 0x11)  // moretoylandfeatures
05336                      |                                                 (1 << 0x12)  // newstations
05337                      |                                                 (1 << 0x13)  // tracktypecostdiff
05338                      |                                                 (1 << 0x14)  // manualconvert
05339                      |  ((_settings_game.construction.build_on_slopes ? 1 : 0) << 0x15)  // buildoncoasts
05340                      |                                                 (1 << 0x16)  // canals
05341                      |                                                 (1 << 0x17)  // newstartyear
05342                      |    ((_settings_game.vehicle.freight_trains > 1 ? 1 : 0) << 0x18)  // freighttrains
05343                      |                                                 (1 << 0x19)  // newhouses
05344                      |                                                 (1 << 0x1A)  // newbridges
05345                      |                                                 (1 << 0x1B)  // newtownnames
05346                      |                                                 (1 << 0x1C)  // moreanimation
05347                      |    ((_settings_game.vehicle.wagon_speed_limits ? 1 : 0) << 0x1D)  // wagonspeedlimits
05348                      |                                                 (1 << 0x1E)  // newshistory
05349                      |                                                 (0 << 0x1F); // custombridgeheads
05350 
05351   _ttdpatch_flags[3] =                                                 (0 << 0x00)  // newcargodistribution
05352                      |                                                 (1 << 0x01)  // windowsnap
05353                      | ((_settings_game.economy.allow_town_roads || _generating_world ? 0 : 1) << 0x02)  // townbuildnoroad
05354                      |                                                 (1 << 0x03)  // pathbasedsignalling
05355                      |                                                 (0 << 0x04)  // aichoosechance
05356                      |                                                 (1 << 0x05)  // resolutionwidth
05357                      |                                                 (1 << 0x06)  // resolutionheight
05358                      |                                                 (1 << 0x07)  // newindustries
05359                      |           ((_settings_game.order.improved_load ? 1 : 0) << 0x08)  // fifoloading
05360                      |                                                 (0 << 0x09)  // townroadbranchprob
05361                      |                                                 (0 << 0x0A)  // tempsnowline
05362                      |                                                 (1 << 0x0B)  // newcargo
05363                      |                                                 (1 << 0x0C)  // enhancemultiplayer
05364                      |                                                 (1 << 0x0D)  // onewayroads
05365                      |   ((_settings_game.station.nonuniform_stations ? 1 : 0) << 0x0E)  // irregularstations
05366                      |                                                 (1 << 0x0F)  // statistics
05367                      |                                                 (1 << 0x10)  // newsounds
05368                      |                                                 (1 << 0x11)  // autoreplace
05369                      |                                                 (1 << 0x12)  // autoslope
05370                      |                                                 (0 << 0x13)  // followvehicle
05371                      |                                                 (1 << 0x14)  // trams
05372                      |                                                 (0 << 0x15)  // enhancetunnels
05373                      |                                                 (1 << 0x16)  // shortrvs
05374                      |                                                 (1 << 0x17)  // articulatedrvs
05375                      |       ((_settings_game.vehicle.dynamic_engines ? 1 : 0) << 0x18)  // dynamic engines
05376                      |                                                 (1 << 0x1E)  // variablerunningcosts
05377                      |                                                 (1 << 0x1F); // any switch is on
05378 }
05379 
05380 static void ResetCustomStations()
05381 {
05382   for (GRFFile *file = _first_grffile; file != NULL; file = file->next) {
05383     if (file->stations == NULL) continue;
05384     for (uint i = 0; i < MAX_STATIONS; i++) {
05385       if (file->stations[i] == NULL) continue;
05386       StationSpec *statspec = file->stations[i];
05387 
05388       /* Release renderdata, if it wasn't copied from another custom station spec  */
05389       if (!statspec->copied_renderdata) {
05390         for (uint t = 0; t < statspec->tiles; t++) {
05391           free((void*)statspec->renderdata[t].seq);
05392         }
05393         free(statspec->renderdata);
05394       }
05395 
05396       /* Release platforms and layouts */
05397       if (!statspec->copied_layouts) {
05398         for (uint l = 0; l < statspec->lengths; l++) {
05399           for (uint p = 0; p < statspec->platforms[l]; p++) {
05400             free(statspec->layouts[l][p]);
05401           }
05402           free(statspec->layouts[l]);
05403         }
05404         free(statspec->layouts);
05405         free(statspec->platforms);
05406       }
05407 
05408       /* Release this station */
05409       free(statspec);
05410     }
05411 
05412     /* Free and reset the station data */
05413     free(file->stations);
05414     file->stations = NULL;
05415   }
05416 }
05417 
05418 static void ResetCustomHouses()
05419 {
05420   GRFFile *file;
05421   uint i;
05422 
05423   for (file = _first_grffile; file != NULL; file = file->next) {
05424     if (file->housespec == NULL) continue;
05425     for (i = 0; i < HOUSE_MAX; i++) {
05426       free(file->housespec[i]);
05427     }
05428 
05429     free(file->housespec);
05430     file->housespec = NULL;
05431   }
05432 }
05433 
05434 static void ResetCustomIndustries()
05435 {
05436   GRFFile *file;
05437 
05438   for (file = _first_grffile; file != NULL; file = file->next) {
05439     uint i;
05440     /* We are verifiying both tiles and industries specs loaded from the grf file
05441      * First, let's deal with industryspec */
05442     if (file->industryspec != NULL) {
05443 
05444       for (i = 0; i < NUM_INDUSTRYTYPES; i++) {
05445         IndustrySpec *ind = file->industryspec[i];
05446 
05447         if (ind != NULL) {
05448           /* We need to remove the sounds array */
05449           if (HasBit(ind->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
05450             free((void*)ind->random_sounds);
05451           }
05452 
05453           /* We need to remove the tiles layouts */
05454           if (HasBit(ind->cleanup_flag, CLEAN_TILELSAYOUT) && ind->table != NULL) {
05455             for (int j = 0; j < ind->num_table; j++) {
05456               /* remove the individual layouts */
05457               if (ind->table[j] != NULL) {
05458                 free((IndustryTileTable*)ind->table[j]);
05459               }
05460             }
05461             /* remove the layouts pointers */
05462             free((IndustryTileTable**)ind->table);
05463             ind->table = NULL;
05464           }
05465 
05466           free(ind);
05467           ind = NULL;
05468         }
05469       }
05470 
05471       free(file->industryspec);
05472       file->industryspec = NULL;
05473     }
05474 
05475     if (file->indtspec != NULL) {
05476       for (i = 0; i < NUM_INDUSTRYTILES; i++) {
05477         if (file->indtspec[i] != NULL) {
05478           free(file->indtspec[i]);
05479           file->indtspec[i] = NULL;
05480         }
05481       }
05482 
05483       free(file->indtspec);
05484       file->indtspec = NULL;
05485     }
05486   }
05487 }
05488 
05489 static void ResetNewGRF()
05490 {
05491   GRFFile *next;
05492 
05493   for (GRFFile *f = _first_grffile; f != NULL; f = next) {
05494     next = f->next;
05495 
05496     free(f->filename);
05497     free(f->cargo_list);
05498     free(f->railtype_list);
05499     free(f);
05500   }
05501 
05502   _first_grffile = NULL;
05503   _cur_grffile   = NULL;
05504 }
05505 
05506 static void ResetNewGRFErrors()
05507 {
05508   for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
05509     if (!HasBit(c->flags, GCF_COPY) && c->error != NULL) {
05510       free(c->error->custom_message);
05511       free(c->error->data);
05512       free(c->error);
05513       c->error = NULL;
05514     }
05515   }
05516 }
05517 
05522 static void ResetNewGRFData()
05523 {
05524   CleanUpStrings();
05525   CleanUpGRFTownNames();
05526 
05527   /* Copy/reset original engine info data */
05528   SetupEngines();
05529 
05530   /* Copy/reset original bridge info data */
05531   ResetBridges();
05532 
05533   /* Reset rail type information */
05534   ResetRailTypes();
05535 
05536   /* Allocate temporary refit/cargo class data */
05537   _gted = CallocT<GRFTempEngineData>(GetEnginePoolSize());
05538 
05539   /* Reset GRM reservations */
05540   memset(&_grm_engines, 0, sizeof(_grm_engines));
05541   memset(&_grm_cargos, 0, sizeof(_grm_cargos));
05542 
05543   /* Reset generic feature callback lists */
05544   ResetGenericCallbacks();
05545 
05546   /* Reset price base data */
05547   ResetPriceBaseMultipliers();
05548 
05549   /* Reset the curencies array */
05550   ResetCurrencies();
05551 
05552   /* Reset the house array */
05553   ResetCustomHouses();
05554   ResetHouses();
05555 
05556   /* Reset the industries structures*/
05557   ResetCustomIndustries();
05558   ResetIndustries();
05559 
05560   /* Reset station classes */
05561   ResetStationClasses();
05562   ResetCustomStations();
05563 
05564   /* Reset canal sprite groups and flags */
05565   memset(_water_feature, 0, sizeof(_water_feature));
05566 
05567   /* Reset the snowline table. */
05568   ClearSnowLine();
05569 
05570   /* Reset NewGRF files */
05571   ResetNewGRF();
05572 
05573   /* Reset NewGRF errors. */
05574   ResetNewGRFErrors();
05575 
05576   /* Set up the default cargo types */
05577   SetupCargoForClimate(_settings_game.game_creation.landscape);
05578 
05579   /* Reset misc GRF features and train list display variables */
05580   _misc_grf_features = 0;
05581   _traininfo_vehicle_pitch = 0;
05582   _traininfo_vehicle_width = 29;
05583 
05584   _loaded_newgrf_features.has_2CC           = false;
05585   _loaded_newgrf_features.has_newhouses     = false;
05586   _loaded_newgrf_features.has_newindustries = false;
05587   _loaded_newgrf_features.shore             = SHORE_REPLACE_NONE;
05588 
05589   /* Clear all GRF overrides */
05590   _grf_id_overrides.clear();
05591 
05592   InitializeSoundPool();
05593   InitializeSpriteGroupPool();
05594 }
05595 
05596 static void BuildCargoTranslationMap()
05597 {
05598   memset(_cur_grffile->cargo_map, 0xFF, sizeof(_cur_grffile->cargo_map));
05599 
05600   for (CargoID c = 0; c < NUM_CARGO; c++) {
05601     const CargoSpec *cs = GetCargo(c);
05602     if (!cs->IsValid()) continue;
05603 
05604     if (_cur_grffile->cargo_max == 0) {
05605       /* Default translation table, so just a straight mapping to bitnum */
05606       _cur_grffile->cargo_map[c] = cs->bitnum;
05607     } else {
05608       /* Check the translation table for this cargo's label */
05609       for (uint i = 0; i < _cur_grffile->cargo_max; i++) {
05610         if (cs->label == _cur_grffile->cargo_list[i]) {
05611           _cur_grffile->cargo_map[c] = i;
05612           break;
05613         }
05614       }
05615     }
05616   }
05617 }
05618 
05619 static void InitNewGRFFile(const GRFConfig *config, int sprite_offset)
05620 {
05621   GRFFile *newfile = GetFileByFilename(config->filename);
05622   if (newfile != NULL) {
05623     /* We already loaded it once. */
05624     newfile->sprite_offset = sprite_offset;
05625     _cur_grffile = newfile;
05626     return;
05627   }
05628 
05629   newfile = CallocT<GRFFile>(1);
05630 
05631   if (newfile == NULL) error ("Out of memory");
05632 
05633   newfile->filename = strdup(config->filename);
05634   newfile->sprite_offset = sprite_offset;
05635 
05636   /* Copy the initial parameter list */
05637   assert(lengthof(newfile->param) == lengthof(config->param) && lengthof(config->param) == 0x80);
05638   newfile->param_end = config->num_params;
05639   memcpy(newfile->param, config->param, sizeof(newfile->param));
05640 
05641   if (_first_grffile == NULL) {
05642     _cur_grffile = newfile;
05643     _first_grffile = newfile;
05644   } else {
05645     _cur_grffile->next = newfile;
05646     _cur_grffile = newfile;
05647   }
05648 }
05649 
05650 
05653 static const CargoLabel _default_refitmasks_rail[] = {
05654   'PASS', 'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD',
05655   'IORE', 'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE',
05656   'WATR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
05657   'PLST', 'FZDR',
05658   0 };
05659 
05660 static const CargoLabel _default_refitmasks_road[] = {
05661   0 };
05662 
05663 static const CargoLabel _default_refitmasks_ships[] = {
05664   'COAL', 'MAIL', 'LVST', 'GOOD', 'GRAI', 'WHEA', 'MAIZ', 'WOOD', 'IORE',
05665   'STEL', 'VALU', 'GOLD', 'DIAM', 'PAPR', 'FOOD', 'FRUT', 'CORE', 'WATR',
05666   'RUBR', 'SUGR', 'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL',
05667   'PLST', 'FZDR',
05668   0 };
05669 
05670 static const CargoLabel _default_refitmasks_aircraft[] = {
05671   'PASS', 'MAIL', 'GOOD', 'VALU', 'GOLD', 'DIAM', 'FOOD', 'FRUT', 'SUGR',
05672   'TOYS', 'BATT', 'SWET', 'TOFF', 'COLA', 'CTCD', 'BUBL', 'PLST', 'FZDR',
05673   0 };
05674 
05675 static const CargoLabel *_default_refitmasks[] = {
05676   _default_refitmasks_rail,
05677   _default_refitmasks_road,
05678   _default_refitmasks_ships,
05679   _default_refitmasks_aircraft,
05680 };
05681 
05682 
05686 static void CalculateRefitMasks()
05687 {
05688   Engine *e;
05689 
05690   FOR_ALL_ENGINES(e) {
05691     EngineID engine = e->index;
05692     EngineInfo *ei = &e->info;
05693     uint32 mask = 0;
05694     uint32 not_mask = 0;
05695     uint32 xor_mask = 0;
05696 
05697     if (ei->refit_mask != 0) {
05698       const GRFFile *file = e->grffile;
05699       if (file != NULL && file->cargo_max != 0) {
05700         /* Apply cargo translation table to the refit mask */
05701         uint num_cargo = min(32, file->cargo_max);
05702         for (uint i = 0; i < num_cargo; i++) {
05703           if (!HasBit(ei->refit_mask, i)) continue;
05704 
05705           CargoID c = GetCargoIDByLabel(file->cargo_list[i]);
05706           if (c == CT_INVALID) continue;
05707 
05708           SetBit(xor_mask, c);
05709         }
05710       } else {
05711         /* No cargo table, so use the cargo bitnum values */
05712         for (CargoID c = 0; c < NUM_CARGO; c++) {
05713           const CargoSpec *cs = GetCargo(c);
05714           if (!cs->IsValid()) continue;
05715 
05716           if (HasBit(ei->refit_mask, cs->bitnum)) SetBit(xor_mask, c);
05717         }
05718       }
05719     }
05720 
05721     if (_gted[engine].cargo_allowed != 0) {
05722       /* Build up the list of cargo types from the set cargo classes. */
05723       for (CargoID i = 0; i < NUM_CARGO; i++) {
05724         const CargoSpec *cs = GetCargo(i);
05725         if (_gted[engine].cargo_allowed    & cs->classes) SetBit(mask,     i);
05726         if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, i);
05727       }
05728     } else if (xor_mask == 0) {
05729       /* Don't apply default refit mask to wagons or engines with no capacity */
05730       if (e->type != VEH_TRAIN || (e->u.rail.capacity != 0 && e->u.rail.railveh_type != RAILVEH_WAGON)) {
05731         const CargoLabel *cl = _default_refitmasks[e->type];
05732         for (uint i = 0;; i++) {
05733           if (cl[i] == 0) break;
05734 
05735           CargoID cargo = GetCargoIDByLabel(cl[i]);
05736           if (cargo == CT_INVALID) continue;
05737 
05738           SetBit(xor_mask, cargo);
05739         }
05740       }
05741     }
05742 
05743     ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
05744 
05745     /* Check if this engine's cargo type is valid. If not, set to the first refittable
05746      * cargo type. Apparently cargo_type isn't a common property... */
05747     switch (e->type) {
05748       default: NOT_REACHED();
05749       case VEH_AIRCRAFT: break;
05750       case VEH_TRAIN: {
05751         RailVehicleInfo *rvi = &e->u.rail;
05752         if (rvi->cargo_type == CT_INVALID) rvi->cargo_type = FindFirstRefittableCargo(engine);
05753         if (rvi->cargo_type == CT_INVALID) ei->climates = 0x80;
05754         break;
05755       }
05756       case VEH_ROAD: {
05757         RoadVehicleInfo *rvi = &e->u.road;
05758         if (rvi->cargo_type == CT_INVALID) rvi->cargo_type = FindFirstRefittableCargo(engine);
05759         if (rvi->cargo_type == CT_INVALID) ei->climates = 0x80;
05760         break;
05761       }
05762       case VEH_SHIP: {
05763         ShipVehicleInfo *svi = &e->u.ship;
05764         if (svi->cargo_type == CT_INVALID) svi->cargo_type = FindFirstRefittableCargo(engine);
05765         if (svi->cargo_type == CT_INVALID) ei->climates = 0x80;
05766         break;
05767       }
05768     }
05769   }
05770 }
05771 
05776 static void FinaliseHouseArray()
05777 {
05778   /* If there are no houses with start dates before 1930, then all houses
05779    * with start dates of 1930 have them reset to 0. This is in order to be
05780    * compatible with TTDPatch, where if no houses have start dates before
05781    * 1930 and the date is before 1930, the game pretends that this is 1930.
05782    * If there have been any houses defined with start dates before 1930 then
05783    * the dates are left alone.
05784    * On the other hand, why 1930? Just 'fix' the houses with the lowest
05785    * minimum introduction date to 0.
05786    */
05787   Year min_year = MAX_YEAR;
05788 
05789   for (GRFFile *file = _first_grffile; file != NULL; file = file->next) {
05790     if (file->housespec == NULL) continue;
05791 
05792     for (int i = 0; i < HOUSE_MAX; i++) {
05793       HouseSpec *hs = file->housespec[i];
05794       if (hs != NULL) {
05795         _house_mngr.SetEntitySpec(hs);
05796         if (hs->min_year < min_year) min_year = hs->min_year;
05797       }
05798     }
05799   }
05800 
05801   if (min_year != 0) {
05802     for (int i = 0; i < HOUSE_MAX; i++) {
05803       HouseSpec *hs = GetHouseSpecs(i);
05804 
05805       if (hs->enabled && hs->min_year == min_year) hs->min_year = 0;
05806     }
05807   }
05808 }
05809 
05813 static void FinaliseIndustriesArray()
05814 {
05815   for (GRFFile *file = _first_grffile; file != NULL; file = file->next) {
05816     if (file->industryspec != NULL) {
05817       for (int i = 0; i < NUM_INDUSTRYTYPES; i++) {
05818         IndustrySpec *indsp = file->industryspec[i];
05819 
05820         if (indsp != NULL && indsp->enabled) {
05821           StringID strid;
05822           /* process the conversion of text at the end, so to be sure everything will be fine
05823            * and available.  Check if it does not return undefind marker, which is a very good sign of a
05824            * substitute industry who has not changed the string been examined, thus using it as such */
05825           strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
05826           if (strid != STR_UNDEFINED) indsp->name = strid;
05827 
05828           strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
05829           if (strid != STR_UNDEFINED) indsp->closure_text = strid;
05830 
05831           strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
05832           if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
05833 
05834           strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
05835           if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
05836 
05837           strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
05838           if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
05839 
05840           if (indsp->station_name != STR_NULL) {
05841             /* STR_NULL (0) can be set by grf.  It has a meaning regarding assignation of the
05842              * station's name. Don't want to lose the value, therefore, do not process. */
05843             strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
05844             if (strid != STR_UNDEFINED) indsp->station_name = strid;
05845           }
05846 
05847           _industry_mngr.SetEntitySpec(indsp);
05848           _loaded_newgrf_features.has_newindustries = true;
05849         }
05850       }
05851     }
05852 
05853     if (file->indtspec != NULL) {
05854       for (int i = 0; i < NUM_INDUSTRYTILES; i++) {
05855         IndustryTileSpec *indtsp = file->indtspec[i];
05856         if (indtsp != NULL) {
05857           _industile_mngr.SetEntitySpec(indtsp);
05858         }
05859       }
05860     }
05861   }
05862 
05863   for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
05864     IndustrySpec *indsp = &_industry_specs[j];
05865     if (indsp->enabled && indsp->grf_prop.grffile != NULL) {
05866       for (uint i = 0; i < 3; i++) {
05867         indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
05868       }
05869     }
05870   }
05871 }
05872 
05873 /* Here we perform initial decoding of some special sprites (as are they
05874  * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
05875  * partial implementation yet). */
05876 /* XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
05877  * a crafted invalid GRF file. We should tell that to the user somehow, or
05878  * better make this more robust in the future. */
05879 static void DecodeSpecialSprite(uint num, GrfLoadingStage stage)
05880 {
05881   /* XXX: There is a difference between staged loading in TTDPatch and
05882    * here.  In TTDPatch, for some reason actions 1 and 2 are carried out
05883    * during stage 1, whilst action 3 is carried out during stage 2 (to
05884    * "resolve" cargo IDs... wtf). This is a little problem, because cargo
05885    * IDs are valid only within a given set (action 1) block, and may be
05886    * overwritten after action 3 associates them. But overwriting happens
05887    * in an earlier stage than associating, so...  We just process actions
05888    * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
05889    * --pasky */
05890   /* We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
05891    * is not in memory and scanning the file every time would be too expensive.
05892    * In other stages we skip action 0x10 since it's already dealt with. */
05893   static const SpecialSpriteHandler handlers[][GLS_END] = {
05894     /* 0x00 */ { NULL,     SafeChangeInfo, NULL,       NULL,           ReserveChangeInfo, FeatureChangeInfo, },
05895     /* 0x01 */ { SkipAct1, SkipAct1,  SkipAct1,        SkipAct1,       SkipAct1,          NewSpriteSet, },
05896     /* 0x02 */ { NULL,     NULL,      NULL,            NULL,           NULL,              NewSpriteGroup, },
05897     /* 0x03 */ { NULL,     GRFUnsafe, NULL,            NULL,           NULL,              FeatureMapSpriteGroup, },
05898     /* 0x04 */ { NULL,     NULL,      NULL,            NULL,           NULL,              FeatureNewName, },
05899     /* 0x05 */ { SkipAct5, SkipAct5,  SkipAct5,        SkipAct5,       SkipAct5,          GraphicsNew, },
05900     /* 0x06 */ { NULL,     NULL,      NULL,            CfgApply,       CfgApply,          CfgApply, },
05901     /* 0x07 */ { NULL,     NULL,      NULL,            NULL,           SkipIf,            SkipIf, },
05902     /* 0x08 */ { ScanInfo, NULL,      NULL,            GRFInfo,        GRFInfo,           GRFInfo, },
05903     /* 0x09 */ { NULL,     NULL,      NULL,            SkipIf,         SkipIf,            SkipIf, },
05904     /* 0x0A */ { SkipActA, SkipActA,  SkipActA,        SkipActA,       SkipActA,          SpriteReplace, },
05905     /* 0x0B */ { NULL,     NULL,      NULL,            GRFLoadError,   GRFLoadError,      GRFLoadError, },
05906     /* 0x0C */ { NULL,     NULL,      NULL,            GRFComment,     NULL,              GRFComment, },
05907     /* 0x0D */ { NULL,     SafeParamSet, NULL,         ParamSet,       ParamSet,          ParamSet, },
05908     /* 0x0E */ { NULL,     SafeGRFInhibit, NULL,       GRFInhibit,     GRFInhibit,        GRFInhibit, },
05909     /* 0x0F */ { NULL,     GRFUnsafe, NULL,            FeatureTownName, NULL,             NULL, },
05910     /* 0x10 */ { NULL,     NULL,      DefineGotoLabel, NULL,           NULL,              NULL, },
05911     /* 0x11 */ { SkipAct11,GRFUnsafe, SkipAct11,       SkipAct11,      SkipAct11,         GRFSound, },
05912     /* 0x12 */ { SkipAct12, SkipAct12, SkipAct12,      SkipAct12,      SkipAct12,         LoadFontGlyph, },
05913     /* 0x13 */ { NULL,     NULL,      NULL,            NULL,           NULL,              TranslateGRFStrings, },
05914   };
05915 
05916   bool preloaded_sprite = true;
05917   GRFLocation location(_cur_grfconfig->grfid, _nfo_line);
05918   byte *buf;
05919 
05920   GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
05921   if (it == _grf_line_to_action6_sprite_override.end()) {
05922     /* No preloaded sprite to work with; allocate and read the
05923      * pseudo sprite content. */
05924     buf = MallocT<byte>(num);
05925     FioReadBlock(buf, num);
05926     preloaded_sprite = false;
05927   } else {
05928     /* Use the preloaded sprite data. */
05929     buf = _grf_line_to_action6_sprite_override[location];
05930     grfmsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
05931 
05932     /* Skip the real (original) content of this action. */
05933     FioSeekTo(num, SEEK_CUR);
05934   }
05935 
05936   byte action = buf[0];
05937 
05938   if (action == 0xFF) {
05939     grfmsg(7, "DecodeSpecialSprite: Handling data block in stage %d", stage);
05940     GRFDataBlock(buf, num);
05941   } else if (action == 0xFE) {
05942     grfmsg(7, "DecodeSpecialSprite: Handling import block in stage %d", stage);
05943     GRFImportBlock(buf, num);
05944   } else if (action >= lengthof(handlers)) {
05945     grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
05946   } else if (handlers[action][stage] == NULL) {
05947     grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
05948   } else {
05949     grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
05950     handlers[action][stage](buf, num);
05951   }
05952   if (!preloaded_sprite) free(buf);
05953 }
05954 
05955 
05956 void LoadNewGRFFile(GRFConfig *config, uint file_index, GrfLoadingStage stage)
05957 {
05958   const char *filename = config->filename;
05959   uint16 num;
05960 
05961   /* A .grf file is activated only if it was active when the game was
05962    * started.  If a game is loaded, only its active .grfs will be
05963    * reactivated, unless "loadallgraphics on" is used.  A .grf file is
05964    * considered active if its action 8 has been processed, i.e. its
05965    * action 8 hasn't been skipped using an action 7.
05966    *
05967    * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
05968    * carried out.  All others are ignored, because they only need to be
05969    * processed once at initialization.  */
05970   if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
05971     _cur_grffile = GetFileByFilename(filename);
05972     if (_cur_grffile == NULL) usererror("File '%s' lost in cache.\n", filename);
05973     if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
05974     if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
05975     _cur_grffile->is_ottdfile = config->IsOpenTTDBaseGRF();
05976   }
05977 
05978   if (file_index > LAST_GRF_SLOT) {
05979     DEBUG(grf, 0, "'%s' is not loaded as the maximum number of GRFs has been reached", filename);
05980     config->status = GCS_DISABLED;
05981     config->error  = CallocT<GRFError>(1);
05982     config->error->severity = STR_NEWGRF_ERROR_MSG_FATAL;
05983     config->error->message  = STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED;
05984     return;
05985   }
05986 
05987   FioOpenFile(file_index, filename);
05988   _file_index = file_index; // XXX
05989   _palette_remap_grf[_file_index] = (config->windows_paletted != (_use_palette == PAL_WINDOWS));
05990 
05991   _cur_grfconfig = config;
05992 
05993   DEBUG(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '%s'", filename);
05994 
05995   /* Skip the first sprite; we don't care about how many sprites this
05996    * does contain; newest TTDPatches and George's longvehicles don't
05997    * neither, apparently. */
05998   if (FioReadWord() == 4 && FioReadByte() == 0xFF) {
05999     FioReadDword();
06000   } else {
06001     DEBUG(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
06002     return;
06003   }
06004 
06005   _skip_sprites = 0; // XXX
06006   _nfo_line = 0;
06007 
06008   while ((num = FioReadWord()) != 0) {
06009     byte type = FioReadByte();
06010     _nfo_line++;
06011 
06012     if (type == 0xFF) {
06013       if (_skip_sprites == 0) {
06014         DecodeSpecialSprite(num, stage);
06015 
06016         /* Stop all processing if we are to skip the remaining sprites */
06017         if (_skip_sprites == -1) break;
06018 
06019         continue;
06020       } else {
06021         FioSkipBytes(num);
06022       }
06023     } else {
06024       if (_skip_sprites == 0) {
06025         grfmsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
06026         config->status = GCS_DISABLED;
06027         config->error  = CallocT<GRFError>(1);
06028         config->error->severity = STR_NEWGRF_ERROR_MSG_FATAL;
06029         config->error->message  = STR_NEWGRF_ERROR_UNEXPECTED_SPRITE;
06030         break;
06031       }
06032 
06033       FioSkipBytes(7);
06034       SkipSpriteData(type, num - 8);
06035     }
06036 
06037     if (_skip_sprites > 0) _skip_sprites--;
06038   }
06039 }
06040 
06048 static void ActivateOldShore()
06049 {
06050   /* Use default graphics, if no shore sprites were loaded.
06051    * Should not happen, as openttd(w/d).grf includes some. */
06052   if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
06053 
06054   if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
06055     DupSprite(SPR_ORIGINALSHORE_START +  1, SPR_SHORE_BASE +  1); // SLOPE_W
06056     DupSprite(SPR_ORIGINALSHORE_START +  2, SPR_SHORE_BASE +  2); // SLOPE_S
06057     DupSprite(SPR_ORIGINALSHORE_START +  6, SPR_SHORE_BASE +  3); // SLOPE_SW
06058     DupSprite(SPR_ORIGINALSHORE_START     , SPR_SHORE_BASE +  4); // SLOPE_E
06059     DupSprite(SPR_ORIGINALSHORE_START +  4, SPR_SHORE_BASE +  6); // SLOPE_SE
06060     DupSprite(SPR_ORIGINALSHORE_START +  3, SPR_SHORE_BASE +  8); // SLOPE_N
06061     DupSprite(SPR_ORIGINALSHORE_START +  7, SPR_SHORE_BASE +  9); // SLOPE_NW
06062     DupSprite(SPR_ORIGINALSHORE_START +  5, SPR_SHORE_BASE + 12); // SLOPE_NE
06063   }
06064 
06065   if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
06066     DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE +  0); // SLOPE_STEEP_S
06067     DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE +  5); // SLOPE_STEEP_W
06068     DupSprite(SPR_FLAT_GRASS_TILE +  7, SPR_SHORE_BASE +  7); // SLOPE_WSE
06069     DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
06070     DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
06071     DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
06072     DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
06073     DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
06074 
06075     /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
06076      *       If they would be used somewhen, then these grass tiles will most like not look as needed */
06077     DupSprite(SPR_FLAT_GRASS_TILE +  5, SPR_SHORE_BASE + 16); // SLOPE_EW
06078     DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
06079   }
06080 }
06081 
06082 void InitDepotWindowBlockSizes();
06083 
06084 extern void InitGRFTownGeneratorNames();
06085 
06086 static void AfterLoadGRFs()
06087 {
06088   for (StringIDToGRFIDMapping::iterator it = _string_to_grf_mapping.begin(); it != _string_to_grf_mapping.end(); it++) {
06089     *((*it).first) = MapGRFStringID((*it).second, *((*it).first));
06090   }
06091   _string_to_grf_mapping.clear();
06092 
06093   /* Free the action 6 override sprites. */
06094   for (GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.begin(); it != _grf_line_to_action6_sprite_override.end(); it++) {
06095     free((*it).second);
06096   }
06097   _grf_line_to_action6_sprite_override.clear();
06098 
06099   /* Pre-calculate all refit masks after loading GRF files. */
06100   CalculateRefitMasks();
06101 
06102   /* Set the block size in the depot windows based on vehicle sprite sizes */
06103   InitDepotWindowBlockSizes();
06104 
06105   /* Add all new houses to the house array. */
06106   FinaliseHouseArray();
06107 
06108   /* Add all new industries to the industry array. */
06109   FinaliseIndustriesArray();
06110 
06111   /* Create dynamic list of industry legends for smallmap_gui.cpp */
06112   BuildIndustriesLegend();
06113 
06114   /* Update the townname generators list */
06115   InitGRFTownGeneratorNames();
06116 
06117   /* Run all queued vehicle list order changes */
06118   CommitVehicleListOrderChanges();
06119 
06120   /* Load old shore sprites in new position, if they were replaced by ActionA */
06121   ActivateOldShore();
06122 
06123   Engine *e;
06124   FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
06125     if (_gted[e->index].rv_max_speed != 0) {
06126       /* Set RV maximum speed from the mph/0.8 unit value */
06127       e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
06128     }
06129   }
06130 
06131   SetYearEngineAgingStops();
06132 
06133   /* Deallocate temporary loading data */
06134   free(_gted);
06135   _grm_sprites.clear();
06136 }
06137 
06138 void LoadNewGRF(uint load_index, uint file_index)
06139 {
06140   /* In case of networking we need to "sync" the start values
06141    * so all NewGRFs are loaded equally. For this we use the
06142    * start date of the game and we set the counters, etc. to
06143    * 0 so they're the same too. */
06144   Date date            = _date;
06145   Year year            = _cur_year;
06146   DateFract date_fract = _date_fract;
06147   uint16 tick_counter  = _tick_counter;
06148   byte display_opt     = _display_opt;
06149 
06150   if (_networking) {
06151     _cur_year     = _settings_game.game_creation.starting_year;
06152     _date         = ConvertYMDToDate(_cur_year, 0, 1);
06153     _date_fract   = 0;
06154     _tick_counter = 0;
06155     _display_opt  = 0;
06156   }
06157 
06158   InitializeGRFSpecial();
06159 
06160   ResetNewGRFData();
06161 
06162   /*
06163    * Reset the status of all files, so we can 'retry' to load them.
06164    * This is needed when one for example rearranges the NewGRFs in-game
06165    * and a previously disabled NewGRF becomes useable. If it would not
06166    * be reset, the NewGRF would remain disabled even though it should
06167    * have been enabled.
06168    */
06169   for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
06170     if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
06171   }
06172 
06173   _cur_spriteid = load_index;
06174 
06175   /* Load newgrf sprites
06176    * in each loading stage, (try to) open each file specified in the config
06177    * and load information from it. */
06178   for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
06179     /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
06180      * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
06181     for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
06182       if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
06183     }
06184 
06185     uint slot = file_index;
06186 
06187     _cur_stage = stage;
06188     for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
06189       if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
06190       if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
06191 
06192       /* @todo usererror() */
06193       if (!FioCheckFileExists(c->filename)) usererror("NewGRF file is missing '%s'", c->filename);
06194 
06195       if (stage == GLS_LABELSCAN) InitNewGRFFile(c, _cur_spriteid);
06196       LoadNewGRFFile(c, slot++, stage);
06197       if (stage == GLS_RESERVE) {
06198         SetBit(c->flags, GCF_RESERVED);
06199       } else if (stage == GLS_ACTIVATION) {
06200         ClrBit(c->flags, GCF_RESERVED);
06201         assert(GetFileByGRFID(c->grfid) == _cur_grffile);
06202         ClearTemporaryNewGRFData(_cur_grffile);
06203         BuildCargoTranslationMap();
06204         DEBUG(sprite, 2, "LoadNewGRF: Currently %i sprites are loaded", _cur_spriteid);
06205       } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
06206         /* We're not going to activate this, so free whatever data we allocated */
06207         ClearTemporaryNewGRFData(_cur_grffile);
06208       }
06209     }
06210   }
06211 
06212   /* Call any functions that should be run after GRFs have been loaded. */
06213   AfterLoadGRFs();
06214 
06215   /* Now revert back to the original situation */
06216   _cur_year     = year;
06217   _date         = date;
06218   _date_fract   = date_fract;
06219   _tick_counter = tick_counter;
06220   _display_opt  = display_opt;
06221 }
06222 
06223 bool HasGrfMiscBit(GrfMiscBit bit)
06224 {
06225   return HasBit(_misc_grf_features, bit);
06226 }

Generated on Mon Feb 16 23:12:08 2009 for openttd by  doxygen 1.5.6