# newgrf.cpp

Go to the documentation of this file.

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