newgrf.cpp

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

Generated on Wed Jan 20 23:38:37 2010 for OpenTTD by  doxygen 1.5.6