/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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 .
*/
/** @file newgrf.cpp Base of all NewGRF support. */
#include "stdafx.h"
#include
#include "newgrf_internal.h"
#include "core/container_func.hpp"
#include "debug.h"
#include "fileio_func.h"
#include "engine_func.h"
#include "engine_base.h"
#include "bridge.h"
#include "town.h"
#include "newgrf_engine.h"
#include "newgrf_text.h"
#include "fontcache.h"
#include "currency.h"
#include "landscape.h"
#include "newgrf_cargo.h"
#include "newgrf_house.h"
#include "newgrf_sound.h"
#include "newgrf_station.h"
#include "industrytype.h"
#include "industry_map.h"
#include "newgrf_canal.h"
#include "newgrf_townname.h"
#include "newgrf_industries.h"
#include "newgrf_airporttiles.h"
#include "newgrf_airport.h"
#include "newgrf_object.h"
#include "newgrf_newsignals.h"
#include "newgrf_newlandscape.h"
#include "newgrf_extension.h"
#include "rev.h"
#include "fios.h"
#include "strings_func.h"
#include "date_func.h"
#include "string_func.h"
#include "network/core/config.h"
#include "smallmap_gui.h"
#include "genworld.h"
#include "error.h"
#include "vehicle_func.h"
#include "language.h"
#include "vehicle_base.h"
#include "road.h"
#include "newgrf_roadstop.h"
#include "debug_settings.h"
#include "table/strings.h"
#include "table/build_industry.h"
#include "3rdparty/cpp-btree/btree_map.h"
#include "safeguards.h"
/* TTDPatch extended GRF format codec
* (c) Petr Baudis 2004 (GPL'd)
* Changes by Florian octo Forster are (c) by the OpenTTD development team.
*
* Contains portions of documentation by TTDPatch team.
* Thanks especially to Josef Drexler for the documentation as well as a lot
* of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
* served as subject to the initial testing of this codec. */
/** List of all loaded GRF files */
static std::vector _grf_files;
const std::vector &GetAllGRFFiles()
{
return _grf_files;
}
static btree::btree_map _callback_result_cache;
/** Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E */
byte _misc_grf_features = 0;
/** 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */
static uint32_t _ttdpatch_flags[8];
static uint32_t _observed_ttdpatch_flags[8];
/** Indicates which are the newgrf features currently loaded ingame */
GRFLoadedFeatures _loaded_newgrf_features;
GrfProcessingState _cur;
/**
* Helper to check whether an image index is valid for a particular NewGRF vehicle.
* @tparam T The type of vehicle.
* @param image_index The image index to check.
* @return True iff the image index is valid, or 0xFD (use new graphics).
*/
template
static inline bool IsValidNewGRFImageIndex(uint8_t image_index)
{
return image_index == 0xFD || IsValidImageIndex(image_index);
}
class OTTDByteReaderSignal { };
/** Class to read from a NewGRF file */
class ByteReader {
protected:
byte *data;
byte *end;
public:
ByteReader(byte *data, byte *end) : data(data), end(end) { }
inline byte *ReadBytes(size_t size)
{
if (data + size >= end) {
/* Put data at the end, as would happen if every byte had been individually read. */
data = end;
throw OTTDByteReaderSignal();
}
byte *ret = data;
data += size;
return ret;
}
inline byte ReadByte()
{
if (data < end) return *(data)++;
throw OTTDByteReaderSignal();
}
uint16_t ReadWord()
{
uint16_t val = ReadByte();
return val | (ReadByte() << 8);
}
uint16_t ReadExtendedByte()
{
uint16_t val = ReadByte();
return val == 0xFF ? ReadWord() : val;
}
uint32_t ReadDWord()
{
uint32_t val = ReadWord();
return val | (ReadWord() << 16);
}
uint32_t ReadVarSize(byte size)
{
switch (size) {
case 1: return ReadByte();
case 2: return ReadWord();
case 4: return ReadDWord();
default:
NOT_REACHED();
return 0;
}
}
const char *ReadString()
{
char *string = reinterpret_cast(data);
size_t string_length = ttd_strnlen(string, Remaining());
if (string_length == Remaining()) {
/* String was not NUL terminated, so make sure it is now. */
string[string_length - 1] = '\0';
grfmsg(7, "String was not terminated with a zero byte.");
} else {
/* Increase the string length to include the NUL byte. */
string_length++;
}
Skip(string_length);
return string;
}
inline size_t Remaining() const
{
return end - data;
}
inline bool HasData(size_t count = 1) const
{
return data + count <= end;
}
inline byte *Data()
{
return data;
}
inline void Skip(size_t len)
{
data += len;
/* It is valid to move the buffer to exactly the end of the data,
* as there may not be any more data read. */
if (data > end) throw OTTDByteReaderSignal();
}
inline void ResetReadPosition(byte *pos)
{
data = pos;
}
};
typedef void (*SpecialSpriteHandler)(ByteReader *buf);
/** The maximum amount of stations a single GRF is allowed to add */
static const uint NUM_STATIONS_PER_GRF = UINT16_MAX - 1;
/** Temporary engine data used when loading only */
struct GRFTempEngineData {
/** Summary state of refittability properties */
enum Refittability {
UNSET = 0, ///< No properties assigned. Default refit masks shall be activated.
EMPTY, ///< GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
NONEMPTY, ///< GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not available), disable the vehicle.
};
uint16_t cargo_allowed;
uint16_t cargo_disallowed;
RailTypeLabel railtypelabel;
uint8_t roadtramtype;
const GRFFile *defaultcargo_grf; ///< GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
Refittability refittability; ///< Did the newgrf set any refittability property? If not, default refittability will be applied.
uint8_t rv_max_speed; ///< Temporary storage of RV prop 15, maximum speed in mph/0.8
CargoTypes ctt_include_mask; ///< Cargo types always included in the refit mask.
CargoTypes ctt_exclude_mask; ///< Cargo types always excluded from the refit mask.
/**
* Update the summary refittability on setting a refittability property.
* @param non_empty true if the GRF sets the vehicle to be refittable.
*/
void UpdateRefittability(bool non_empty)
{
if (non_empty) {
this->refittability = NONEMPTY;
} else if (this->refittability == UNSET) {
this->refittability = EMPTY;
}
}
};
static std::vector _gted; ///< Temporary engine data used during NewGRF loading
/**
* Contains the GRF ID of the owner of a vehicle if it has been reserved.
* GRM for vehicles is only used if dynamic engine allocation is disabled,
* so 256 is the number of original engines. */
static uint32_t _grm_engines[256];
/** Contains the GRF ID of the owner of a cargo if it has been reserved */
static uint32_t _grm_cargoes[NUM_CARGO * 2];
struct GRFLocation {
uint32_t grfid;
uint32_t nfoline;
GRFLocation() { }
GRFLocation(uint32_t grfid, uint32_t nfoline) : grfid(grfid), nfoline(nfoline) { }
bool operator<(const GRFLocation &other) const
{
return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
}
bool operator == (const GRFLocation &other) const
{
return this->grfid == other.grfid && this->nfoline == other.nfoline;
}
};
static btree::btree_map _grm_sprites;
typedef btree::btree_map> GRFLineToSpriteOverride;
static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
static bool _action6_override_active = false;
/**
* DEBUG() function dedicated to newGRF debugging messages
* Function is essentially the same as DEBUG(grf, severity, ...) with the
* addition of file:line information when parsing grf files.
* NOTE: for the above reason(s) grfmsg() should ONLY be used for
* loading/parsing grf files, not for runtime debug messages as there
* is no file information available during that time.
* @param severity debugging severity level, see debug.h
* @param str message in printf() format
*/
void CDECL _intl_grfmsg(int severity, const char *str, ...)
{
char buf[1024];
va_list va;
va_start(va, str);
vseprintf(buf, lastof(buf), str, va);
va_end(va);
DEBUG(grf, severity, "[%s:%d] %s", _cur.grfconfig->GetDisplayPath(), _cur.nfo_line, buf);
}
/**
* Obtain a NewGRF file by its grfID
* @param grfid The grfID to obtain the file for
* @return The file.
*/
GRFFile *GetFileByGRFID(uint32_t grfid)
{
for (GRFFile * const file : _grf_files) {
if (file->grfid == grfid) return file;
}
return nullptr;
}
/**
* Obtain a NewGRF file by its grfID, expect it to usually be the current GRF's grfID
* @param grfid The grfID to obtain the file for
* @return The file.
*/
GRFFile *GetFileByGRFIDExpectCurrent(uint32_t grfid)
{
if (_cur.grffile->grfid == grfid) return _cur.grffile;
return GetFileByGRFID(grfid);
}
/**
* Obtain a NewGRF file by its filename
* @param filename The filename to obtain the file for.
* @return The file.
*/
static GRFFile *GetFileByFilename(const std::string &filename)
{
for (GRFFile * const file : _grf_files) {
if (file->filename == filename) return file;
}
return nullptr;
}
/** Reset all NewGRFData that was used only while processing data */
static void ClearTemporaryNewGRFData(GRFFile *gf)
{
gf->labels.clear();
}
/**
* Disable a GRF
* @param message Error message or STR_NULL.
* @param config GRFConfig to disable, nullptr for current.
* @return Error message of the GRF for further customisation.
*/
static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
{
GRFFile *file;
if (config != nullptr) {
file = GetFileByGRFID(config->ident.grfid);
} else {
config = _cur.grfconfig;
file = _cur.grffile;
}
config->status = GCS_DISABLED;
if (file != nullptr) ClearTemporaryNewGRFData(file);
if (config == _cur.grfconfig) _cur.skip_sprites = -1;
if (message == STR_NULL) return nullptr;
config->error = {STR_NEWGRF_ERROR_MSG_FATAL, message};
if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
return &config->error.value();
}
/**
* Information for mapping static StringIDs.
*/
struct StringIDMapping {
uint32_t grfid; ///< Source NewGRF.
StringID source; ///< Source StringID (GRF local).
StringID *target; ///< Destination for mapping result.
};
typedef std::vector StringIDMappingVector;
static StringIDMappingVector _string_to_grf_mapping;
/**
* Record a static StringID for getting translated later.
* @param source Source StringID (GRF local).
* @param target Destination for the mapping result.
*/
static void AddStringForMapping(StringID source, StringID *target)
{
*target = STR_UNDEFINED;
_string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
}
/**
* Perform a mapping from TTDPatch's string IDs to OpenTTD's
* string IDs, but only for the ones we are aware off; the rest
* like likely unused and will show a warning.
* @param str the string ID to convert
* @return the converted string ID
*/
static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
{
/* StringID table for TextIDs 0x4E->0x6D */
static const StringID units_volume[] = {
STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
};
/* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
assert(!IsInsideMM(str, 0xD000, 0xD7FF));
#define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
static_assert(stringend - stringid == end - begin); \
if (str >= begin && str <= end) return str + (stringid - begin)
/* We have some changes in our cargo strings, resulting in some missing. */
TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
/* Map building names according to our lang file changes. There are several
* ranges of house ids, all of which need to be remapped to allow newgrfs
* to use original house names. */
TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
/* Same thing for industries */
TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
switch (str) {
case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
}
#undef TEXTID_TO_STRINGID
if (str == STR_NULL) return STR_EMPTY;
DEBUG(grf, 0, "Unknown StringID 0x%04X remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
return STR_EMPTY;
}
/**
* Used when setting an object's property to map to the GRF's strings
* while taking in consideration the "drift" between TTDPatch string system and OpenTTD's one
* @param grfid Id of the grf file.
* @param str StringID that we want to have the equivalent in OoenTTD.
* @return The properly adjusted StringID.
*/
StringID MapGRFStringID(uint32_t grfid, StringID str)
{
if (IsInsideMM(str, 0xD800, 0x10000)) {
/* General text provided by NewGRF.
* In the specs this is called the 0xDCxx range (misc persistent texts),
* but we meanwhile extended the range to 0xD800-0xFFFF.
* Note: We are not involved in the "persistent" business, since we do not store
* any NewGRF strings in savegames. */
return GetGRFStringID(grfid, str);
} else if (IsInsideMM(str, 0xD000, 0xD800)) {
/* Callback text provided by NewGRF.
* In the specs this is called the 0xD0xx range (misc graphics texts).
* These texts can be returned by various callbacks.
*
* Due to how TTDP implements the GRF-local- to global-textid translation
* texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
* We do not care about that difference and just mask out the 0x400 bit.
*/
str &= ~0x400;
return GetGRFStringID(grfid, str);
} else {
/* The NewGRF wants to include/reference an original TTD string.
* Try our best to find an equivalent one. */
return TTDPStringIDToOTTDStringIDMapping(str);
}
}
static btree::btree_map _grf_id_overrides;
/**
* Set the override for a NewGRF
* @param source_grfid The grfID which wants to override another NewGRF.
* @param target_grfid The grfID which is being overridden.
*/
static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
{
_grf_id_overrides[source_grfid] = target_grfid;
grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
}
/**
* Returns the engine associated to a certain internal_id, resp. allocates it.
* @param file NewGRF that wants to change the engine.
* @param type Vehicle type.
* @param internal_id Engine ID inside the NewGRF.
* @param static_access If the engine is not present, return nullptr instead of allocating a new engine. (Used for static Action 0x04).
* @return The requested engine.
*/
static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access = false)
{
/* Hack for add-on GRFs that need to modify another GRF's engines. This lets
* them use the same engine slots. */
uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
if (_settings_game.vehicle.dynamic_engines) {
/* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
scope_grfid = file->grfid;
uint32_t override = _grf_id_overrides[file->grfid];
if (override != 0) {
scope_grfid = override;
const GRFFile *grf_match = GetFileByGRFID(override);
if (grf_match == nullptr) {
grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
} else {
grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
}
}
/* Check if the engine is registered in the override manager */
EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
if (engine != INVALID_ENGINE) {
Engine *e = Engine::Get(engine);
if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
return e;
}
}
/* Check if there is an unreserved slot */
EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
if (engine != INVALID_ENGINE) {
Engine *e = Engine::Get(engine);
if (e->grf_prop.grffile == nullptr) {
e->grf_prop.grffile = file;
grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
}
/* Reserve the engine slot */
if (!static_access) {
EngineIDMapping *eid = _engine_mngr.data() + engine;
eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
}
return e;
}
if (static_access) return nullptr;
if (!Engine::CanAllocateItem()) {
grfmsg(0, "Can't allocate any more engines");
return nullptr;
}
size_t engine_pool_size = Engine::GetPoolSize();
/* ... it's not, so create a new one based off an existing engine */
Engine *e = new Engine(type, internal_id);
e->grf_prop.grffile = file;
/* Reserve the engine slot */
assert(_engine_mngr.size() == e->index);
_engine_mngr.push_back({
scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
internal_id,
type,
std::min(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
});
if (engine_pool_size != Engine::GetPoolSize()) {
/* Resize temporary engine data ... */
_gted.resize(Engine::GetPoolSize());
}
if (type == VEH_TRAIN) {
_gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
}
grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
return e;
}
/**
* Return the ID of a new engine
* @param file The NewGRF file providing the engine.
* @param type The Vehicle type.
* @param internal_id NewGRF-internal ID of the engine.
* @return The new EngineID.
* @note depending on the dynamic_engine setting and a possible override
* property the grfID may be unique or overwriting or partially re-defining
* properties of an existing engine.
*/
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
{
uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
if (_settings_game.vehicle.dynamic_engines) {
scope_grfid = file->grfid;
uint32_t override = _grf_id_overrides[file->grfid];
if (override != 0) scope_grfid = override;
}
return _engine_mngr.GetID(type, internal_id, scope_grfid);
}
/**
* Map the colour modifiers of TTDPatch to those that Open is using.
* @param grf_sprite Pointer to the structure been modified.
*/
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
{
if (HasBit(grf_sprite->pal, 14)) {
ClrBit(grf_sprite->pal, 14);
SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
}
if (HasBit(grf_sprite->sprite, 14)) {
ClrBit(grf_sprite->sprite, 14);
SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
}
if (HasBit(grf_sprite->sprite, 15)) {
ClrBit(grf_sprite->sprite, 15);
SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
}
}
/**
* Read a sprite and a palette from the GRF and convert them into a format
* suitable to OpenTTD.
* @param buf Input stream.
* @param read_flags Whether to read TileLayoutFlags.
* @param invert_action1_flag Set to true, if palette bit 15 means 'not from action 1'.
* @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
* @param feature GrfSpecFeature to use spritesets from.
* @param[out] grf_sprite Read sprite and palette.
* @param[out] max_sprite_offset Optionally returns the number of sprites in the spriteset of the sprite. (0 if no spritset)
* @param[out] max_palette_offset Optionally returns the number of sprites in the spriteset of the palette. (0 if no spritset)
* @return Read TileLayoutFlags.
*/
static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16_t *max_sprite_offset = nullptr, uint16_t *max_palette_offset = nullptr)
{
grf_sprite->sprite = buf->ReadWord();
grf_sprite->pal = buf->ReadWord();
TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
MapSpriteMappingRecolour(grf_sprite);
bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
ClrBit(grf_sprite->pal, 15);
if (custom_sprite) {
/* Use sprite from Action 1 */
uint index = GB(grf_sprite->sprite, 0, 14);
if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d", index);
grf_sprite->sprite = SPR_IMG_QUERY;
grf_sprite->pal = PAL_NONE;
} else {
SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
}
} else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return flags;
}
if (flags & TLF_CUSTOM_PALETTE) {
/* Use palette from Action 1 */
uint index = GB(grf_sprite->pal, 0, 14);
if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d for 'palette'", index);
grf_sprite->pal = PAL_NONE;
} else {
SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
}
} else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return flags;
}
return flags;
}
/**
* Preprocess the TileLayoutFlags and read register modifiers from the GRF.
* @param buf Input stream.
* @param flags TileLayoutFlags to process.
* @param is_parent Whether the sprite is a parentsprite with a bounding box.
* @param dts Sprite layout to insert data into.
* @param index Sprite index to process; 0 for ground sprite.
*/
static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
{
if (!(flags & TLF_DRAWING_FLAGS)) return;
if (dts->registers == nullptr) dts->AllocateRegisters();
TileLayoutRegisters ®s = const_cast(dts->registers[index]);
regs.flags = flags & TLF_DRAWING_FLAGS;
if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
if (is_parent) {
if (flags & TLF_BB_XY_OFFSET) {
regs.delta.parent[0] = buf->ReadByte();
regs.delta.parent[1] = buf->ReadByte();
}
if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
} else {
if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
}
if (flags & TLF_SPRITE_VAR10) {
regs.sprite_var10 = buf->ReadByte();
if (regs.sprite_var10 > TLR_MAX_VAR10) {
grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.sprite_var10, TLR_MAX_VAR10);
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return;
}
}
if (flags & TLF_PALETTE_VAR10) {
regs.palette_var10 = buf->ReadByte();
if (regs.palette_var10 > TLR_MAX_VAR10) {
grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.palette_var10, TLR_MAX_VAR10);
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return;
}
}
}
/**
* Read a spritelayout from the GRF.
* @param buf Input
* @param num_building_sprites Number of building sprites to read
* @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
* @param feature GrfSpecFeature to use spritesets from.
* @param allow_var10 Whether the spritelayout may specify var10 values for resolving multiple action-1-2-3 chains
* @param no_z_position Whether bounding boxes have no Z offset
* @param dts Layout container to output into
* @return True on error (GRF was disabled).
*/
static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
{
bool has_flags = HasBit(num_building_sprites, 6);
ClrBit(num_building_sprites, 6);
TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
uint16_t *max_sprite_offset = AllocaM(uint16_t, num_building_sprites + 1);
uint16_t *max_palette_offset = AllocaM(uint16_t, num_building_sprites + 1);
MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
MemSetT(max_palette_offset, 0, num_building_sprites + 1);
/* Groundsprite */
TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
if (_cur.skip_sprites < 0) return true;
if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
grfmsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x%x for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return true;
}
ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
if (_cur.skip_sprites < 0) return true;
for (uint i = 0; i < num_building_sprites; i++) {
DrawTileSeqStruct *seq = const_cast(&dts->seq[i]);
flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
if (_cur.skip_sprites < 0) return true;
if (flags & ~valid_flags) {
grfmsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x%x", flags & ~valid_flags);
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return true;
}
seq->delta_x = buf->ReadByte();
seq->delta_y = buf->ReadByte();
if (!no_z_position) seq->delta_z = buf->ReadByte();
if (seq->IsParentSprite()) {
seq->size_x = buf->ReadByte();
seq->size_y = buf->ReadByte();
seq->size_z = buf->ReadByte();
}
ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
if (_cur.skip_sprites < 0) return true;
}
/* Check if the number of sprites per spriteset is consistent */
bool is_consistent = true;
dts->consistent_max_offset = 0;
for (uint i = 0; i < num_building_sprites + 1; i++) {
if (max_sprite_offset[i] > 0) {
if (dts->consistent_max_offset == 0) {
dts->consistent_max_offset = max_sprite_offset[i];
} else if (dts->consistent_max_offset != max_sprite_offset[i]) {
is_consistent = false;
break;
}
}
if (max_palette_offset[i] > 0) {
if (dts->consistent_max_offset == 0) {
dts->consistent_max_offset = max_palette_offset[i];
} else if (dts->consistent_max_offset != max_palette_offset[i]) {
is_consistent = false;
break;
}
}
}
/* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
if (!is_consistent || dts->registers != nullptr) {
dts->consistent_max_offset = 0;
if (dts->registers == nullptr) dts->AllocateRegisters();
for (uint i = 0; i < num_building_sprites + 1; i++) {
TileLayoutRegisters ®s = const_cast(dts->registers[i]);
regs.max_sprite_offset = max_sprite_offset[i];
regs.max_palette_offset = max_palette_offset[i];
}
}
return false;
}
/**
* Translate the refit mask. refit_mask is uint32_t as it has not been mapped to CargoTypes.
*/
static CargoTypes TranslateRefitMask(uint32_t refit_mask)
{
CargoTypes result = 0;
for (uint8_t bit : SetBitIterator(refit_mask)) {
CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
if (cargo != INVALID_CARGO) SetBit(result, cargo);
}
return result;
}
/**
* Converts TTD(P) Base Price pointers into the enum used by OTTD
* See http://wiki.ttdpatch.net/tiki-index.php?page=BaseCosts
* @param base_pointer TTD(P) Base Price Pointer
* @param error_location Function name for grf error messages
* @param[out] index If \a base_pointer is valid, \a index is assigned to the matching price; else it is left unchanged
*/
static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
{
/* Special value for 'none' */
if (base_pointer == 0) {
*index = INVALID_PRICE;
return;
}
static const uint32_t start = 0x4B34; ///< Position of first base price
static const uint32_t size = 6; ///< Size of each base price record
if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
grfmsg(1, "%s: Unsupported running cost base 0x%04X, ignoring", error_location, base_pointer);
return;
}
*index = (Price)((base_pointer - start) / size);
}
/** Possible return values for the FeatureChangeInfo functions */
enum ChangeInfoResult {
CIR_SUCCESS, ///< Variable was parsed and read
CIR_DISABLED, ///< GRF was disabled due to error
CIR_UNHANDLED, ///< Variable was parsed but unread
CIR_UNKNOWN, ///< Variable is unknown
CIR_INVALID_ID, ///< Attempt to modify an invalid ID
};
typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf);
static ChangeInfoResult HandleAction0PropertyDefault(ByteReader *buf, int prop)
{
if (prop == A0RPI_UNKNOWN_ERROR) {
return CIR_DISABLED;
} else if (prop < A0RPI_UNKNOWN_IGNORE) {
return CIR_UNKNOWN;
} else {
buf->Skip(buf->ReadExtendedByte());
return CIR_SUCCESS;
}
}
static bool MappedPropertyLengthMismatch(ByteReader *buf, uint expected_size, const GRFFilePropertyRemapEntry *mapping_entry)
{
uint length = buf->ReadExtendedByte();
if (length != expected_size) {
if (mapping_entry != nullptr) {
grfmsg(2, "Ignoring use of mapped property: %s, feature: %s, mapped to: %X%s, with incorrect data size: %u instead of %u",
mapping_entry->name, GetFeatureString(mapping_entry->feature),
mapping_entry->property_id, mapping_entry->extended ? " (extended)" : "",
length, expected_size);
}
buf->Skip(length);
return true;
} else {
return false;
}
}
/**
* Define properties common to all vehicles
* @param ei Engine info.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
switch (prop) {
case 0x00: // Introduction date
ei->base_intro = buf->ReadWord() + CalTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
break;
case 0x02: // Decay speed
ei->decay_speed = buf->ReadByte();
break;
case 0x03: // Vehicle life
ei->lifelength = buf->ReadByte();
break;
case 0x04: // Model life
ei->base_life = buf->ReadByte();
break;
case 0x06: // Climates available
ei->climates = buf->ReadByte();
break;
case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
/* Amount of cargo loaded during a vehicle's "loading tick" */
ei->load_amount = buf->ReadByte();
break;
default:
return HandleAction0PropertyDefault(buf, prop);
}
return CIR_SUCCESS;
}
/**
* Define properties for rail vehicles
* @param engine :ocal ID of the first vehicle.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
RailVehicleInfo *rvi = &e->u.rail;
switch (prop) {
case 0x05: { // Track type
uint8_t tracktype = buf->ReadByte();
if (tracktype < _cur.grffile->railtype_list.size()) {
_gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
break;
}
switch (tracktype) {
case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_LABEL_ELECTRIC : RAILTYPE_LABEL_RAIL; break;
case 1: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MONO; break;
case 2: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MAGLEV; break;
default:
grfmsg(1, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring", tracktype);
break;
}
break;
}
case 0x08: // AI passenger service
/* Tells the AI that this engine is designed for
* passenger services and shouldn't be used for freight. */
rvi->ai_passenger_only = buf->ReadByte();
break;
case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
uint16_t speed = buf->ReadWord();
if (speed == 0xFFFF) speed = 0;
rvi->max_speed = speed;
break;
}
case PROP_TRAIN_POWER: // 0x0B Power
rvi->power = buf->ReadWord();
/* Set engine / wagon state based on power */
if (rvi->power != 0) {
if (rvi->railveh_type == RAILVEH_WAGON) {
rvi->railveh_type = RAILVEH_SINGLEHEAD;
}
} else {
rvi->railveh_type = RAILVEH_WAGON;
}
break;
case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
rvi->running_cost = buf->ReadByte();
break;
case 0x0E: // Running cost base
ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
break;
case 0x12: { // Sprite ID
uint8_t spriteid = buf->ReadByte();
uint8_t orig_spriteid = spriteid;
/* TTD sprite IDs point to a location in a 16bit array, but we use it
* as an array index, so we need it to be half the original value. */
if (spriteid < 0xFD) spriteid >>= 1;
if (IsValidNewGRFImageIndex(spriteid)) {
rvi->image_index = spriteid;
} else {
grfmsg(1, "RailVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
rvi->image_index = 0;
}
break;
}
case 0x13: { // Dual-headed
uint8_t dual = buf->ReadByte();
if (dual != 0) {
rvi->railveh_type = RAILVEH_MULTIHEAD;
} else {
rvi->railveh_type = rvi->power == 0 ?
RAILVEH_WAGON : RAILVEH_SINGLEHEAD;
}
break;
}
case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
rvi->capacity = buf->ReadByte();
break;
case 0x15: { // Cargo type
_gted[e->index].defaultcargo_grf = _cur.grffile;
uint8_t ctype = buf->ReadByte();
if (ctype == 0xFF) {
/* 0xFF is specified as 'use first refittable' */
ei->cargo_type = INVALID_CARGO;
} else if (_cur.grffile->grf_version >= 8) {
/* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
} else if (ctype < NUM_CARGO) {
/* Use untranslated cargo. */
ei->cargo_type = ctype;
} else {
ei->cargo_type = INVALID_CARGO;
grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
}
ei->cargo_label = CT_INVALID;
break;
}
case PROP_TRAIN_WEIGHT: // 0x16 Weight
SB(rvi->weight, 0, 8, buf->ReadByte());
break;
case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
rvi->cost_factor = buf->ReadByte();
break;
case 0x18: // AI rank
grfmsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
buf->ReadByte();
break;
case 0x19: { // Engine traction type
/* What do the individual numbers mean?
* 0x00 .. 0x07: Steam
* 0x08 .. 0x27: Diesel
* 0x28 .. 0x31: Electric
* 0x32 .. 0x37: Monorail
* 0x38 .. 0x41: Maglev
*/
uint8_t traction = buf->ReadByte();
EngineClass engclass;
if (traction <= 0x07) {
engclass = EC_STEAM;
} else if (traction <= 0x27) {
engclass = EC_DIESEL;
} else if (traction <= 0x31) {
engclass = EC_ELECTRIC;
} else if (traction <= 0x37) {
engclass = EC_MONORAIL;
} else if (traction <= 0x41) {
engclass = EC_MAGLEV;
} else {
break;
}
if (_cur.grffile->railtype_list.empty()) {
/* Use traction type to select between normal and electrified
* rail only when no translation list is in place. */
if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_RAIL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_ELECTRIC;
if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_ELECTRIC && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_RAIL;
}
rvi->engclass = engclass;
break;
}
case 0x1A: // Alter purchase list sort order
AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
break;
case 0x1B: // Powered wagons power bonus
rvi->pow_wag_power = buf->ReadWord();
break;
case 0x1C: // Refit cost
ei->refit_cost = buf->ReadByte();
break;
case 0x1D: { // Refit cargo
uint32_t mask = buf->ReadDWord();
_gted[e->index].UpdateRefittability(mask != 0);
ei->refit_mask = TranslateRefitMask(mask);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
}
case 0x1E: // Callback
SB(ei->callback_mask, 0, 8, buf->ReadByte());
break;
case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
rvi->tractive_effort = buf->ReadByte();
break;
case 0x20: // Air drag
rvi->air_drag = buf->ReadByte();
break;
case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
rvi->shorten_factor = buf->ReadByte();
break;
case 0x22: // Visual effect
rvi->visual_effect = buf->ReadByte();
/* Avoid accidentally setting visual_effect to the default value
* Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
if (rvi->visual_effect == VE_DEFAULT) {
assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
}
break;
case 0x23: // Powered wagons weight bonus
rvi->pow_wag_weight = buf->ReadByte();
break;
case 0x24: { // High byte of vehicle weight
byte weight = buf->ReadByte();
if (weight > 4) {
grfmsg(2, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring", weight << 8);
} else {
SB(rvi->weight, 8, 8, weight);
}
break;
}
case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
rvi->user_def_data = buf->ReadByte();
break;
case 0x26: // Retire vehicle early
ei->retire_early = buf->ReadByte();
break;
case 0x27: // Miscellaneous flags
ei->misc_flags = buf->ReadByte();
_loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
break;
case 0x28: // Cargo classes allowed
_gted[e->index].cargo_allowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
case 0x29: // Cargo classes disallowed
_gted[e->index].cargo_disallowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(false);
break;
case 0x2A: // Long format introduction date (days since year 0)
ei->base_intro = buf->ReadDWord();
break;
case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
ei->cargo_age_period = buf->ReadWord();
break;
case 0x2C: // CTT refit include list
case 0x2D: { // CTT refit exclude list
uint8_t count = buf->ReadByte();
_gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
ctt = 0;
while (count--) {
CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
if (ctype == INVALID_CARGO) continue;
SetBit(ctt, ctype);
}
break;
}
case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
rvi->curve_speed_mod = buf->ReadWord();
break;
case 0x2F: // Engine variant
ei->variant_id = buf->ReadWord();
break;
case 0x30: // Extra miscellaneous flags
ei->extra_flags = static_cast(buf->ReadDWord());
break;
case 0x31: // Callback additional mask
SB(ei->callback_mask, 8, 8, buf->ReadByte());
break;
default:
ret = CommonVehicleChangeInfo(ei, prop, mapping_entry, buf);
break;
}
}
return ret;
}
/**
* Define properties for road vehicles
* @param engine Local ID of the first vehicle.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
RoadVehicleInfo *rvi = &e->u.road;
switch (prop) {
case 0x05: // Road/tram type
/* RoadTypeLabel is looked up later after the engine's road/tram
* flag is set, however 0 means the value has not been set. */
_gted[e->index].roadtramtype = buf->ReadByte() + 1;
break;
case 0x08: // Speed (1 unit is 0.5 kmh)
rvi->max_speed = buf->ReadByte();
break;
case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
rvi->running_cost = buf->ReadByte();
break;
case 0x0A: // Running cost base
ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
break;
case 0x0E: { // Sprite ID
uint8_t spriteid = buf->ReadByte();
uint8_t orig_spriteid = spriteid;
/* cars have different custom id in the GRF file */
if (spriteid == 0xFF) spriteid = 0xFD;
if (spriteid < 0xFD) spriteid >>= 1;
if (IsValidNewGRFImageIndex(spriteid)) {
rvi->image_index = spriteid;
} else {
grfmsg(1, "RoadVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
rvi->image_index = 0;
}
break;
}
case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
rvi->capacity = buf->ReadByte();
break;
case 0x10: { // Cargo type
_gted[e->index].defaultcargo_grf = _cur.grffile;
uint8_t ctype = buf->ReadByte();
if (ctype == 0xFF) {
/* 0xFF is specified as 'use first refittable' */
ei->cargo_type = INVALID_CARGO;
} else if (_cur.grffile->grf_version >= 8) {
/* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
} else if (ctype < NUM_CARGO) {
/* Use untranslated cargo. */
ei->cargo_type = ctype;
} else {
ei->cargo_type = INVALID_CARGO;
grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
}
ei->cargo_label = CT_INVALID;
break;
}
case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
rvi->cost_factor = buf->ReadByte();
break;
case 0x12: // SFX
rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
break;
case PROP_ROADVEH_POWER: // Power in units of 10 HP.
rvi->power = buf->ReadByte();
break;
case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
rvi->weight = buf->ReadByte();
break;
case PROP_ROADVEH_SPEED: // Speed in mph/0.8
_gted[e->index].rv_max_speed = buf->ReadByte();
break;
case 0x16: { // Cargoes available for refitting
uint32_t mask = buf->ReadDWord();
_gted[e->index].UpdateRefittability(mask != 0);
ei->refit_mask = TranslateRefitMask(mask);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
}
case 0x17: // Callback mask
SB(ei->callback_mask, 0, 8, buf->ReadByte());
break;
case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
rvi->tractive_effort = buf->ReadByte();
break;
case 0x19: // Air drag
rvi->air_drag = buf->ReadByte();
break;
case 0x1A: // Refit cost
ei->refit_cost = buf->ReadByte();
break;
case 0x1B: // Retire vehicle early
ei->retire_early = buf->ReadByte();
break;
case 0x1C: // Miscellaneous flags
ei->misc_flags = buf->ReadByte();
_loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
break;
case 0x1D: // Cargo classes allowed
_gted[e->index].cargo_allowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
case 0x1E: // Cargo classes disallowed
_gted[e->index].cargo_disallowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(false);
break;
case 0x1F: // Long format introduction date (days since year 0)
ei->base_intro = buf->ReadDWord();
break;
case 0x20: // Alter purchase list sort order
AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
break;
case 0x21: // Visual effect
rvi->visual_effect = buf->ReadByte();
/* Avoid accidentally setting visual_effect to the default value
* Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
if (rvi->visual_effect == VE_DEFAULT) {
assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
}
break;
case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
ei->cargo_age_period = buf->ReadWord();
break;
case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
rvi->shorten_factor = buf->ReadByte();
break;
case 0x24: // CTT refit include list
case 0x25: { // CTT refit exclude list
uint8_t count = buf->ReadByte();
_gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
ctt = 0;
while (count--) {
CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
if (ctype == INVALID_CARGO) continue;
SetBit(ctt, ctype);
}
break;
}
case 0x26: // Engine variant
ei->variant_id = buf->ReadWord();
break;
case 0x27: // Extra miscellaneous flags
ei->extra_flags = static_cast(buf->ReadDWord());
break;
case 0x28: // Callback additional mask
SB(ei->callback_mask, 8, 8, buf->ReadByte());
break;
default:
ret = CommonVehicleChangeInfo(ei, prop, mapping_entry, buf);
break;
}
}
return ret;
}
/**
* Define properties for ships
* @param engine Local ID of the first vehicle.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
ShipVehicleInfo *svi = &e->u.ship;
switch (prop) {
case 0x08: { // Sprite ID
uint8_t spriteid = buf->ReadByte();
uint8_t orig_spriteid = spriteid;
/* ships have different custom id in the GRF file */
if (spriteid == 0xFF) spriteid = 0xFD;
if (spriteid < 0xFD) spriteid >>= 1;
if (IsValidNewGRFImageIndex(spriteid)) {
svi->image_index = spriteid;
} else {
grfmsg(1, "ShipVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
svi->image_index = 0;
}
break;
}
case 0x09: // Refittable
svi->old_refittable = (buf->ReadByte() != 0);
break;
case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
svi->cost_factor = buf->ReadByte();
break;
case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h). Use 0x23 to achieve higher speeds.
svi->max_speed = buf->ReadByte();
break;
case 0x0C: { // Cargo type
_gted[e->index].defaultcargo_grf = _cur.grffile;
uint8_t ctype = buf->ReadByte();
if (ctype == 0xFF) {
/* 0xFF is specified as 'use first refittable' */
ei->cargo_type = INVALID_CARGO;
} else if (_cur.grffile->grf_version >= 8) {
/* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
} else if (ctype < NUM_CARGO) {
/* Use untranslated cargo. */
ei->cargo_type = ctype;
} else {
ei->cargo_type = INVALID_CARGO;
grfmsg(2, "ShipVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
}
ei->cargo_label = CT_INVALID;
break;
}
case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
svi->capacity = buf->ReadWord();
break;
case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
svi->running_cost = buf->ReadByte();
break;
case 0x10: // SFX
svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
break;
case 0x11: { // Cargoes available for refitting
uint32_t mask = buf->ReadDWord();
_gted[e->index].UpdateRefittability(mask != 0);
ei->refit_mask = TranslateRefitMask(mask);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
}
case 0x12: // Callback mask
SB(ei->callback_mask, 0, 8, buf->ReadByte());
break;
case 0x13: // Refit cost
ei->refit_cost = buf->ReadByte();
break;
case 0x14: // Ocean speed fraction
svi->ocean_speed_frac = buf->ReadByte();
break;
case 0x15: // Canal speed fraction
svi->canal_speed_frac = buf->ReadByte();
break;
case 0x16: // Retire vehicle early
ei->retire_early = buf->ReadByte();
break;
case 0x17: // Miscellaneous flags
ei->misc_flags = buf->ReadByte();
_loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
break;
case 0x18: // Cargo classes allowed
_gted[e->index].cargo_allowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
case 0x19: // Cargo classes disallowed
_gted[e->index].cargo_disallowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(false);
break;
case 0x1A: // Long format introduction date (days since year 0)
ei->base_intro = buf->ReadDWord();
break;
case 0x1B: // Alter purchase list sort order
AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
break;
case 0x1C: // Visual effect
svi->visual_effect = buf->ReadByte();
/* Avoid accidentally setting visual_effect to the default value
* Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
if (svi->visual_effect == VE_DEFAULT) {
assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
SB(svi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
}
break;
case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
ei->cargo_age_period = buf->ReadWord();
break;
case 0x1E: // CTT refit include list
case 0x1F: { // CTT refit exclude list
uint8_t count = buf->ReadByte();
_gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
ctt = 0;
while (count--) {
CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
if (ctype == INVALID_CARGO) continue;
SetBit(ctt, ctype);
}
break;
}
case 0x20: // Engine variant
ei->variant_id = buf->ReadWord();
break;
case 0x21: // Extra miscellaneous flags
ei->extra_flags = static_cast(buf->ReadDWord());
break;
case 0x22: // Callback additional mask
SB(ei->callback_mask, 8, 8, buf->ReadByte());
break;
case 0x23: // Speed (1 unit is 0.5 km-ish/h)
svi->max_speed = buf->ReadWord();
break;
case 0x24: // Acceleration (1 unit is 0.5 km-ish/h per tick)
svi->acceleration = std::max(1, buf->ReadByte());
break;
default:
ret = CommonVehicleChangeInfo(ei, prop, mapping_entry, buf);
break;
}
}
return ret;
}
/**
* Define properties for aircraft
* @param engine Local ID of the aircraft.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
EngineInfo *ei = &e->info;
AircraftVehicleInfo *avi = &e->u.air;
switch (prop) {
case 0x08: { // Sprite ID
uint8_t spriteid = buf->ReadByte();
uint8_t orig_spriteid = spriteid;
/* aircraft have different custom id in the GRF file */
if (spriteid == 0xFF) spriteid = 0xFD;
if (spriteid < 0xFD) spriteid >>= 1;
if (IsValidNewGRFImageIndex(spriteid)) {
avi->image_index = spriteid;
} else {
grfmsg(1, "AircraftVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
avi->image_index = 0;
}
break;
}
case 0x09: // Helicopter
if (buf->ReadByte() == 0) {
avi->subtype = AIR_HELI;
} else {
SB(avi->subtype, 0, 1, 1); // AIR_CTOL
}
break;
case 0x0A: // Large
SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
break;
case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
avi->cost_factor = buf->ReadByte();
break;
case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
avi->max_speed = (buf->ReadByte() * 128) / 10;
break;
case 0x0D: // Acceleration
avi->acceleration = buf->ReadByte();
break;
case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
avi->running_cost = buf->ReadByte();
break;
case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
avi->passenger_capacity = buf->ReadWord();
break;
case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
avi->mail_capacity = buf->ReadByte();
break;
case 0x12: // SFX
avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
break;
case 0x13: { // Cargoes available for refitting
uint32_t mask = buf->ReadDWord();
_gted[e->index].UpdateRefittability(mask != 0);
ei->refit_mask = TranslateRefitMask(mask);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
}
case 0x14: // Callback mask
SB(ei->callback_mask, 0, 8, buf->ReadByte());
break;
case 0x15: // Refit cost
ei->refit_cost = buf->ReadByte();
break;
case 0x16: // Retire vehicle early
ei->retire_early = buf->ReadByte();
break;
case 0x17: // Miscellaneous flags
ei->misc_flags = buf->ReadByte();
_loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
break;
case 0x18: // Cargo classes allowed
_gted[e->index].cargo_allowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
_gted[e->index].defaultcargo_grf = _cur.grffile;
break;
case 0x19: // Cargo classes disallowed
_gted[e->index].cargo_disallowed = buf->ReadWord();
_gted[e->index].UpdateRefittability(false);
break;
case 0x1A: // Long format introduction date (days since year 0)
ei->base_intro = buf->ReadDWord();
break;
case 0x1B: // Alter purchase list sort order
AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
break;
case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
ei->cargo_age_period = buf->ReadWord();
break;
case 0x1D: // CTT refit include list
case 0x1E: { // CTT refit exclude list
uint8_t count = buf->ReadByte();
_gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
ctt = 0;
while (count--) {
CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
if (ctype == INVALID_CARGO) continue;
SetBit(ctt, ctype);
}
break;
}
case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
avi->max_range = buf->ReadWord();
break;
case 0x20: // Engine variant
ei->variant_id = buf->ReadWord();
break;
case 0x21: // Extra miscellaneous flags
ei->extra_flags = static_cast(buf->ReadDWord());
break;
case 0x22: // Callback additional mask
SB(ei->callback_mask, 8, 8, buf->ReadByte());
break;
default:
ret = CommonVehicleChangeInfo(ei, prop, mapping_entry, buf);
break;
}
}
return ret;
}
/**
* Define properties for stations
* @param stid StationID of the first station tile.
* @param numinfo Number of subsequent station tiles to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (stid + numinfo > NUM_STATIONS_PER_GRF) {
grfmsg(1, "StationChangeInfo: Station %u is invalid, max %u, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
return CIR_INVALID_ID;
}
/* Allocate station specs if necessary */
if (_cur.grffile->stations.size() < stid + numinfo) _cur.grffile->stations.resize(stid + numinfo);
for (int i = 0; i < numinfo; i++) {
StationSpec *statspec = _cur.grffile->stations[stid + i].get();
/* Check that the station we are modifying is defined. */
if (statspec == nullptr && prop != 0x08) {
grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
return CIR_INVALID_ID;
}
switch (prop) {
case 0x08: { // Class ID
/* Property 0x08 is special; it is where the station is allocated */
if (statspec == nullptr) {
_cur.grffile->stations[stid + i] = std::make_unique();
statspec = _cur.grffile->stations[stid + i].get();
}
/* Swap classid because we read it in BE meaning WAYP or DFLT */
uint32_t classid = buf->ReadDWord();
statspec->cls_id = StationClass::Allocate(BSWAP32(classid));
break;
}
case 0x09: { // Define sprite layout
uint16_t tiles = buf->ReadExtendedByte();
statspec->renderdata.clear(); // delete earlier loaded stuff
statspec->renderdata.reserve(tiles);
for (uint t = 0; t < tiles; t++) {
NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
if (buf->HasData(4) && *(unaligned_uint32*)buf->Data() == 0) {
buf->Skip(4);
extern const DrawTileSprites _station_display_datas_rail[8];
dts->Clone(&_station_display_datas_rail[t % 8]);
continue;
}
ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
/* On error, bail out immediately. Temporary GRF data was already freed */
if (_cur.skip_sprites < 0) return CIR_DISABLED;
static std::vector tmp_layout;
tmp_layout.clear();
for (;;) {
/* no relative bounding box support */
DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
MemSetT(&dtss, 0);
dtss.delta_x = buf->ReadByte();
if (dtss.IsTerminator()) break;
dtss.delta_y = buf->ReadByte();
dtss.delta_z = buf->ReadByte();
dtss.size_x = buf->ReadByte();
dtss.size_y = buf->ReadByte();
dtss.size_z = buf->ReadByte();
ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
/* On error, bail out immediately. Temporary GRF data was already freed */
if (_cur.skip_sprites < 0) return CIR_DISABLED;
}
dts->Clone(tmp_layout.data());
}
/* Number of layouts must be even, alternating X and Y */
if (statspec->renderdata.size() & 1) {
grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
statspec->renderdata.pop_back();
}
break;
}
case 0x0A: { // Copy sprite layout
uint16_t srcid = buf->ReadExtendedByte();
const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
if (srcstatspec == nullptr) {
grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy sprite layout to %u.", srcid, stid + i);
continue;
}
statspec->renderdata.clear(); // delete earlier loaded stuff
statspec->renderdata.reserve(srcstatspec->renderdata.size());
for (const auto &it : srcstatspec->renderdata) {
NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
dts->Clone(&it);
}
break;
}
case 0x0B: // Callback mask
statspec->callback_mask = buf->ReadByte();
break;
case 0x0C: // Disallowed number of platforms
statspec->disallowed_platforms = buf->ReadByte();
break;
case 0x0D: // Disallowed platform lengths
statspec->disallowed_lengths = buf->ReadByte();
break;
case 0x0E: // Define custom layout
while (buf->HasData()) {
byte length = buf->ReadByte();
byte number = buf->ReadByte();
if (length == 0 || number == 0) break;
if (statspec->layouts.size() < length) statspec->layouts.resize(length);
if (statspec->layouts[length - 1].size() < number) statspec->layouts[length - 1].resize(number);
const byte *layout = buf->ReadBytes(length * number);
statspec->layouts[length - 1][number - 1].assign(layout, layout + length * number);
/* Validate tile values are only the permitted 00, 02, 04 and 06. */
for (auto &tile : statspec->layouts[length - 1][number - 1]) {
if ((tile & 6) != tile) {
grfmsg(1, "StationChangeInfo: Invalid tile %u in layout %ux%u", tile, length, number);
tile &= 6;
}
}
}
break;
case 0x0F: { // Copy custom layout
uint16_t srcid = buf->ReadExtendedByte();
const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
if (srcstatspec == nullptr) {
grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy tile layout to %u.", srcid, stid + i);
continue;
}
statspec->layouts = srcstatspec->layouts;
break;
}
case 0x10: // Little/lots cargo threshold
statspec->cargo_threshold = buf->ReadWord();
break;
case 0x11: // Pylon placement
statspec->pylons = buf->ReadByte();
break;
case 0x12: // Cargo types for random triggers
if (_cur.grffile->grf_version >= 7) {
statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
} else {
statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
}
break;
case 0x13: // General flags
statspec->flags = buf->ReadByte();
break;
case 0x14: // Overhead wire placement
statspec->wires = buf->ReadByte();
break;
case 0x15: // Blocked tiles
statspec->blocked = buf->ReadByte();
break;
case 0x16: // Animation info
statspec->animation.frames = buf->ReadByte();
statspec->animation.status = buf->ReadByte();
break;
case 0x17: // Animation speed
statspec->animation.speed = buf->ReadByte();
break;
case 0x18: // Animation triggers
statspec->animation.triggers = buf->ReadWord();
break;
/* 0x19 road routing (not implemented) */
case 0x1A: { // Advanced sprite layout
uint16_t tiles = buf->ReadExtendedByte();
statspec->renderdata.clear(); // delete earlier loaded stuff
statspec->renderdata.reserve(tiles);
for (uint t = 0; t < tiles; t++) {
NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
uint num_building_sprites = buf->ReadByte();
/* On error, bail out immediately. Temporary GRF data was already freed */
if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
}
/* Number of layouts must be even, alternating X and Y */
if (statspec->renderdata.size() & 1) {
grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
statspec->renderdata.pop_back();
}
break;
}
case A0RPI_STATION_MIN_BRIDGE_HEIGHT:
if (MappedPropertyLengthMismatch(buf, 8, mapping_entry)) break;
[[fallthrough]];
case 0x1B: // Minimum height for a bridge above
SetBit(statspec->internal_flags, SSIF_BRIDGE_HEIGHTS_SET);
for (uint i = 0; i < 8; i++) {
statspec->bridge_height[i] = buf->ReadByte();
}
break;
case A0RPI_STATION_DISALLOWED_BRIDGE_PILLARS:
if (MappedPropertyLengthMismatch(buf, 8, mapping_entry)) break;
SetBit(statspec->internal_flags, SSIF_BRIDGE_DISALLOWED_PILLARS_SET);
for (uint i = 0; i < 8; i++) {
statspec->bridge_disallowed_pillars[i] = buf->ReadByte();
}
break;
case 0x1C: // Station Name
AddStringForMapping(buf->ReadWord(), &statspec->name);
break;
case 0x1D: // Station Class name
AddStringForMapping(buf->ReadWord(), &StationClass::Get(statspec->cls_id)->name);
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for water features
* @param id Type of the first water feature.
* @param numinfo Number of subsequent water feature ids to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (id + numinfo > CF_END) {
grfmsg(1, "CanalChangeInfo: Canal feature 0x%02X is invalid, max %u, ignoring", id + numinfo, CF_END);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
switch (prop) {
case 0x08:
cp->callback_mask = buf->ReadByte();
break;
case 0x09:
cp->flags = buf->ReadByte();
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for bridges
* @param brid BridgeID of the bridge.
* @param numinfo Number of subsequent bridgeIDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (brid + numinfo > MAX_BRIDGES) {
grfmsg(1, "BridgeChangeInfo: Bridge %u is invalid, max %u, ignoring", brid + numinfo, MAX_BRIDGES);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
BridgeSpec *bridge = &_bridge[brid + i];
switch (prop) {
case 0x08: { // Year of availability
/* We treat '0' as always available */
byte year = buf->ReadByte();
bridge->avail_year = (year > 0 ? CalTime::ORIGINAL_BASE_YEAR + year : 0);
break;
}
case 0x09: // Minimum length
bridge->min_length = buf->ReadByte();
break;
case 0x0A: // Maximum length
bridge->max_length = buf->ReadByte();
if (bridge->max_length > 16) bridge->max_length = UINT16_MAX;
break;
case 0x0B: // Cost factor
bridge->price = buf->ReadByte();
break;
case 0x0C: // Maximum speed
bridge->speed = buf->ReadWord();
if (bridge->speed == 0) bridge->speed = UINT16_MAX;
break;
case 0x0D: { // Bridge sprite tables
byte tableid = buf->ReadByte();
byte numtables = buf->ReadByte();
if (bridge->sprite_table == nullptr) {
/* Allocate memory for sprite table pointers and zero out */
bridge->sprite_table = CallocT(7);
}
for (; numtables-- != 0; tableid++) {
if (tableid >= 7) { // skip invalid data
grfmsg(1, "BridgeChangeInfo: Table %d >= 7, skipping", tableid);
for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
continue;
}
if (bridge->sprite_table[tableid] == nullptr) {
bridge->sprite_table[tableid] = MallocT(32);
}
for (byte sprite = 0; sprite < 32; sprite++) {
SpriteID image = buf->ReadWord();
PaletteID pal = buf->ReadWord();
bridge->sprite_table[tableid][sprite].sprite = image;
bridge->sprite_table[tableid][sprite].pal = pal;
MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
}
}
if (!HasBit(bridge->ctrl_flags, BSCF_CUSTOM_PILLAR_FLAGS)) SetBit(bridge->ctrl_flags, BSCF_INVALID_PILLAR_FLAGS);
break;
}
case 0x0E: // Flags; bit 0 - disable far pillars
bridge->flags = buf->ReadByte();
break;
case 0x0F: // Long format year of availability (year since year 0)
bridge->avail_year = Clamp(buf->ReadDWord(), CalTime::MIN_YEAR, CalTime::MAX_YEAR);
break;
case 0x10: { // purchase string
StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
if (newone != STR_UNDEFINED) bridge->material = newone;
break;
}
case 0x11: // description of bridge with rails or roads
case 0x12: {
StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
break;
}
case 0x13: // 16 bits cost multiplier
bridge->price = buf->ReadWord();
break;
case A0RPI_BRIDGE_MENU_ICON:
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
[[fallthrough]];
case 0x14: // purchase sprite
bridge->sprite = buf->ReadWord();
bridge->pal = buf->ReadWord();
break;
case A0RPI_BRIDGE_PILLAR_FLAGS:
if (MappedPropertyLengthMismatch(buf, 12, mapping_entry)) break;
for (uint i = 0; i < 12; i++) {
bridge->pillar_flags[i] = buf->ReadByte();
}
ClrBit(bridge->ctrl_flags, BSCF_INVALID_PILLAR_FLAGS);
SetBit(bridge->ctrl_flags, BSCF_CUSTOM_PILLAR_FLAGS);
break;
case A0RPI_BRIDGE_AVAILABILITY_FLAGS: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
byte flags = buf->ReadByte();
SB(bridge->ctrl_flags, BSCF_NOT_AVAILABLE_TOWN, 1, HasBit(flags, 0) ? 1 : 0);
SB(bridge->ctrl_flags, BSCF_NOT_AVAILABLE_AI_GS, 1, HasBit(flags, 1) ? 1 : 0);
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Ignore a house property
* @param prop Property to read.
* @param buf Property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
switch (prop) {
case 0x09:
case 0x0B:
case 0x0C:
case 0x0D:
case 0x0E:
case 0x0F:
case 0x11:
case 0x14:
case 0x15:
case 0x16:
case 0x18:
case 0x19:
case 0x1A:
case 0x1B:
case 0x1C:
case 0x1D:
case 0x1F:
buf->ReadByte();
break;
case 0x0A:
case 0x10:
case 0x12:
case 0x13:
case 0x21:
case 0x22:
buf->ReadWord();
break;
case 0x1E:
buf->ReadDWord();
break;
case 0x17:
for (uint j = 0; j < 4; j++) buf->ReadByte();
break;
case 0x20: {
byte count = buf->ReadByte();
for (byte j = 0; j < count; j++) buf->ReadByte();
break;
}
case 0x23:
buf->Skip(buf->ReadByte() * 2);
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
return ret;
}
/**
* Define properties for houses
* @param hid HouseID of the house.
* @param numinfo Number of subsequent houseIDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (hid + numinfo > NUM_HOUSES_PER_GRF) {
grfmsg(1, "TownHouseChangeInfo: Too many houses loaded (%u), max (%u). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
return CIR_INVALID_ID;
}
/* Allocate house specs if they haven't been allocated already. */
if (_cur.grffile->housespec.size() < hid + numinfo) _cur.grffile->housespec.resize(hid + numinfo);
for (int i = 0; i < numinfo; i++) {
HouseSpec *housespec = _cur.grffile->housespec[hid + i].get();
if (prop != 0x08 && housespec == nullptr) {
/* If the house property 08 is not yet set, ignore this property */
ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
if (cir > ret) ret = cir;
continue;
}
switch (prop) {
case 0x08: { // Substitute building type, and definition of a new house
byte subs_id = buf->ReadByte();
if (subs_id == 0xFF) {
/* Instead of defining a new house, a substitute house id
* of 0xFF disables the old house with the current id. */
if (hid + i < NEW_HOUSE_OFFSET) HouseSpec::Get(hid + i)->enabled = false;
continue;
} else if (subs_id >= NEW_HOUSE_OFFSET) {
/* The substitute id must be one of the original houses. */
grfmsg(2, "TownHouseChangeInfo: Attempt to use new house %u as substitute house for %u. Ignoring.", subs_id, hid + i);
continue;
}
/* Allocate space for this house. */
if (housespec == nullptr) {
/* Only the first property 08 setting copies properties; if you later change it, properties will stay. */
_cur.grffile->housespec[hid + i] = std::make_unique(*HouseSpec::Get(subs_id));
housespec = _cur.grffile->housespec[hid + i].get();
housespec->enabled = true;
housespec->grf_prop.local_id = hid + i;
housespec->grf_prop.subst_id = subs_id;
housespec->grf_prop.grffile = _cur.grffile;
/* Set default colours for randomization, used if not overridden. */
housespec->random_colour[0] = COLOUR_RED;
housespec->random_colour[1] = COLOUR_BLUE;
housespec->random_colour[2] = COLOUR_ORANGE;
housespec->random_colour[3] = COLOUR_GREEN;
/* House flags 40 and 80 are exceptions; these flags are never set automatically. */
housespec->building_flags &= ~(BUILDING_IS_CHURCH | BUILDING_IS_STADIUM);
/* Make sure that the third cargo type is valid in this
* climate. This can cause problems when copying the properties
* of a house that accepts food, where the new house is valid
* in the temperate climate. */
CargoID cid = housespec->accepts_cargo[2];
if (!IsValidCargoID(cid)) cid = GetCargoIDByLabel(housespec->accepts_cargo_label[2]);
if (!IsValidCargoID(cid)) {
housespec->cargo_acceptance[2] = 0;
}
}
break;
}
case 0x09: // Building flags
housespec->building_flags = (BuildingFlags)buf->ReadByte();
break;
case 0x0A: { // Availability years
uint16_t years = buf->ReadWord();
housespec->min_year = GB(years, 0, 8) > 150 ? CalTime::MAX_YEAR : CalTime::ORIGINAL_BASE_YEAR + GB(years, 0, 8);
housespec->max_year = GB(years, 8, 8) > 150 ? CalTime::MAX_YEAR : CalTime::ORIGINAL_BASE_YEAR + GB(years, 8, 8);
break;
}
case 0x0B: // Population
housespec->population = buf->ReadByte();
break;
case 0x0C: // Mail generation multiplier
housespec->mail_generation = buf->ReadByte();
break;
case 0x0D: // Passenger acceptance
case 0x0E: // Mail acceptance
housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
break;
case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
int8_t goods = buf->ReadByte();
/* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
* Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_CANDY) : GetCargoIDByLabel(CT_GOODS)) :
((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_FIZZY_DRINKS) : GetCargoIDByLabel(CT_FOOD));
/* Make sure the cargo type is valid in this climate. */
if (!IsValidCargoID(cid)) goods = 0;
housespec->accepts_cargo[2] = cid;
housespec->accepts_cargo_label[2] = CT_INVALID;
housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
break;
}
case 0x10: // Local authority rating decrease on removal
housespec->remove_rating_decrease = buf->ReadWord();
break;
case 0x11: // Removal cost multiplier
housespec->removal_cost = buf->ReadByte();
break;
case 0x12: // Building name ID
AddStringForMapping(buf->ReadWord(), &housespec->building_name);
break;
case 0x13: // Building availability mask
housespec->building_availability = (HouseZones)buf->ReadWord();
break;
case 0x14: // House callback mask
housespec->callback_mask |= buf->ReadByte();
break;
case 0x15: { // House override byte
byte override = buf->ReadByte();
/* The house being overridden must be an original house. */
if (override >= NEW_HOUSE_OFFSET) {
grfmsg(2, "TownHouseChangeInfo: Attempt to override new house %u with house id %u. Ignoring.", override, hid + i);
continue;
}
_house_mngr.Add(hid + i, _cur.grffile->grfid, override);
break;
}
case 0x16: // Periodic refresh multiplier
housespec->processing_time = std::min(buf->ReadByte(), 63u);
break;
case 0x17: // Four random colours to use
for (uint j = 0; j < 4; j++) housespec->random_colour[j] = static_cast(GB(buf->ReadByte(), 0, 4));
break;
case 0x18: // Relative probability of appearing
housespec->probability = buf->ReadByte();
break;
case 0x19: // Extra flags
housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
break;
case 0x1A: // Animation frames
housespec->animation.frames = buf->ReadByte();
housespec->animation.status = GB(housespec->animation.frames, 7, 1);
SB(housespec->animation.frames, 7, 1, 0);
break;
case 0x1B: // Animation speed
housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
break;
case 0x1C: // Class of the building type
housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
break;
case 0x1D: // Callback mask part 2
housespec->callback_mask |= (buf->ReadByte() << 8);
break;
case 0x1E: { // Accepted cargo types
uint32_t cargotypes = buf->ReadDWord();
/* Check if the cargo types should not be changed */
if (cargotypes == 0xFFFFFFFF) break;
for (uint j = 0; j < 3; j++) {
/* Get the cargo number from the 'list' */
uint8_t cargo_part = GB(cargotypes, 8 * j, 8);
CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
if (cargo == INVALID_CARGO) {
/* Disable acceptance of invalid cargo type */
housespec->cargo_acceptance[j] = 0;
} else {
housespec->accepts_cargo[j] = cargo;
}
}
break;
}
case 0x1F: // Minimum life span
housespec->minimum_life = buf->ReadByte();
break;
case 0x20: { // Cargo acceptance watch list
byte count = buf->ReadByte();
for (byte j = 0; j < count; j++) {
CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
if (cargo != INVALID_CARGO) SetBit(housespec->watched_cargoes, cargo);
}
break;
}
case 0x21: // long introduction year
housespec->min_year = buf->ReadWord();
break;
case 0x22: // long maximum year
housespec->max_year = buf->ReadWord();
break;
case 0x23: { // variable length cargo types accepted
uint count = buf->ReadByte();
if (count > lengthof(housespec->accepts_cargo)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop;
return CIR_DISABLED;
}
/* Always write the full accepts_cargo array, and check each index for being inside the
* provided data. This ensures all values are properly initialized, and also avoids
* any risks of array overrun. */
for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
if (i < count) {
housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
housespec->cargo_acceptance[i] = buf->ReadByte();
} else {
housespec->accepts_cargo[i] = INVALID_CARGO;
housespec->cargo_acceptance[i] = 0;
}
housespec->accepts_cargo_label[i] = CT_INVALID;
}
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Get the language map associated with a given NewGRF and language.
* @param grfid The NewGRF to get the map for.
* @param language_id The (NewGRF) language ID to get the map for.
* @return The LanguageMap, or nullptr if it couldn't be found.
*/
/* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32_t grfid, uint8_t language_id)
{
/* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
const GRFFile *grffile = GetFileByGRFID(grfid);
return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
}
/**
* Load a cargo- or railtype-translation table.
* @param gvid ID of the global variable. This is basically only checked for zerones.
* @param numinfo Number of subsequent IDs to change the property for.
* @param buf The property value.
* @param[in,out] translation_table Storage location for the translation table.
* @param name Name of the table for debug output.
* @return ChangeInfoResult.
*/
template
static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, std::vector &translation_table, const char *name)
{
if (gvid != 0) {
grfmsg(1, "LoadTranslationTable: %s translation table must start at zero", name);
return CIR_INVALID_ID;
}
translation_table.clear();
for (int i = 0; i < numinfo; i++) {
translation_table.push_back(T(BSWAP32(buf->ReadDWord())));
}
return CIR_SUCCESS;
}
/**
* Helper to read a DWord worth of bytes from the reader
* and to return it as a valid string.
* @param reader The source of the DWord.
* @return The read DWord as string.
*/
static std::string ReadDWordAsString(ByteReader *reader)
{
std::string output;
for (int i = 0; i < 4; i++) output.push_back(reader->ReadByte());
return StrMakeValid(output);
}
/**
* Define properties for global variables
* @param gvid ID of the global variable.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
/* Properties which are handled as a whole */
switch (prop) {
case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
default:
break;
}
/* Properties which are handled per item */
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
switch (prop) {
case 0x08: { // Cost base factor
int factor = buf->ReadByte();
uint price = gvid + i;
if (price < PR_END) {
_cur.grffile->price_base_multipliers[price] = std::min(factor - 8, MAX_PRICE_MODIFIER);
} else {
grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
}
break;
}
case 0x0A: { // Currency display names
uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
_currency_specs[curidx].name = newone;
_currency_specs[curidx].code.clear();
}
break;
}
case 0x0B: { // Currency multipliers
uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
uint32_t rate = buf->ReadDWord();
if (curidx < CURRENCY_END) {
/* TTDPatch uses a multiple of 1000 for its conversion calculations,
* which OTTD does not. For this reason, divide grf value by 1000,
* to be compatible */
_currency_specs[curidx].rate = rate / 1000;
} else {
grfmsg(1, "GlobalVarChangeInfo: Currency multipliers %d out of range, ignoring", curidx);
}
break;
}
case 0x0C: { // Currency options
uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
uint16_t options = buf->ReadWord();
if (curidx < CURRENCY_END) {
_currency_specs[curidx].separator.clear();
_currency_specs[curidx].separator.push_back(GB(options, 0, 8));
/* By specifying only one bit, we prevent errors,
* since newgrf specs said that only 0 and 1 can be set for symbol_pos */
_currency_specs[curidx].symbol_pos = GB(options, 8, 1);
} else {
grfmsg(1, "GlobalVarChangeInfo: Currency option %d out of range, ignoring", curidx);
}
break;
}
case 0x0D: { // Currency prefix symbol
uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
std::string prefix = ReadDWordAsString(buf);
if (curidx < CURRENCY_END) {
_currency_specs[curidx].prefix = prefix;
} else {
grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
}
break;
}
case 0x0E: { // Currency suffix symbol
uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
std::string suffix = ReadDWordAsString(buf);
if (curidx < CURRENCY_END) {
_currency_specs[curidx].suffix = suffix;
} else {
grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
}
break;
}
case 0x0F: { // Euro introduction dates
uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
CalTime::Year year_euro = buf->ReadWord();
if (curidx < CURRENCY_END) {
_currency_specs[curidx].to_euro = year_euro;
} else {
grfmsg(1, "GlobalVarChangeInfo: Euro intro date %d out of range, ignoring", curidx);
}
break;
}
case 0x10: // Snow line height table
if (numinfo > 1 || IsSnowLineSet()) {
grfmsg(1, "GlobalVarChangeInfo: The snowline can only be set once (%d)", numinfo);
} else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
grfmsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table (" PRINTF_SIZE ")", buf->Remaining());
} else {
byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
table[i][j] = buf->ReadByte();
if (_cur.grffile->grf_version >= 8) {
if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
} else {
if (table[i][j] >= 128) {
/* no snow */
table[i][j] = 0xFF;
} else {
table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
}
}
}
}
SetSnowLine(table);
}
break;
case 0x11: // GRF match for engine allocation
/* This is loaded during the reservation stage, so just skip it here. */
/* Each entry is 8 bytes. */
buf->Skip(8);
break;
case 0x13: // Gender translation table
case 0x14: // Case translation table
case 0x15: { // Plural form translation
uint curidx = gvid + i; // The current index, i.e. language.
const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
if (lang == nullptr) {
grfmsg(1, "GlobalVarChangeInfo: Language %d is not known, ignoring", curidx);
/* Skip over the data. */
if (prop == 0x15) {
buf->ReadByte();
} else {
while (buf->ReadByte() != 0) {
buf->ReadString();
}
}
break;
}
if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
if (prop == 0x15) {
uint plural_form = buf->ReadByte();
if (plural_form >= LANGUAGE_MAX_PLURAL) {
grfmsg(1, "GlobalVarChanceInfo: Plural form %d is out of range, ignoring", plural_form);
} else {
_cur.grffile->language_map[curidx].plural_form = plural_form;
}
break;
}
byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
while (newgrf_id != 0) {
const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
/* We'll just ignore the UTF8 identifier character. This is (fairly)
* safe as OpenTTD's strings gender/cases are usually in ASCII which
* is just a subset of UTF8, or they need the bigger UTF8 characters
* such as Cyrillic. Thus we will simply assume they're all UTF8. */
char32_t c;
size_t len = Utf8Decode(&c, name);
if (c == NFO_UTF8_IDENTIFIER) name += len;
LanguageMap::Mapping map;
map.newgrf_id = newgrf_id;
if (prop == 0x13) {
map.openttd_id = lang->GetGenderIndex(name);
if (map.openttd_id >= MAX_NUM_GENDERS) {
grfmsg(1, "GlobalVarChangeInfo: Gender name %s is not known, ignoring", name);
} else {
_cur.grffile->language_map[curidx].gender_map.push_back(map);
}
} else {
map.openttd_id = lang->GetCaseIndex(name);
if (map.openttd_id >= MAX_NUM_CASES) {
grfmsg(1, "GlobalVarChangeInfo: Case name %s is not known, ignoring", name);
} else {
_cur.grffile->language_map[curidx].case_map.push_back(map);
}
}
newgrf_id = buf->ReadByte();
}
break;
}
case A0RPI_GLOBALVAR_EXTRA_STATION_NAMES: {
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
uint16_t str = buf->ReadWord();
uint16_t flags = buf->ReadWord();
if (_extra_station_names_used < MAX_EXTRA_STATION_NAMES) {
ExtraStationNameInfo &info = _extra_station_names[_extra_station_names_used];
AddStringForMapping(str, &info.str);
info.flags = flags;
_extra_station_names_used++;
}
break;
}
case A0RPI_GLOBALVAR_EXTRA_STATION_NAMES_PROBABILITY: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
_extra_station_names_probability = buf->ReadByte();
break;
}
case A0RPI_GLOBALVAR_LIGHTHOUSE_GENERATE_AMOUNT:
case A0RPI_GLOBALVAR_TRANSMITTER_GENERATE_AMOUNT: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
extern std::vector _object_specs;
ObjectType type = (prop == A0RPI_GLOBALVAR_LIGHTHOUSE_GENERATE_AMOUNT) ? OBJECT_LIGHTHOUSE : OBJECT_TRANSMITTER;
_object_specs[type].generate_amount = buf->ReadByte();
break;
}
case A0RPI_GLOBALVAR_ALLOW_ROCKS_DESERT: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
extern bool _allow_rocks_desert;
_allow_rocks_desert = (buf->ReadByte() != 0);
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
/* Properties which are handled as a whole */
switch (prop) {
case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
default:
break;
}
/* Properties which are handled per item */
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
switch (prop) {
case 0x08: // Cost base factor
case 0x15: // Plural form translation
buf->ReadByte();
break;
case 0x0A: // Currency display names
case 0x0C: // Currency options
case 0x0F: // Euro introduction dates
buf->ReadWord();
break;
case 0x0B: // Currency multipliers
case 0x0D: // Currency prefix symbol
case 0x0E: // Currency suffix symbol
buf->ReadDWord();
break;
case 0x10: // Snow line height table
buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
break;
case 0x11: { // GRF match for engine allocation
uint32_t s = buf->ReadDWord();
uint32_t t = buf->ReadDWord();
SetNewGRFOverride(s, t);
break;
}
case 0x13: // Gender translation table
case 0x14: // Case translation table
while (buf->ReadByte() != 0) {
buf->ReadString();
}
break;
case A0RPI_GLOBALVAR_EXTRA_STATION_NAMES:
case A0RPI_GLOBALVAR_EXTRA_STATION_NAMES_PROBABILITY:
case A0RPI_GLOBALVAR_LIGHTHOUSE_GENERATE_AMOUNT:
case A0RPI_GLOBALVAR_TRANSMITTER_GENERATE_AMOUNT:
case A0RPI_GLOBALVAR_ALLOW_ROCKS_DESERT:
buf->Skip(buf->ReadExtendedByte());
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for cargoes
* @param cid Local ID of the cargo.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (cid + numinfo > NUM_CARGO) {
grfmsg(2, "CargoChangeInfo: Cargo type %d out of range (max %d)", cid + numinfo, NUM_CARGO - 1);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
CargoSpec *cs = CargoSpec::Get(cid + i);
switch (prop) {
case 0x08: // Bit number of cargo
cs->bitnum = buf->ReadByte();
if (cs->IsValid()) {
cs->grffile = _cur.grffile;
SetBit(_cargo_mask, cid + i);
} else {
ClrBit(_cargo_mask, cid + i);
}
BuildCargoLabelMap();
break;
case 0x09: // String ID for cargo type name
AddStringForMapping(buf->ReadWord(), &cs->name);
break;
case 0x0A: // String for 1 unit of cargo
AddStringForMapping(buf->ReadWord(), &cs->name_single);
break;
case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
case 0x1B: // String for cargo units
/* String for units of cargo. This is different in OpenTTD
* (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
* Property 1B is used to set OpenTTD's behaviour. */
AddStringForMapping(buf->ReadWord(), &cs->units_volume);
break;
case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
case 0x1C: // String for any amount of cargo
/* Strings for an amount of cargo. This is different in OpenTTD
* (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
* Property 1C is used to set OpenTTD's behaviour. */
AddStringForMapping(buf->ReadWord(), &cs->quantifier);
break;
case 0x0D: // String for two letter cargo abbreviation
AddStringForMapping(buf->ReadWord(), &cs->abbrev);
break;
case 0x0E: // Sprite ID for cargo icon
cs->sprite = buf->ReadWord();
break;
case 0x0F: // Weight of one unit of cargo
cs->weight = buf->ReadByte();
break;
case 0x10: // Used for payment calculation
cs->transit_periods[0] = buf->ReadByte();
break;
case 0x11: // Used for payment calculation
cs->transit_periods[1] = buf->ReadByte();
break;
case 0x12: // Base cargo price
cs->initial_payment = buf->ReadDWord();
break;
case 0x13: // Colour for station rating bars
cs->rating_colour = buf->ReadByte();
break;
case 0x14: // Colour for cargo graph
cs->legend_colour = buf->ReadByte();
break;
case 0x15: // Freight status
cs->is_freight = (buf->ReadByte() != 0);
break;
case 0x16: // Cargo classes
cs->classes = buf->ReadWord();
break;
case 0x17: // Cargo label
cs->label = CargoLabel{BSWAP32(buf->ReadDWord())};
BuildCargoLabelMap();
break;
case 0x18: { // Town growth substitute type
uint8_t substitute_type = buf->ReadByte();
switch (substitute_type) {
case 0x00: cs->town_acceptance_effect = TAE_PASSENGERS; break;
case 0x02: cs->town_acceptance_effect = TAE_MAIL; break;
case 0x05: cs->town_acceptance_effect = TAE_GOODS; break;
case 0x09: cs->town_acceptance_effect = TAE_WATER; break;
case 0x0B: cs->town_acceptance_effect = TAE_FOOD; break;
default:
grfmsg(1, "CargoChangeInfo: Unknown town growth substitute value %d, setting to none.", substitute_type);
[[fallthrough]];
case 0xFF: cs->town_acceptance_effect = TAE_NONE; break;
}
break;
}
case 0x19: // Town growth coefficient
buf->ReadWord();
break;
case 0x1A: // Bitmask of callbacks to use
cs->callback_mask = buf->ReadByte();
break;
case 0x1D: // Vehicle capacity muliplier
cs->multiplier = std::max(1u, buf->ReadWord());
break;
case 0x1E: { // Town production substitute type
uint8_t substitute_type = buf->ReadByte();
switch (substitute_type) {
case 0x00: cs->town_production_effect = TPE_PASSENGERS; break;
case 0x02: cs->town_production_effect = TPE_MAIL; break;
default:
grfmsg(1, "CargoChangeInfo: Unknown town production substitute value %u, setting to none.", substitute_type);
[[fallthrough]];
case 0xFF: cs->town_production_effect = TPE_NONE; break;
}
break;
}
case 0x1F: // Town production multiplier
cs->town_production_multiplier = std::max(1U, buf->ReadWord());
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for sound effects
* @param sid Local ID of the sound.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (_cur.grffile->sound_offset == 0) {
grfmsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
return CIR_INVALID_ID;
}
if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
grfmsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect (%u), max (%u). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
switch (prop) {
case 0x08: // Relative volume
sound->volume = buf->ReadByte();
break;
case 0x09: // Priority
sound->priority = buf->ReadByte();
break;
case 0x0A: { // Override old sound
SoundID orig_sound = buf->ReadByte();
if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
grfmsg(1, "SoundEffectChangeInfo: Original sound %d not defined (max %d)", orig_sound, ORIGINAL_SAMPLE_COUNT);
} else {
SoundEntry *old_sound = GetSound(orig_sound);
/* Literally copy the data of the new sound over the original */
*old_sound = *sound;
}
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Ignore an industry tile property
* @param prop The property to ignore.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
switch (prop) {
case 0x09:
case 0x0D:
case 0x0E:
case 0x10:
case 0x11:
case 0x12:
buf->ReadByte();
break;
case 0x0A:
case 0x0B:
case 0x0C:
case 0x0F:
buf->ReadWord();
break;
case 0x13:
buf->Skip(buf->ReadByte() * 2);
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
return ret;
}
/**
* Define properties for industry tiles
* @param indtid Local ID of the industry tile.
* @param numinfo Number of subsequent industry tile IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
grfmsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded (%u), max (%u). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
return CIR_INVALID_ID;
}
/* Allocate industry tile specs if they haven't been allocated already. */
if (_cur.grffile->indtspec.size() < indtid + numinfo) _cur.grffile->indtspec.resize(indtid + numinfo);
for (int i = 0; i < numinfo; i++) {
IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i].get();
if (prop != 0x08 && tsp == nullptr) {
ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf);
if (cir > ret) ret = cir;
continue;
}
switch (prop) {
case 0x08: { // Substitute industry tile type
byte subs_id = buf->ReadByte();
if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
/* The substitute id must be one of the original industry tile. */
grfmsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile %u as substitute industry tile for %u. Ignoring.", subs_id, indtid + i);
continue;
}
/* Allocate space for this industry. */
if (tsp == nullptr) {
_cur.grffile->indtspec[indtid + i] = std::make_unique(_industry_tile_specs[subs_id]);
tsp = _cur.grffile->indtspec[indtid + i].get();
tsp->enabled = true;
/* A copied tile should not have the animation infos copied too.
* The anim_state should be left untouched, though
* It is up to the author to animate them */
tsp->anim_production = INDUSTRYTILE_NOANIM;
tsp->anim_next = INDUSTRYTILE_NOANIM;
tsp->grf_prop.local_id = indtid + i;
tsp->grf_prop.subst_id = subs_id;
tsp->grf_prop.grffile = _cur.grffile;
_industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
}
break;
}
case 0x09: { // Industry tile override
byte ovrid = buf->ReadByte();
/* The industry being overridden must be an original industry. */
if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
grfmsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile %u with industry tile id %u. Ignoring.", ovrid, indtid + i);
continue;
}
_industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
break;
}
case 0x0A: // Tile acceptance
case 0x0B:
case 0x0C: {
uint16_t acctp = buf->ReadWord();
tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
break;
}
case 0x0D: // Land shape flags
tsp->slopes_refused = (Slope)buf->ReadByte();
break;
case 0x0E: // Callback mask
tsp->callback_mask = buf->ReadByte();
break;
case 0x0F: // Animation information
tsp->animation.frames = buf->ReadByte();
tsp->animation.status = buf->ReadByte();
break;
case 0x10: // Animation speed
tsp->animation.speed = buf->ReadByte();
break;
case 0x11: // Triggers for callback 25
tsp->animation.triggers = buf->ReadByte();
break;
case 0x12: // Special flags
tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
break;
case 0x13: { // variable length cargo acceptance
byte num_cargoes = buf->ReadByte();
if (num_cargoes > std::size(tsp->acceptance)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop;
return CIR_DISABLED;
}
for (uint i = 0; i < std::size(tsp->acceptance); i++) {
if (i < num_cargoes) {
tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
/* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
tsp->acceptance[i] = (int8_t)buf->ReadByte();
} else {
tsp->accepts_cargo[i] = INVALID_CARGO;
tsp->acceptance[i] = 0;
}
tsp->accepts_cargo_label[i] = CT_INVALID;
}
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Ignore an industry property
* @param prop The property to ignore.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
switch (prop) {
case 0x09:
case 0x0B:
case 0x0F:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x18:
case 0x19:
case 0x21:
case 0x22:
buf->ReadByte();
break;
case 0x0C:
case 0x0D:
case 0x0E:
case 0x10:
case 0x1B:
case 0x1F:
case 0x24:
buf->ReadWord();
break;
case 0x11:
case 0x1A:
case 0x1C:
case 0x1D:
case 0x1E:
case 0x20:
case 0x23:
buf->ReadDWord();
break;
case 0x0A: {
byte num_table = buf->ReadByte();
for (byte j = 0; j < num_table; j++) {
for (uint k = 0;; k++) {
byte x = buf->ReadByte();
if (x == 0xFE && k == 0) {
buf->ReadByte();
buf->ReadByte();
break;
}
byte y = buf->ReadByte();
if (x == 0 && y == 0x80) break;
byte gfx = buf->ReadByte();
if (gfx == 0xFE) buf->ReadWord();
}
}
break;
}
case 0x16:
for (byte j = 0; j < 3; j++) buf->ReadByte();
break;
case 0x15:
case 0x25:
case 0x26:
case 0x27:
buf->Skip(buf->ReadByte());
break;
case 0x28: {
int num_inputs = buf->ReadByte();
int num_outputs = buf->ReadByte();
buf->Skip(num_inputs * num_outputs * 2);
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
return ret;
}
/**
* Validate the industry layout; e.g. to prevent duplicate tiles.
* @param layout The layout to check.
* @return True if the layout is deemed valid.
*/
static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
{
const size_t size = layout.size();
if (size == 0) return false;
for (size_t i = 0; i < size - 1; i++) {
for (size_t j = i + 1; j < size; j++) {
if (layout[i].ti.x == layout[j].ti.x &&
layout[i].ti.y == layout[j].ti.y) {
return false;
}
}
}
bool have_regular_tile = false;
for (const auto &tilelayout : layout) {
if (tilelayout.gfx != GFX_WATERTILE_SPECIALCHECK) {
have_regular_tile = true;
break;
}
}
return have_regular_tile;
}
/**
* Define properties for industries
* @param indid Local ID of the industry.
* @param numinfo Number of subsequent industry IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
grfmsg(1, "IndustriesChangeInfo: Too many industries loaded (%u), max (%u). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
return CIR_INVALID_ID;
}
/* Allocate industry specs if they haven't been allocated already. */
if (_cur.grffile->industryspec.size() < indid + numinfo) _cur.grffile->industryspec.resize(indid + numinfo);
for (int i = 0; i < numinfo; i++) {
IndustrySpec *indsp = _cur.grffile->industryspec[indid + i].get();
if (prop != 0x08 && indsp == nullptr) {
ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
if (cir > ret) ret = cir;
continue;
}
switch (prop) {
case 0x08: { // Substitute industry type
byte subs_id = buf->ReadByte();
if (subs_id == 0xFF) {
/* Instead of defining a new industry, a substitute industry id
* of 0xFF disables the old industry with the current id. */
_industry_specs[indid + i].enabled = false;
continue;
} else if (subs_id >= NEW_INDUSTRYOFFSET) {
/* The substitute id must be one of the original industry. */
grfmsg(2, "_industry_specs: Attempt to use new industry %u as substitute industry for %u. Ignoring.", subs_id, indid + i);
continue;
}
/* Allocate space for this industry.
* Only need to do it once. If ever it is called again, it should not
* do anything */
if (indsp == nullptr) {
_cur.grffile->industryspec[indid + i] = std::make_unique(_origin_industry_specs[subs_id]);
indsp = _cur.grffile->industryspec[indid + i].get();
indsp->enabled = true;
indsp->grf_prop.local_id = indid + i;
indsp->grf_prop.subst_id = subs_id;
indsp->grf_prop.grffile = _cur.grffile;
/* If the grf industry needs to check its surrounding upon creation, it should
* rely on callbacks, not on the original placement functions */
indsp->check_proc = CHECK_NOTHING;
}
break;
}
case 0x09: { // Industry type override
byte ovrid = buf->ReadByte();
/* The industry being overridden must be an original industry. */
if (ovrid >= NEW_INDUSTRYOFFSET) {
grfmsg(2, "IndustriesChangeInfo: Attempt to override new industry %u with industry id %u. Ignoring.", ovrid, indid + i);
continue;
}
indsp->grf_prop.override = ovrid;
_industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
break;
}
case 0x0A: { // Set industry layout(s)
byte new_num_layouts = buf->ReadByte();
uint32_t definition_size = buf->ReadDWord();
uint32_t bytes_read = 0;
std::vector new_layouts;
IndustryTileLayout layout;
for (byte j = 0; j < new_num_layouts; j++) {
layout.clear();
for (uint k = 0;; k++) {
if (bytes_read >= definition_size) {
grfmsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry %u.", indid);
/* Avoid warning twice */
definition_size = UINT32_MAX;
}
layout.push_back(IndustryTileLayoutTile{});
IndustryTileLayoutTile &it = layout.back();
it.ti.x = buf->ReadByte(); // Offsets from northermost tile
++bytes_read;
if (it.ti.x == 0xFE && k == 0) {
/* This means we have to borrow the layout from an old industry */
IndustryType type = buf->ReadByte();
byte laynbr = buf->ReadByte();
bytes_read += 2;
if (type >= lengthof(_origin_industry_specs)) {
grfmsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry %u", indid);
DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
return CIR_DISABLED;
}
if (laynbr >= _origin_industry_specs[type].layouts.size()) {
grfmsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry %u", indid);
DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
return CIR_DISABLED;
}
layout = _origin_industry_specs[type].layouts[laynbr];
break;
}
it.ti.y = buf->ReadByte(); // Or table definition finalisation
++bytes_read;
if (it.ti.x == 0 && it.ti.y == 0x80) {
/* Terminator, remove and finish up */
layout.pop_back();
break;
}
it.gfx = buf->ReadByte();
++bytes_read;
if (it.gfx == 0xFE) {
/* Use a new tile from this GRF */
int local_tile_id = buf->ReadWord();
bytes_read += 2;
/* Read the ID from the _industile_mngr. */
int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
if (tempid == INVALID_INDUSTRYTILE) {
grfmsg(2, "IndustriesChangeInfo: Attempt to use industry tile %u with industry id %u, not yet defined. Ignoring.", local_tile_id, indid);
} else {
/* Declared as been valid, can be used */
it.gfx = tempid;
}
} else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
it.ti.x = (int8_t)GB(it.ti.x, 0, 8);
it.ti.y = (int8_t)GB(it.ti.y, 0, 8);
/* When there were only 256x256 maps, TileIndex was a uint16_t and
* it.ti was just a TileIndexDiff that was added to it.
* As such negative "x" values were shifted into the "y" position.
* x = -1, y = 1 -> x = 255, y = 0
* Since GRF version 8 the position is interpreted as pair of independent int8.
* For GRF version < 8 we need to emulate the old shifting behaviour.
*/
if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
}
}
if (!ValidateIndustryLayout(layout)) {
/* The industry layout was not valid, so skip this one. */
grfmsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id %u. Ignoring", indid);
new_num_layouts--;
j--;
} else {
new_layouts.push_back(layout);
}
}
/* Install final layout construction in the industry spec */
indsp->layouts = new_layouts;
break;
}
case 0x0B: // Industry production flags
indsp->life_type = (IndustryLifeType)buf->ReadByte();
break;
case 0x0C: // Industry closure message
AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
break;
case 0x0D: // Production increase message
AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
break;
case 0x0E: // Production decrease message
AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
break;
case 0x0F: // Fund cost multiplier
indsp->cost_multiplier = buf->ReadByte();
break;
case 0x10: // Production cargo types
for (byte j = 0; j < 2; j++) {
indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
indsp->produced_cargo_label[j] = CT_INVALID;
}
break;
case 0x11: // Acceptance cargo types
for (byte j = 0; j < 3; j++) {
indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
indsp->accepts_cargo_label[j] = CT_INVALID;
}
buf->ReadByte(); // Unnused, eat it up
break;
case 0x12: // Production multipliers
case 0x13:
indsp->production_rate[prop - 0x12] = buf->ReadByte();
break;
case 0x14: // Minimal amount of cargo distributed
indsp->minimal_cargo = buf->ReadByte();
break;
case 0x15: { // Random sound effects
indsp->number_of_sounds = buf->ReadByte();
uint8_t *sounds = MallocT(indsp->number_of_sounds);
try {
for (uint8_t j = 0; j < indsp->number_of_sounds; j++) {
sounds[j] = buf->ReadByte();
}
} catch (...) {
free(sounds);
throw;
}
if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
free(indsp->random_sounds);
}
indsp->random_sounds = sounds;
SetBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS);
break;
}
case 0x16: // Conflicting industry types
for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
break;
case 0x17: // Probability in random game
indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
break;
case 0x18: // Probability during gameplay
indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
break;
case 0x19: // Map colour
indsp->map_colour = buf->ReadByte();
break;
case 0x1A: // Special industry flags to define special behavior
indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
break;
case 0x1B: // New industry text ID
AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
break;
case 0x1C: // Input cargo multipliers for the three input cargo types
case 0x1D:
case 0x1E: {
uint32_t multiples = buf->ReadDWord();
indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
break;
}
case 0x1F: // Industry name
AddStringForMapping(buf->ReadWord(), &indsp->name);
break;
case 0x20: // Prospecting success chance
indsp->prospecting_chance = buf->ReadDWord();
break;
case 0x21: // Callback mask
case 0x22: { // Callback additional mask
byte aflag = buf->ReadByte();
SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
break;
}
case 0x23: // removal cost multiplier
indsp->removal_cost_multiplier = buf->ReadDWord();
break;
case 0x24: { // name for nearby station
uint16_t str = buf->ReadWord();
if (str == 0) {
indsp->station_name = STR_NULL;
} else {
AddStringForMapping(str, &indsp->station_name);
}
break;
}
case 0x25: { // variable length produced cargoes
byte num_cargoes = buf->ReadByte();
if (num_cargoes > lengthof(indsp->produced_cargo)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop;
return CIR_DISABLED;
}
for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
if (i < num_cargoes) {
CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
indsp->produced_cargo[i] = cargo;
} else {
indsp->produced_cargo[i] = INVALID_CARGO;
}
indsp->produced_cargo_label[i] = CT_INVALID;
}
break;
}
case 0x26: { // variable length accepted cargoes
byte num_cargoes = buf->ReadByte();
if (num_cargoes > lengthof(indsp->accepts_cargo)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop;
return CIR_DISABLED;
}
for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
if (i < num_cargoes) {
CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
indsp->accepts_cargo[i] = cargo;
} else {
indsp->accepts_cargo[i] = INVALID_CARGO;
}
indsp->accepts_cargo_label[i] = CT_INVALID;
}
break;
}
case 0x27: { // variable length production rates
byte num_cargoes = buf->ReadByte();
if (num_cargoes > lengthof(indsp->production_rate)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop;
return CIR_DISABLED;
}
for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
if (i < num_cargoes) {
indsp->production_rate[i] = buf->ReadByte();
} else {
indsp->production_rate[i] = 0;
}
}
break;
}
case 0x28: { // variable size input/output production multiplier table
byte num_inputs = buf->ReadByte();
byte num_outputs = buf->ReadByte();
if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop;
return CIR_DISABLED;
}
for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
uint16_t mult = 0;
if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
indsp->input_cargo_multiplier[i][j] = mult;
}
}
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Create a copy of the tile table so it can be freed later
* without problems.
* @param as The AirportSpec to copy the arrays of.
*/
static void DuplicateTileTable(AirportSpec *as)
{
AirportTileTable **table_list = MallocT(as->num_table);
for (int i = 0; i < as->num_table; i++) {
uint num_tiles = 1;
const AirportTileTable *it = as->table[0];
do {
num_tiles++;
} while ((++it)->ti.x != -0x80);
table_list[i] = MallocT(num_tiles);
MemCpyT(table_list[i], as->table[i], num_tiles);
}
as->table = table_list;
HangarTileTable *depot_table = nullptr;
if (as->nof_depots > 0) {
depot_table = MallocT(as->nof_depots);
MemCpyT(depot_table, as->depot_table, as->nof_depots);
}
as->depot_table = depot_table;
Direction *rotation = MallocT(as->num_table);
MemCpyT(rotation, as->rotation, as->num_table);
as->rotation = rotation;
}
/**
* Define properties for airports
* @param airport Local ID of the airport.
* @param numinfo Number of subsequent airport IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
grfmsg(1, "AirportChangeInfo: Too many airports, trying id (%u), max (%u). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
return CIR_INVALID_ID;
}
/* Allocate industry specs if they haven't been allocated already. */
if (_cur.grffile->airportspec.size() < airport + numinfo) _cur.grffile->airportspec.resize(airport + numinfo);
for (int i = 0; i < numinfo; i++) {
AirportSpec *as = _cur.grffile->airportspec[airport + i].get();
if (as == nullptr && prop != 0x08 && prop != 0x09) {
grfmsg(2, "AirportChangeInfo: Attempt to modify undefined airport %u, ignoring", airport + i);
return CIR_INVALID_ID;
}
switch (prop) {
case 0x08: { // Modify original airport
byte subs_id = buf->ReadByte();
if (subs_id == 0xFF) {
/* Instead of defining a new airport, an airport id
* of 0xFF disables the old airport with the current id. */
AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
continue;
} else if (subs_id >= NEW_AIRPORT_OFFSET) {
/* The substitute id must be one of the original airports. */
grfmsg(2, "AirportChangeInfo: Attempt to use new airport %u as substitute airport for %u. Ignoring.", subs_id, airport + i);
continue;
}
/* Allocate space for this airport.
* Only need to do it once. If ever it is called again, it should not
* do anything */
if (as == nullptr) {
_cur.grffile->airportspec[airport + i] = std::make_unique(*AirportSpec::GetWithoutOverride(subs_id));
as = _cur.grffile->airportspec[airport + i].get();
as->enabled = true;
as->grf_prop.local_id = airport + i;
as->grf_prop.subst_id = subs_id;
as->grf_prop.grffile = _cur.grffile;
/* override the default airport */
_airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
/* Create a copy of the original tiletable so it can be freed later. */
DuplicateTileTable(as);
}
break;
}
case 0x0A: { // Set airport layout
byte old_num_table = as->num_table;
as->num_table = buf->ReadByte(); // Number of layouts
free(as->rotation);
as->rotation = MallocT(as->num_table);
uint32_t defsize = buf->ReadDWord(); // Total size of the definition
AirportTileTable **tile_table = CallocT(as->num_table); // Table with tiles to compose the airport
AirportTileTable *att = CallocT(defsize); // Temporary array to read the tile layouts from the GRF
int size;
const AirportTileTable *copy_from;
try {
for (byte j = 0; j < as->num_table; j++) {
const_cast(as->rotation[j]) = (Direction)buf->ReadByte();
for (int k = 0;; k++) {
att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
att[k].ti.y = buf->ReadByte();
if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
/* Not the same terminator. The one we are using is rather
* x = -80, y = 0 . So, adjust it. */
att[k].ti.x = -0x80;
att[k].ti.y = 0;
att[k].gfx = 0;
size = k + 1;
copy_from = att;
break;
}
att[k].gfx = buf->ReadByte();
if (att[k].gfx == 0xFE) {
/* Use a new tile from this GRF */
int local_tile_id = buf->ReadWord();
/* Read the ID from the _airporttile_mngr. */
uint16_t tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
if (tempid == INVALID_AIRPORTTILE) {
grfmsg(2, "AirportChangeInfo: Attempt to use airport tile %u with airport id %u, not yet defined. Ignoring.", local_tile_id, airport + i);
} else {
/* Declared as been valid, can be used */
att[k].gfx = tempid;
}
} else if (att[k].gfx == 0xFF) {
att[k].ti.x = (int8_t)GB(att[k].ti.x, 0, 8);
att[k].ti.y = (int8_t)GB(att[k].ti.y, 0, 8);
}
if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
as->size_x = std::max(as->size_x, att[k].ti.y + 1);
as->size_y = std::max(as->size_y, att[k].ti.x + 1);
} else {
as->size_x = std::max(as->size_x, att[k].ti.x + 1);
as->size_y = std::max(as->size_y, att[k].ti.y + 1);
}
}
tile_table[j] = CallocT(size);
memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
}
/* Free old layouts in the airport spec */
for (int j = 0; j < old_num_table; j++) {
/* remove the individual layouts */
free(as->table[j]);
}
free(as->table);
/* Install final layout construction in the airport spec */
as->table = tile_table;
free(att);
} catch (...) {
for (int i = 0; i < as->num_table; i++) {
free(tile_table[i]);
}
free(tile_table);
free(att);
throw;
}
break;
}
case 0x0C:
as->min_year = buf->ReadWord();
as->max_year = buf->ReadWord();
if (as->max_year == 0xFFFF) as->max_year = CalTime::MAX_YEAR;
break;
case 0x0D:
as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
break;
case 0x0E:
as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
break;
case 0x0F:
as->noise_level = buf->ReadByte();
break;
case 0x10:
AddStringForMapping(buf->ReadWord(), &as->name);
break;
case 0x11: // Maintenance cost factor
as->maintenance_cost = buf->ReadWord();
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for signals
* @param id Local ID (unused).
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult SignalsChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
/* Properties which are handled per item */
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
switch (prop) {
case A0RPI_SIGNALS_ENABLE_PROGRAMMABLE_SIGNALS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(_cur.grffile->new_signal_ctrl_flags, NSCF_PROGSIG, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_SIGNALS_ENABLE_NO_ENTRY_SIGNALS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(_cur.grffile->new_signal_ctrl_flags, NSCF_NOENTRYSIG, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_SIGNALS_ENABLE_RESTRICTED_SIGNALS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(_cur.grffile->new_signal_ctrl_flags, NSCF_RESTRICTEDSIG, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_SIGNALS_ENABLE_SIGNAL_RECOLOUR:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(_cur.grffile->new_signal_ctrl_flags, NSCF_RECOLOUR_ENABLED, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_SIGNALS_EXTRA_ASPECTS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
_cur.grffile->new_signal_extra_aspects = std::min(buf->ReadByte(), NEW_SIGNALS_MAX_EXTRA_ASPECT);
break;
case A0RPI_SIGNALS_NO_DEFAULT_STYLE:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(_cur.grffile->new_signal_style_mask, 0, 1, (buf->ReadByte() != 0 ? 0 : 1));
break;
case A0RPI_SIGNALS_DEFINE_STYLE: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t local_id = buf->ReadByte();
if (_num_new_signal_styles < MAX_NEW_SIGNAL_STYLES) {
NewSignalStyle &style = _new_signal_styles[_num_new_signal_styles];
style = {};
_num_new_signal_styles++;
SetBit(_cur.grffile->new_signal_style_mask, _num_new_signal_styles);
style.grf_local_id = local_id;
style.grffile = _cur.grffile;
_cur.grffile->current_new_signal_style = &style;
} else {
_cur.grffile->current_new_signal_style = nullptr;
}
break;
}
case A0RPI_SIGNALS_STYLE_NAME: {
if (MappedPropertyLengthMismatch(buf, 2, mapping_entry)) break;
uint16_t str = buf->ReadWord();
if (_cur.grffile->current_new_signal_style != nullptr) {
AddStringForMapping(str, &(_cur.grffile->current_new_signal_style->name));
}
break;
}
case A0RPI_SIGNALS_STYLE_NO_ASPECT_INCREASE: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t value = buf->ReadByte();
if (_cur.grffile->current_new_signal_style != nullptr) {
SB(_cur.grffile->current_new_signal_style->style_flags, NSSF_NO_ASPECT_INC, 1, (value != 0 ? 1 : 0));
}
break;
}
case A0RPI_SIGNALS_STYLE_ALWAYS_RESERVE_THROUGH: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t value = buf->ReadByte();
if (_cur.grffile->current_new_signal_style != nullptr) {
SB(_cur.grffile->current_new_signal_style->style_flags, NSSF_ALWAYS_RESERVE_THROUGH, 1, (value != 0 ? 1 : 0));
}
break;
}
case A0RPI_SIGNALS_STYLE_LOOKAHEAD_EXTRA_ASPECTS: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t value = buf->ReadByte();
if (_cur.grffile->current_new_signal_style != nullptr) {
SetBit(_cur.grffile->current_new_signal_style->style_flags, NSSF_LOOKAHEAD_ASPECTS_SET);
_cur.grffile->current_new_signal_style->lookahead_extra_aspects = value;
}
break;
}
case A0RPI_SIGNALS_STYLE_LOOKAHEAD_SINGLE_SIGNAL_ONLY: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t value = buf->ReadByte();
if (_cur.grffile->current_new_signal_style != nullptr) {
SB(_cur.grffile->current_new_signal_style->style_flags, NSSF_LOOKAHEAD_SINGLE_SIGNAL, 1, (value != 0 ? 1 : 0));
}
break;
}
case A0RPI_SIGNALS_STYLE_SEMAPHORE_ENABLED: {
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
uint32_t mask = buf->ReadDWord();
if (_cur.grffile->current_new_signal_style != nullptr) {
_cur.grffile->current_new_signal_style->semaphore_mask = (uint8_t)mask;
}
break;
}
case A0RPI_SIGNALS_STYLE_ELECTRIC_ENABLED: {
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
uint32_t mask = buf->ReadDWord();
if (_cur.grffile->current_new_signal_style != nullptr) {
_cur.grffile->current_new_signal_style->electric_mask = (uint8_t)mask;
}
break;
}
case A0RPI_SIGNALS_STYLE_OPPOSITE_SIDE: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t value = buf->ReadByte();
if (_cur.grffile->current_new_signal_style != nullptr) {
SB(_cur.grffile->current_new_signal_style->style_flags, NSSF_OPPOSITE_SIDE, 1, (value != 0 ? 1 : 0));
}
break;
}
case A0RPI_SIGNALS_STYLE_COMBINED_NORMAL_SHUNT: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t value = buf->ReadByte();
if (_cur.grffile->current_new_signal_style != nullptr) {
SB(_cur.grffile->current_new_signal_style->style_flags, NSSF_COMBINED_NORMAL_SHUNT, 1, (value != 0 ? 1 : 0));
}
break;
}
case A0RPI_SIGNALS_STYLE_REALISTIC_BRAKING_ONLY: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t value = buf->ReadByte();
if (_cur.grffile->current_new_signal_style != nullptr) {
SB(_cur.grffile->current_new_signal_style->style_flags, NSSF_REALISTIC_BRAKING_ONLY, 1, (value != 0 ? 1 : 0));
}
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Ignore properties for objects
* @param prop The property to ignore.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
switch (prop) {
case 0x0B:
case 0x0C:
case 0x0D:
case 0x12:
case 0x14:
case 0x16:
case 0x17:
case 0x18:
buf->ReadByte();
break;
case 0x09:
case 0x0A:
case 0x10:
case 0x11:
case 0x13:
case 0x15:
buf->ReadWord();
break;
case 0x08:
case 0x0E:
case 0x0F:
buf->ReadDWord();
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
return ret;
}
/**
* Define properties for objects
* @param id Local ID of the object.
* @param numinfo Number of subsequent objectIDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (id + numinfo > NUM_OBJECTS) {
grfmsg(1, "ObjectChangeInfo: Too many objects loaded (%u), max (%u). Ignoring.", id + numinfo, NUM_OBJECTS);
return CIR_INVALID_ID;
}
if (id + numinfo > _cur.grffile->objectspec.size()) {
_cur.grffile->objectspec.resize(id + numinfo);
}
for (int i = 0; i < numinfo; i++) {
ObjectSpec *spec = _cur.grffile->objectspec[id + i].get();
if (prop != 0x08 && spec == nullptr) {
/* If the object property 08 is not yet set, ignore this property */
ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
if (cir > ret) ret = cir;
continue;
}
switch (prop) {
case 0x08: { // Class ID
/* Allocate space for this object. */
if (spec == nullptr) {
_cur.grffile->objectspec[id + i] = std::make_unique();
spec = _cur.grffile->objectspec[id + i].get();
spec->views = 1; // Default for NewGRFs that don't set it.
spec->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
}
/* Swap classid because we read it in BE. */
uint32_t classid = buf->ReadDWord();
spec->cls_id = ObjectClass::Allocate(BSWAP32(classid));
break;
}
case 0x09: { // Class name
ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
AddStringForMapping(buf->ReadWord(), &objclass->name);
break;
}
case 0x0A: // Object name
AddStringForMapping(buf->ReadWord(), &spec->name);
break;
case 0x0B: // Climate mask
spec->climate = buf->ReadByte();
break;
case 0x0C: // Size
spec->size = buf->ReadByte();
if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
grfmsg(0, "ObjectChangeInfo: Invalid object size requested (0x%x) for object id %u. Ignoring.", spec->size, id + i);
spec->size = OBJECT_SIZE_1X1;
}
break;
case 0x0D: // Build cost multipler
spec->build_cost_multiplier = buf->ReadByte();
spec->clear_cost_multiplier = spec->build_cost_multiplier;
break;
case 0x0E: // Introduction date
spec->introduction_date = buf->ReadDWord();
break;
case 0x0F: // End of life
spec->end_of_life_date = buf->ReadDWord();
break;
case 0x10: // Flags
spec->flags = (ObjectFlags)buf->ReadWord();
_loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
break;
case 0x11: // Animation info
spec->animation.frames = buf->ReadByte();
spec->animation.status = buf->ReadByte();
break;
case 0x12: // Animation speed
spec->animation.speed = buf->ReadByte();
break;
case 0x13: // Animation triggers
spec->animation.triggers = buf->ReadWord();
break;
case 0x14: // Removal cost multiplier
spec->clear_cost_multiplier = buf->ReadByte();
break;
case 0x15: // Callback mask
spec->callback_mask = buf->ReadWord();
break;
case 0x16: // Building height
spec->height = buf->ReadByte();
break;
case 0x17: // Views
spec->views = buf->ReadByte();
if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
grfmsg(2, "ObjectChangeInfo: Invalid number of views (%u) for object id %u. Ignoring.", spec->views, id + i);
spec->views = 1;
}
break;
case 0x18: // Amount placed on 256^2 map on map creation
spec->generate_amount = buf->ReadByte();
break;
case A0RPI_OBJECT_USE_LAND_GROUND:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
spec->ctrl_flags &= ~OBJECT_CTRL_FLAG_USE_LAND_GROUND;
if (buf->ReadByte() != 0) spec->ctrl_flags |= OBJECT_CTRL_FLAG_USE_LAND_GROUND;
break;
case A0RPI_OBJECT_EDGE_FOUNDATION_MODE:
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
spec->ctrl_flags |= OBJECT_CTRL_FLAG_EDGE_FOUNDATION;
for (int i = 0; i < 4; i++) {
spec->edge_foundation[i] = buf->ReadByte();
}
break;
case A0RPI_OBJECT_FLOOD_RESISTANT:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
spec->ctrl_flags &= ~OBJECT_CTRL_FLAG_FLOOD_RESISTANT;
if (buf->ReadByte() != 0) spec->ctrl_flags |= OBJECT_CTRL_FLAG_FLOOD_RESISTANT;
break;
case A0RPI_OBJECT_VIEWPORT_MAP_TYPE:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
spec->vport_map_type = (ObjectViewportMapType)buf->ReadByte();
spec->ctrl_flags |= OBJECT_CTRL_FLAG_VPORT_MAP_TYPE;
break;
case A0RPI_OBJECT_VIEWPORT_MAP_SUBTYPE:
if (MappedPropertyLengthMismatch(buf, 2, mapping_entry)) break;
spec->vport_map_subtype = buf->ReadWord();
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for railtypes
* @param id ID of the railtype.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
extern RailTypeInfo _railtypes[RAILTYPE_END];
if (id + numinfo > RAILTYPE_END) {
grfmsg(1, "RailTypeChangeInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
RailType rt = _cur.grffile->railtype_map[id + i];
if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
RailTypeInfo *rti = &_railtypes[rt];
switch (prop) {
case 0x08: // Label of rail type
/* Skipped here as this is loaded during reservation stage. */
buf->ReadDWord();
break;
case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
uint16_t str = buf->ReadWord();
AddStringForMapping(str, &rti->strings.toolbar_caption);
if (_cur.grffile->grf_version < 8) {
AddStringForMapping(str, &rti->strings.name);
}
break;
}
case 0x0A: // Menu text of railtype
AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
break;
case 0x0B: // Build window caption
AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
break;
case 0x0C: // Autoreplace text
AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
break;
case 0x0D: // New locomotive text
AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
break;
case 0x0E: // Compatible railtype list
case 0x0F: // Powered railtype list
case 0x18: // Railtype list required for date introduction
case 0x19: // Introduced railtype list
{
/* Rail type compatibility bits are added to the existing bits
* to allow multiple GRFs to modify compatibility with the
* default rail types. */
int n = buf->ReadByte();
for (int j = 0; j != n; j++) {
RailTypeLabel label = buf->ReadDWord();
RailType resolved_rt = GetRailTypeByLabel(BSWAP32(label), false);
if (resolved_rt != INVALID_RAILTYPE) {
switch (prop) {
case 0x0F: SetBit(rti->powered_railtypes, resolved_rt); [[fallthrough]]; // Powered implies compatible.
case 0x0E: SetBit(rti->compatible_railtypes, resolved_rt); break;
case 0x18: SetBit(rti->introduction_required_railtypes, resolved_rt); break;
case 0x19: SetBit(rti->introduces_railtypes, resolved_rt); break;
}
}
}
break;
}
case 0x10: // Rail Type flags
rti->flags = (RailTypeFlags)buf->ReadByte();
break;
case 0x11: // Curve speed advantage
rti->curve_speed = buf->ReadByte();
break;
case 0x12: // Station graphic
rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
break;
case 0x13: // Construction cost factor
rti->cost_multiplier = buf->ReadWord();
break;
case 0x14: // Speed limit
rti->max_speed = buf->ReadWord();
break;
case 0x15: // Acceleration model
rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
break;
case 0x16: // Map colour
rti->map_colour = buf->ReadByte();
break;
case 0x17: // Introduction date
rti->introduction_date = buf->ReadDWord();
break;
case 0x1A: // Sort order
rti->sorting_order = buf->ReadByte();
break;
case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
AddStringForMapping(buf->ReadWord(), &rti->strings.name);
break;
case 0x1C: // Maintenance cost factor
rti->maintenance_multiplier = buf->ReadWord();
break;
case 0x1D: // Alternate rail type label list
/* Skipped here as this is loaded during reservation stage. */
for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
break;
case A0RPI_RAILTYPE_ENABLE_PROGRAMMABLE_SIGNALS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(rti->ctrl_flags, RTCF_PROGSIG, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_RAILTYPE_ENABLE_NO_ENTRY_SIGNALS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(rti->ctrl_flags, RTCF_NOENTRYSIG, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_RAILTYPE_ENABLE_RESTRICTED_SIGNALS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(rti->ctrl_flags, RTCF_RESTRICTEDSIG, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_RAILTYPE_DISABLE_REALISTIC_BRAKING:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(rti->ctrl_flags, RTCF_NOREALISTICBRAKING, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_RAILTYPE_ENABLE_SIGNAL_RECOLOUR:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
SB(rti->ctrl_flags, RTCF_RECOLOUR_ENABLED, 1, (buf->ReadByte() != 0 ? 1 : 0));
break;
case A0RPI_RAILTYPE_EXTRA_ASPECTS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
rti->signal_extra_aspects = std::min(buf->ReadByte(), NEW_SIGNALS_MAX_EXTRA_ASPECT);
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
extern RailTypeInfo _railtypes[RAILTYPE_END];
if (id + numinfo > RAILTYPE_END) {
grfmsg(1, "RailTypeReserveInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
switch (prop) {
case 0x08: // Label of rail type
{
RailTypeLabel rtl = buf->ReadDWord();
rtl = BSWAP32(rtl);
RailType rt = GetRailTypeByLabel(rtl, false);
if (rt == INVALID_RAILTYPE) {
/* Set up new rail type */
rt = AllocateRailType(rtl);
}
_cur.grffile->railtype_map[id + i] = rt;
break;
}
case 0x09: // Toolbar caption of railtype
case 0x0A: // Menu text
case 0x0B: // Build window caption
case 0x0C: // Autoreplace text
case 0x0D: // New loco
case 0x13: // Construction cost
case 0x14: // Speed limit
case 0x1B: // Name of railtype
case 0x1C: // Maintenance cost factor
buf->ReadWord();
break;
case 0x1D: // Alternate rail type label list
if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
int n = buf->ReadByte();
for (int j = 0; j != n; j++) {
_railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
}
break;
}
grfmsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type %u because no label was set", id + i);
[[fallthrough]];
case 0x0E: // Compatible railtype list
case 0x0F: // Powered railtype list
case 0x18: // Railtype list required for date introduction
case 0x19: // Introduced railtype list
for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
break;
case 0x10: // Rail Type flags
case 0x11: // Curve speed advantage
case 0x12: // Station graphic
case 0x15: // Acceleration model
case 0x16: // Map colour
case 0x1A: // Sort order
buf->ReadByte();
break;
case 0x17: // Introduction date
buf->ReadDWord();
break;
case A0RPI_RAILTYPE_ENABLE_PROGRAMMABLE_SIGNALS:
case A0RPI_RAILTYPE_ENABLE_NO_ENTRY_SIGNALS:
case A0RPI_RAILTYPE_ENABLE_RESTRICTED_SIGNALS:
case A0RPI_RAILTYPE_DISABLE_REALISTIC_BRAKING:
case A0RPI_RAILTYPE_ENABLE_SIGNAL_RECOLOUR:
case A0RPI_RAILTYPE_EXTRA_ASPECTS:
buf->Skip(buf->ReadExtendedByte());
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for roadtypes
* @param id ID of the roadtype.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf, RoadTramType rtt)
{
ChangeInfoResult ret = CIR_SUCCESS;
extern RoadTypeInfo _roadtypes[ROADTYPE_END];
RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
if (id + numinfo > ROADTYPE_END) {
grfmsg(1, "RoadTypeChangeInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
RoadType rt = type_map[id + i];
if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
RoadTypeInfo *rti = &_roadtypes[rt];
switch (prop) {
case 0x08: // Label of road type
/* Skipped here as this is loaded during reservation stage. */
buf->ReadDWord();
break;
case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
uint16_t str = buf->ReadWord();
AddStringForMapping(str, &rti->strings.toolbar_caption);
break;
}
case 0x0A: // Menu text of roadtype
AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
break;
case 0x0B: // Build window caption
AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
break;
case 0x0C: // Autoreplace text
AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
break;
case 0x0D: // New engine text
AddStringForMapping(buf->ReadWord(), &rti->strings.new_engine);
break;
case 0x0F: // Powered roadtype list
case 0x18: // Roadtype list required for date introduction
case 0x19: { // Introduced roadtype list
/* Road type compatibility bits are added to the existing bits
* to allow multiple GRFs to modify compatibility with the
* default road types. */
int n = buf->ReadByte();
for (int j = 0; j != n; j++) {
RoadTypeLabel label = buf->ReadDWord();
RoadType resolved_rt = GetRoadTypeByLabel(BSWAP32(label), false);
if (resolved_rt != INVALID_ROADTYPE) {
switch (prop) {
case 0x0F:
if (GetRoadTramType(resolved_rt) == rtt) {
SetBit(rti->powered_roadtypes, resolved_rt);
} else {
grfmsg(1, "RoadTypeChangeInfo: Powered road type list: Road type %u road/tram type does not match road type %u, ignoring", resolved_rt, rt);
}
break;
case 0x18: SetBit(rti->introduction_required_roadtypes, resolved_rt); break;
case 0x19: SetBit(rti->introduces_roadtypes, resolved_rt); break;
}
}
}
break;
}
case 0x10: // Road Type flags
rti->flags = (RoadTypeFlags)buf->ReadByte();
break;
case 0x13: // Construction cost factor
rti->cost_multiplier = buf->ReadWord();
break;
case 0x14: // Speed limit
rti->max_speed = buf->ReadWord();
break;
case 0x16: // Map colour
rti->map_colour = buf->ReadByte();
break;
case 0x17: // Introduction date
rti->introduction_date = buf->ReadDWord();
break;
case 0x1A: // Sort order
rti->sorting_order = buf->ReadByte();
break;
case 0x1B: // Name of roadtype
AddStringForMapping(buf->ReadWord(), &rti->strings.name);
break;
case 0x1C: // Maintenance cost factor
rti->maintenance_multiplier = buf->ReadWord();
break;
case 0x1D: // Alternate road type label list
/* Skipped here as this is loaded during reservation stage. */
for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
break;
case A0RPI_ROADTYPE_EXTRA_FLAGS:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
rti->extra_flags = (RoadTypeExtraFlags)buf->ReadByte();
break;
case A0RPI_ROADTYPE_COLLISION_MODE: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
uint8_t collision_mode = buf->ReadByte();
if (collision_mode < RTCM_END) rti->collision_mode = (RoadTypeCollisionMode)collision_mode;
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
return RoadTypeChangeInfo(id, numinfo, prop, mapping_entry, buf, RTT_ROAD);
}
static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
return RoadTypeChangeInfo(id, numinfo, prop, mapping_entry, buf, RTT_TRAM);
}
static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf, RoadTramType rtt)
{
ChangeInfoResult ret = CIR_SUCCESS;
extern RoadTypeInfo _roadtypes[ROADTYPE_END];
RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
if (id + numinfo > ROADTYPE_END) {
grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
return CIR_INVALID_ID;
}
for (int i = 0; i < numinfo; i++) {
switch (prop) {
case 0x08: { // Label of road type
RoadTypeLabel rtl = buf->ReadDWord();
rtl = BSWAP32(rtl);
RoadType rt = GetRoadTypeByLabel(rtl, false);
if (rt == INVALID_ROADTYPE) {
/* Set up new road type */
rt = AllocateRoadType(rtl, rtt);
} else if (GetRoadTramType(rt) != rtt) {
grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid type (road/tram), ignoring", id + numinfo);
return CIR_INVALID_ID;
}
type_map[id + i] = rt;
break;
}
case 0x09: // Toolbar caption of roadtype
case 0x0A: // Menu text
case 0x0B: // Build window caption
case 0x0C: // Autoreplace text
case 0x0D: // New loco
case 0x13: // Construction cost
case 0x14: // Speed limit
case 0x1B: // Name of roadtype
case 0x1C: // Maintenance cost factor
buf->ReadWord();
break;
case 0x1D: // Alternate road type label list
if (type_map[id + i] != INVALID_ROADTYPE) {
int n = buf->ReadByte();
for (int j = 0; j != n; j++) {
_roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
}
break;
}
grfmsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type %u because no label was set", id + i);
/* FALL THROUGH */
case 0x0F: // Powered roadtype list
case 0x18: // Roadtype list required for date introduction
case 0x19: // Introduced roadtype list
for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
break;
case 0x10: // Road Type flags
case 0x16: // Map colour
case 0x1A: // Sort order
buf->ReadByte();
break;
case 0x17: // Introduction date
buf->ReadDWord();
break;
case A0RPI_ROADTYPE_EXTRA_FLAGS:
buf->Skip(buf->ReadExtendedByte());
break;
case A0RPI_ROADTYPE_COLLISION_MODE:
buf->Skip(buf->ReadExtendedByte());
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
return RoadTypeReserveInfo(id, numinfo, prop, mapping_entry, buf, RTT_ROAD);
}
static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
return RoadTypeReserveInfo(id, numinfo, prop, mapping_entry, buf, RTT_TRAM);
}
static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
grfmsg(1, "AirportTileChangeInfo: Too many airport tiles loaded (%u), max (%u). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
return CIR_INVALID_ID;
}
/* Allocate airport tile specs if they haven't been allocated already. */
if (_cur.grffile->airtspec.size() < airtid + numinfo) _cur.grffile->airtspec.resize(airtid + numinfo);
for (int i = 0; i < numinfo; i++) {
AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i].get();
if (prop != 0x08 && tsp == nullptr) {
grfmsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile %u. Ignoring.", airtid + i);
return CIR_INVALID_ID;
}
switch (prop) {
case 0x08: { // Substitute airport tile type
byte subs_id = buf->ReadByte();
if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
/* The substitute id must be one of the original airport tiles. */
grfmsg(2, "AirportTileChangeInfo: Attempt to use new airport tile %u as substitute airport tile for %u. Ignoring.", subs_id, airtid + i);
continue;
}
/* Allocate space for this airport tile. */
if (tsp == nullptr) {
_cur.grffile->airtspec[airtid + i] = std::make_unique(*AirportTileSpec::Get(subs_id));
tsp = _cur.grffile->airtspec[airtid + i].get();
tsp->enabled = true;
tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
tsp->grf_prop.local_id = airtid + i;
tsp->grf_prop.subst_id = subs_id;
tsp->grf_prop.grffile = _cur.grffile;
_airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
}
break;
}
case 0x09: { // Airport tile override
byte override = buf->ReadByte();
/* The airport tile being overridden must be an original airport tile. */
if (override >= NEW_AIRPORTTILE_OFFSET) {
grfmsg(2, "AirportTileChangeInfo: Attempt to override new airport tile %u with airport tile id %u. Ignoring.", override, airtid + i);
continue;
}
_airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
break;
}
case 0x0E: // Callback mask
tsp->callback_mask = buf->ReadByte();
break;
case 0x0F: // Animation information
tsp->animation.frames = buf->ReadByte();
tsp->animation.status = buf->ReadByte();
break;
case 0x10: // Animation speed
tsp->animation.speed = buf->ReadByte();
break;
case 0x11: // Animation triggers
tsp->animation.triggers = buf->ReadByte();
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Ignore properties for roadstops
* @param prop The property to ignore.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult IgnoreRoadStopProperty(uint prop, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
switch (prop) {
case 0x09:
case 0x0C:
case 0x0F:
case 0x11:
buf->ReadByte();
break;
case 0x0A:
case 0x0B:
case 0x0E:
case 0x10:
case 0x15:
buf->ReadWord();
break;
case 0x08:
case 0x0D:
case 0x12:
buf->ReadDWord();
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
return ret;
}
static ChangeInfoResult RoadStopChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
ChangeInfoResult ret = CIR_SUCCESS;
if (id + numinfo > NUM_ROADSTOPS_PER_GRF) {
grfmsg(1, "RoadStopChangeInfo: RoadStop %u is invalid, max %u, ignoring", id + numinfo, NUM_ROADSTOPS_PER_GRF);
return CIR_INVALID_ID;
}
if (id + numinfo > _cur.grffile->roadstops.size()) {
_cur.grffile->roadstops.resize(id + numinfo);
}
for (int i = 0; i < numinfo; i++) {
RoadStopSpec *rs = _cur.grffile->roadstops[id + i].get();
if (rs == nullptr && prop != 0x08 && prop != A0RPI_ROADSTOP_CLASS_ID) {
grfmsg(1, "RoadStopChangeInfo: Attempt to modify undefined road stop %u, ignoring", id + i);
ChangeInfoResult cir = IgnoreRoadStopProperty(prop, buf);
if (cir > ret) ret = cir;
continue;
}
switch (prop) {
case A0RPI_ROADSTOP_CLASS_ID:
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
[[fallthrough]];
case 0x08: { // Road Stop Class ID
if (rs == nullptr) {
_cur.grffile->roadstops[id + i] = std::make_unique();
rs = _cur.grffile->roadstops[id + i].get();
}
uint32_t classid = buf->ReadDWord();
rs->cls_id = RoadStopClass::Allocate(BSWAP32(classid));
rs->spec_id = id + i;
break;
}
case A0RPI_ROADSTOP_STOP_TYPE:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
[[fallthrough]];
case 0x09: // Road stop type
rs->stop_type = (RoadStopAvailabilityType)buf->ReadByte();
break;
case A0RPI_ROADSTOP_STOP_NAME:
if (MappedPropertyLengthMismatch(buf, 2, mapping_entry)) break;
[[fallthrough]];
case 0x0A: // Road Stop Name
AddStringForMapping(buf->ReadWord(), &rs->name);
break;
case A0RPI_ROADSTOP_CLASS_NAME:
if (MappedPropertyLengthMismatch(buf, 2, mapping_entry)) break;
[[fallthrough]];
case 0x0B: // Road Stop Class name
AddStringForMapping(buf->ReadWord(), &RoadStopClass::Get(rs->cls_id)->name);
break;
case A0RPI_ROADSTOP_DRAW_MODE:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
[[fallthrough]];
case 0x0C: // The draw mode
rs->draw_mode = (RoadStopDrawMode)buf->ReadByte();
break;
case A0RPI_ROADSTOP_TRIGGER_CARGOES:
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
[[fallthrough]];
case 0x0D: // Cargo types for random triggers
rs->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
break;
case A0RPI_ROADSTOP_ANIMATION_INFO:
if (MappedPropertyLengthMismatch(buf, 2, mapping_entry)) break;
[[fallthrough]];
case 0x0E: // Animation info
rs->animation.frames = buf->ReadByte();
rs->animation.status = buf->ReadByte();
break;
case A0RPI_ROADSTOP_ANIMATION_SPEED:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
[[fallthrough]];
case 0x0F: // Animation speed
rs->animation.speed = buf->ReadByte();
break;
case A0RPI_ROADSTOP_ANIMATION_TRIGGERS:
if (MappedPropertyLengthMismatch(buf, 2, mapping_entry)) break;
[[fallthrough]];
case 0x10: // Animation triggers
rs->animation.triggers = buf->ReadWord();
break;
case A0RPI_ROADSTOP_CALLBACK_MASK:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
[[fallthrough]];
case 0x11: // Callback mask
rs->callback_mask = buf->ReadByte();
break;
case A0RPI_ROADSTOP_GENERAL_FLAGS:
if (MappedPropertyLengthMismatch(buf, 4, mapping_entry)) break;
[[fallthrough]];
case 0x12: // General flags
rs->flags = (uint16_t)buf->ReadDWord(); // Future-proofing, size this as 4 bytes, but we only need two bytes' worth of flags at present
break;
case A0RPI_ROADSTOP_MIN_BRIDGE_HEIGHT:
if (MappedPropertyLengthMismatch(buf, 6, mapping_entry)) break;
[[fallthrough]];
case 0x13: // Minimum height for a bridge above
SetBit(rs->internal_flags, RSIF_BRIDGE_HEIGHTS_SET);
for (uint i = 0; i < 6; i++) {
rs->bridge_height[i] = buf->ReadByte();
}
break;
case A0RPI_ROADSTOP_DISALLOWED_BRIDGE_PILLARS:
if (MappedPropertyLengthMismatch(buf, 6, mapping_entry)) break;
[[fallthrough]];
case 0x14: // Disallowed bridge pillars
SetBit(rs->internal_flags, RSIF_BRIDGE_DISALLOWED_PILLARS_SET);
for (uint i = 0; i < 6; i++) {
rs->bridge_disallowed_pillars[i] = buf->ReadByte();
}
break;
case A0RPI_ROADSTOP_COST_MULTIPLIERS:
if (MappedPropertyLengthMismatch(buf, 2, mapping_entry)) break;
[[fallthrough]];
case 0x15: // Cost multipliers
rs->build_cost_multiplier = buf->ReadByte();
rs->clear_cost_multiplier = buf->ReadByte();
break;
case A0RPI_ROADSTOP_HEIGHT:
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
[[fallthrough]];
case 0x16: // Height
rs->height = buf->ReadByte();
break;
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
/**
* Define properties for new landscape
* @param id Landscape type.
* @param numinfo Number of subsequent IDs to change the property for.
* @param prop The property to change.
* @param buf The property value.
* @return ChangeInfoResult.
*/
static ChangeInfoResult NewLandscapeChangeInfo(uint id, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf)
{
/* Properties which are handled per item */
ChangeInfoResult ret = CIR_SUCCESS;
for (int i = 0; i < numinfo; i++) {
switch (prop) {
case A0RPI_NEWLANDSCAPE_ENABLE_RECOLOUR: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
bool enabled = (buf->ReadByte() != 0 ? 1 : 0);
if (id == NLA3ID_CUSTOM_ROCKS) {
SB(_cur.grffile->new_landscape_ctrl_flags, NLCF_ROCKS_RECOLOUR_ENABLED, 1, enabled);
}
break;
}
case A0RPI_NEWLANDSCAPE_ENABLE_DRAW_SNOWY_ROCKS: {
if (MappedPropertyLengthMismatch(buf, 1, mapping_entry)) break;
bool enabled = (buf->ReadByte() != 0 ? 1 : 0);
if (id == NLA3ID_CUSTOM_ROCKS) {
SB(_cur.grffile->new_landscape_ctrl_flags, NLCF_ROCKS_DRAW_SNOWY_ENABLED, 1, enabled);
}
break;
}
default:
ret = HandleAction0PropertyDefault(buf, prop);
break;
}
}
return ret;
}
static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, GrfSpecFeature feature, int property)
{
switch (cir) {
default: NOT_REACHED();
case CIR_DISABLED:
/* Error has already been printed; just stop parsing */
return true;
case CIR_SUCCESS:
return false;
case CIR_UNHANDLED:
grfmsg(1, "%s: Ignoring property 0x%02X of feature %s (not implemented)", caller, property, GetFeatureString(feature));
return false;
case CIR_UNKNOWN:
grfmsg(0, "%s: Unknown property 0x%02X of feature %s, disabling", caller, property, GetFeatureString(feature));
[[fallthrough]];
case CIR_INVALID_ID: {
/* No debug message for an invalid ID, as it has already been output */
GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
if (cir != CIR_INVALID_ID) error->param_value[1] = property;
return true;
}
}
}
static GrfSpecFeatureRef ReadFeature(uint8_t raw_byte, bool allow_48 = false)
{
if (unlikely(HasBit(_cur.grffile->ctrl_flags, GFCF_HAVE_FEATURE_ID_REMAP))) {
const GRFFeatureMapRemapSet &remap = _cur.grffile->feature_id_remaps;
if (remap.remapped_ids[raw_byte]) {
auto iter = remap.mapping.find(raw_byte);
const GRFFeatureMapRemapEntry &def = iter->second;
if (def.feature == GSF_ERROR_ON_USE) {
grfmsg(0, "Error: Unimplemented mapped feature: %s, mapped to: %02X", def.name, raw_byte);
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_UNIMPLEMETED_MAPPED_FEATURE_ID);
error->data = stredup(def.name);
error->param_value[1] = GSF_INVALID;
error->param_value[2] = raw_byte;
} else if (def.feature == GSF_INVALID) {
grfmsg(2, "Ignoring unimplemented mapped feature: %s, mapped to: %02X", def.name, raw_byte);
}
return { def.feature, raw_byte };
}
}
GrfSpecFeature feature;
if (raw_byte >= GSF_REAL_FEATURE_END && !(allow_48 && raw_byte == 0x48)) {
feature = GSF_INVALID;
} else {
feature = static_cast(raw_byte);
}
return { feature, raw_byte };
}
static const char *_feature_names[] = {
"TRAINS",
"ROADVEHICLES",
"SHIPS",
"AIRCRAFT",
"STATIONS",
"CANALS",
"BRIDGES",
"HOUSES",
"GLOBALVAR",
"INDUSTRYTILES",
"INDUSTRIES",
"CARGOES",
"SOUNDFX",
"AIRPORTS",
"SIGNALS",
"OBJECTS",
"RAILTYPES",
"AIRPORTTILES",
"ROADTYPES",
"TRAMTYPES",
"ROADSTOPS",
"NEWLANDSCAPE",
"TOWN",
};
static_assert(lengthof(_feature_names) == GSF_END);
const char *GetFeatureString(GrfSpecFeatureRef feature)
{
static char buffer[32];
if (feature.id < GSF_END) {
seprintf(buffer, lastof(buffer), "0x%02X (%s)", feature.raw_byte, _feature_names[feature.id]);
} else {
if (unlikely(HasBit(_cur.grffile->ctrl_flags, GFCF_HAVE_FEATURE_ID_REMAP))) {
const GRFFeatureMapRemapSet &remap = _cur.grffile->feature_id_remaps;
if (remap.remapped_ids[feature.raw_byte]) {
auto iter = remap.mapping.find(feature.raw_byte);
const GRFFeatureMapRemapEntry &def = iter->second;
seprintf(buffer, lastof(buffer), "0x%02X (%s)", feature.raw_byte, def.name);
return buffer;
}
}
seprintf(buffer, lastof(buffer), "0x%02X", feature.raw_byte);
}
return buffer;
}
const char *GetFeatureString(GrfSpecFeature feature)
{
uint8_t raw_byte = feature;
if (feature >= GSF_REAL_FEATURE_END) {
for (const auto &entry : _cur.grffile->feature_id_remaps.mapping) {
if (entry.second.feature == feature) {
raw_byte = entry.second.raw_id;
break;
}
}
}
return GetFeatureString(GrfSpecFeatureRef{ feature, raw_byte });
}
struct GRFFilePropertyDescriptor {
int prop;
const GRFFilePropertyRemapEntry *entry;
GRFFilePropertyDescriptor(int prop, const GRFFilePropertyRemapEntry *entry)
: prop(prop), entry(entry) {}
};
static GRFFilePropertyDescriptor ReadAction0PropertyID(ByteReader *buf, uint8_t feature)
{
uint8_t raw_prop = buf->ReadByte();
const GRFFilePropertyRemapSet &remap = _cur.grffile->action0_property_remaps[feature];
if (remap.remapped_ids[raw_prop]) {
auto iter = remap.mapping.find(raw_prop);
assert(iter != remap.mapping.end());
const GRFFilePropertyRemapEntry &def = iter->second;
int prop = def.id;
if (prop == A0RPI_UNKNOWN_ERROR) {
grfmsg(0, "Error: Unimplemented mapped property: %s, feature: %s, mapped to: %X", def.name, GetFeatureString(def.feature), raw_prop);
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_UNIMPLEMETED_MAPPED_PROPERTY);
error->data = stredup(def.name);
error->param_value[1] = def.feature;
error->param_value[2] = raw_prop;
} else if (prop == A0RPI_UNKNOWN_IGNORE) {
grfmsg(2, "Ignoring unimplemented mapped property: %s, feature: %s, mapped to: %X", def.name, GetFeatureString(def.feature), raw_prop);
} else if (prop == A0RPI_ID_EXTENSION) {
byte *outer_data = buf->Data();
size_t outer_length = buf->ReadExtendedByte();
uint16_t mapped_id = buf->ReadWord();
byte *inner_data = buf->Data();
size_t inner_length = buf->ReadExtendedByte();
if (inner_length + (inner_data - outer_data) != outer_length) {
grfmsg(2, "Ignoring extended ID property with malformed lengths: %s, feature: %s, mapped to: %X", def.name, GetFeatureString(def.feature), raw_prop);
buf->ResetReadPosition(outer_data);
return GRFFilePropertyDescriptor(A0RPI_UNKNOWN_IGNORE, &def);
}
auto ext = _cur.grffile->action0_extended_property_remaps.find((((uint32_t)feature) << 16) | mapped_id);
if (ext != _cur.grffile->action0_extended_property_remaps.end()) {
buf->ResetReadPosition(inner_data);
const GRFFilePropertyRemapEntry &ext_def = ext->second;
prop = ext_def.id;
if (prop == A0RPI_UNKNOWN_ERROR) {
grfmsg(0, "Error: Unimplemented mapped extended ID property: %s, feature: %s, mapped to: %X (via %X)", ext_def.name, GetFeatureString(ext_def.feature), mapped_id, raw_prop);
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_UNIMPLEMETED_MAPPED_PROPERTY);
error->data = stredup(ext_def.name);
error->param_value[1] = ext_def.feature;
error->param_value[2] = 0xE0000 | mapped_id;
} else if (prop == A0RPI_UNKNOWN_IGNORE) {
grfmsg(2, "Ignoring unimplemented mapped extended ID property: %s, feature: %s, mapped to: %X (via %X)", ext_def.name, GetFeatureString(ext_def.feature), mapped_id, raw_prop);
}
return GRFFilePropertyDescriptor(prop, &ext_def);
} else {
grfmsg(2, "Ignoring unknown extended ID property: %s, feature: %s, mapped to: %X (via %X)", def.name, GetFeatureString(def.feature), mapped_id, raw_prop);
buf->ResetReadPosition(outer_data);
return GRFFilePropertyDescriptor(A0RPI_UNKNOWN_IGNORE, &def);
}
}
return GRFFilePropertyDescriptor(prop, &def);
} else {
return GRFFilePropertyDescriptor(raw_prop, nullptr);
}
}
/* Action 0x00 */
static void FeatureChangeInfo(ByteReader *buf)
{
/* <00> ()...
*
* B feature
* B num-props how many properties to change per vehicle/station
* B num-info how many vehicles/stations to change
* E id ID of first vehicle/station to change, if num-info is
* greater than one, this one and the following
* vehicles/stations will be changed
* B property what property to change, depends on the feature
* V new-info new bytes of info (variable size; depends on properties) */
static const VCI_Handler handler[] = {
/* GSF_TRAINS */ RailVehicleChangeInfo,
/* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
/* GSF_SHIPS */ ShipVehicleChangeInfo,
/* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
/* GSF_STATIONS */ StationChangeInfo,
/* GSF_CANALS */ CanalChangeInfo,
/* GSF_BRIDGES */ BridgeChangeInfo,
/* GSF_HOUSES */ TownHouseChangeInfo,
/* GSF_GLOBALVAR */ GlobalVarChangeInfo,
/* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
/* GSF_INDUSTRIES */ IndustriesChangeInfo,
/* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
/* GSF_SOUNDFX */ SoundEffectChangeInfo,
/* GSF_AIRPORTS */ AirportChangeInfo,
/* GSF_SIGNALS */ SignalsChangeInfo,
/* GSF_OBJECTS */ ObjectChangeInfo,
/* GSF_RAILTYPES */ RailTypeChangeInfo,
/* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
/* GSF_ROADTYPES */ RoadTypeChangeInfo,
/* GSF_TRAMTYPES */ TramTypeChangeInfo,
/* GSF_ROADSTOPS */ RoadStopChangeInfo,
/* GSF_NEWLANDSCAPE */ NewLandscapeChangeInfo,
/* GSF_FAKE_TOWNS */ nullptr,
};
static_assert(GSF_END == lengthof(handler));
static_assert(lengthof(handler) == lengthof(_cur.grffile->action0_property_remaps), "Action 0 feature list length mismatch");
GrfSpecFeatureRef feature_ref = ReadFeature(buf->ReadByte());
GrfSpecFeature feature = feature_ref.id;
uint8_t numprops = buf->ReadByte();
uint numinfo = buf->ReadByte();
uint engine = buf->ReadExtendedByte();
if (feature >= GSF_END) {
grfmsg(1, "FeatureChangeInfo: Unsupported feature %s skipping", GetFeatureString(feature_ref));
return;
}
grfmsg(6, "FeatureChangeInfo: Feature %s, %d properties, to apply to %d+%d",
GetFeatureString(feature_ref), numprops, engine, numinfo);
if (handler[feature] == nullptr) {
if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature %s, skipping", GetFeatureString(feature_ref));
return;
}
/* Mark the feature as used by the grf */
SetBit(_cur.grffile->grf_features, feature);
while (numprops-- && buf->HasData()) {
GRFFilePropertyDescriptor desc = ReadAction0PropertyID(buf, feature);
ChangeInfoResult cir = handler[feature](engine, numinfo, desc.prop, desc.entry, buf);
if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, desc.prop)) return;
}
}
/* Action 0x00 (GLS_SAFETYSCAN) */
static void SafeChangeInfo(ByteReader *buf)
{
GrfSpecFeatureRef feature = ReadFeature(buf->ReadByte());
uint8_t numprops = buf->ReadByte();
uint numinfo = buf->ReadByte();
buf->ReadExtendedByte(); // id
if (feature.id == GSF_BRIDGES && numprops == 1) {
GRFFilePropertyDescriptor desc = ReadAction0PropertyID(buf, feature.id);
/* Bridge property 0x0D is redefinition of sprite layout tables, which
* is considered safe. */
if (desc.prop == 0x0D) return;
} else if (feature.id == GSF_GLOBALVAR && numprops == 1) {
GRFFilePropertyDescriptor desc = ReadAction0PropertyID(buf, feature.id);
/* Engine ID Mappings are safe, if the source is static */
if (desc.prop == 0x11) {
bool is_safe = true;
for (uint i = 0; i < numinfo; i++) {
uint32_t s = buf->ReadDWord();
buf->ReadDWord(); // dest
const GRFConfig *grfconfig = GetGRFConfig(s);
if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
is_safe = false;
break;
}
}
if (is_safe) return;
}
}
SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
/* Skip remainder of GRF */
_cur.skip_sprites = -1;
}
/* Action 0x00 (GLS_RESERVE) */
static void ReserveChangeInfo(ByteReader *buf)
{
GrfSpecFeatureRef feature_ref = ReadFeature(buf->ReadByte());
GrfSpecFeature feature = feature_ref.id;
if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
uint8_t numprops = buf->ReadByte();
uint8_t numinfo = buf->ReadByte();
uint8_t index = buf->ReadExtendedByte();
while (numprops-- && buf->HasData()) {
GRFFilePropertyDescriptor desc = ReadAction0PropertyID(buf, feature);
ChangeInfoResult cir = CIR_SUCCESS;
switch (feature) {
default: NOT_REACHED();
case GSF_CARGOES:
cir = CargoChangeInfo(index, numinfo, desc.prop, desc.entry, buf);
break;
case GSF_GLOBALVAR:
cir = GlobalVarReserveInfo(index, numinfo, desc.prop, desc.entry, buf);
break;
case GSF_RAILTYPES:
cir = RailTypeReserveInfo(index, numinfo, desc.prop, desc.entry, buf);
break;
case GSF_ROADTYPES:
cir = RoadTypeReserveInfo(index, numinfo, desc.prop, desc.entry, buf);
break;
case GSF_TRAMTYPES:
cir = TramTypeReserveInfo(index, numinfo, desc.prop, desc.entry, buf);
break;
}
if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, desc.prop)) return;
}
}
/* Action 0x01 */
static void NewSpriteSet(ByteReader *buf)
{
/* Basic format: <01>
* Extended format: <01> 00
*
* B feature feature to define sprites for
* 0, 1, 2, 3: veh-type, 4: train stations
* E first-set first sprite set to define
* B num-sets number of sprite sets (extended byte in extended format)
* E num-ent how many entries per sprite set
* For vehicles, this is the number of different
* vehicle directions in each sprite set
* Set num-dirs=8, unless your sprites are symmetric.
* In that case, use num-dirs=4.
*/
GrfSpecFeatureRef feature_ref = ReadFeature(buf->ReadByte());
GrfSpecFeature feature = feature_ref.id;
uint16_t num_sets = buf->ReadByte();
uint16_t first_set = 0;
if (num_sets == 0 && buf->HasData(3)) {
/* Extended Action1 format.
* Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
first_set = buf->ReadExtendedByte();
num_sets = buf->ReadExtendedByte();
}
uint16_t num_ents = buf->ReadExtendedByte();
if (feature >= GSF_END) {
_cur.skip_sprites = num_sets * num_ents;
grfmsg(1, "NewSpriteSet: Unsupported feature %s, skipping %d sprites", GetFeatureString(feature_ref), _cur.skip_sprites);
return;
}
_cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
grfmsg(7, "New sprite set at %d of feature %s, consisting of %d sets with %d views each (total %d)",
_cur.spriteid, GetFeatureString(feature), num_sets, num_ents, num_sets * num_ents
);
for (int i = 0; i < num_sets * num_ents; i++) {
_cur.nfo_line++;
LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
}
}
/* Action 0x01 (SKIP) */
static void SkipAct1(ByteReader *buf)
{
buf->ReadByte();
uint16_t num_sets = buf->ReadByte();
if (num_sets == 0 && buf->HasData(3)) {
/* Extended Action1 format.
* Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
buf->ReadExtendedByte(); // first_set
num_sets = buf->ReadExtendedByte();
}
uint16_t num_ents = buf->ReadExtendedByte();
_cur.skip_sprites = num_sets * num_ents;
grfmsg(3, "SkipAct1: Skipping %d sprites", _cur.skip_sprites);
}
const CallbackResultSpriteGroup *NewCallbackResultSpriteGroupNoTransform(uint16_t result)
{
const CallbackResultSpriteGroup *&ptr = _callback_result_cache[result];
if (ptr == nullptr) {
assert(CallbackResultSpriteGroup::CanAllocateItem());
ptr = new CallbackResultSpriteGroup(result);
}
return ptr;
}
static const CallbackResultSpriteGroup *NewCallbackResultSpriteGroup(uint16_t groupid)
{
uint16_t result = CallbackResultSpriteGroup::TransformResultValue(groupid, _cur.grffile->grf_version >= 8);
return NewCallbackResultSpriteGroupNoTransform(result);
}
static const SpriteGroup *GetGroupFromGroupIDNoCBResult(uint16_t setid, byte type, uint16_t groupid)
{
if ((size_t)groupid >= _cur.spritegroups.size() || _cur.spritegroups[groupid] == nullptr) {
grfmsg(1, "GetGroupFromGroupID(0x%04X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
return nullptr;
}
const SpriteGroup *result = _cur.spritegroups[groupid];
if (likely(!HasBit(_misc_debug_flags, MDF_NEWGRF_SG_SAVE_RAW))) result = PruneTargetSpriteGroup(result);
return result;
}
/* Helper function to either create a callback or link to a previously
* defined spritegroup. */
static const SpriteGroup *GetGroupFromGroupID(uint16_t setid, byte type, uint16_t groupid)
{
if (HasBit(groupid, 15)) {
return NewCallbackResultSpriteGroup(groupid);
}
return GetGroupFromGroupIDNoCBResult(setid, type, groupid);
}
static const SpriteGroup *GetGroupByID(uint16_t groupid)
{
if ((size_t)groupid >= _cur.spritegroups.size()) return nullptr;
const SpriteGroup *result = _cur.spritegroups[groupid];
return result;
}
/**
* Helper function to either create a callback or a result sprite group.
* @param feature GrfSpecFeature to define spritegroup for.
* @param setid SetID of the currently being parsed Action2. (only for debug output)
* @param type Type of the currently being parsed Action2. (only for debug output)
* @param spriteid Raw value from the GRF for the new spritegroup; describes either the return value or the referenced spritegroup.
* @return Created spritegroup.
*/
static const SpriteGroup *CreateGroupFromGroupID(byte feature, uint16_t setid, byte type, uint16_t spriteid)
{
if (HasBit(spriteid, 15)) {
return NewCallbackResultSpriteGroup(spriteid);
}
if (!_cur.IsValidSpriteSet(feature, spriteid)) {
grfmsg(1, "CreateGroupFromGroupID(0x%04X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
return nullptr;
}
SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
uint num_sprites = _cur.GetNumEnts(feature, spriteid);
/* Ensure that the sprites are loeded */
assert(spriteset_start + num_sprites <= _cur.spriteid);
assert(ResultSpriteGroup::CanAllocateItem());
return new ResultSpriteGroup(spriteset_start, num_sprites);
}
static void ProcessDeterministicSpriteGroupRanges(const std::vector &ranges, std::vector &ranges_out, const SpriteGroup *default_group)
{
/* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
std::vector bounds;
for (uint i = 0; i < ranges.size(); i++) {
bounds.push_back(ranges[i].low);
if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
}
std::sort(bounds.begin(), bounds.end());
bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
std::vector target;
for (uint j = 0; j < bounds.size(); ++j) {
uint32_t v = bounds[j];
const SpriteGroup *t = default_group;
for (uint i = 0; i < ranges.size(); i++) {
if (ranges[i].low <= v && v <= ranges[i].high) {
t = ranges[i].group;
break;
}
}
target.push_back(t);
}
assert(target.size() == bounds.size());
for (uint j = 0; j < bounds.size(); ) {
if (target[j] != default_group) {
DeterministicSpriteGroupRange &r = ranges_out.emplace_back();
r.group = target[j];
r.low = bounds[j];
while (j < bounds.size() && target[j] == r.group) {
j++;
}
r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
} else {
j++;
}
}
}
static VarSpriteGroupScopeOffset ParseRelativeScopeByte(byte relative)
{
VarSpriteGroupScopeOffset var_scope_count = (GB(relative, 6, 2) << 8);
if ((relative & 0xF) == 0) {
SetBit(var_scope_count, 15);
} else {
var_scope_count |= (relative & 0xF);
}
return var_scope_count;
}
/* Action 0x02 */
static void NewSpriteGroup(ByteReader *buf)
{
/* <02>
*
* B feature see action 1
* B set-id ID of this particular definition
* This is an extended byte if feature "more_action2_ids" is tested for
* B type/num-entries
* if 80 or greater, this is a randomized or variational
* list definition, see below
* otherwise it specifies a number of entries, the exact
* meaning depends on the feature
* V feature-specific-data (huge mess, don't even look it up --pasky) */
const SpriteGroup *act_group = nullptr;
GrfSpecFeatureRef feature_ref = ReadFeature(buf->ReadByte());
GrfSpecFeature feature = feature_ref.id;
if (feature >= GSF_END) {
grfmsg(1, "NewSpriteGroup: Unsupported feature %s, skipping", GetFeatureString(feature_ref));
return;
}
uint16_t setid = HasBit(_cur.grffile->observed_feature_tests, GFTOF_MORE_ACTION2_IDS) ? buf->ReadExtendedByte() : buf->ReadByte();
uint8_t type = buf->ReadByte();
/* Sprite Groups are created here but they are allocated from a pool, so
* we do not need to delete anything if there is an exception from the
* ByteReader. */
/* Decoded sprite type */
enum SpriteType {
STYPE_NORMAL,
STYPE_DETERMINISTIC,
STYPE_DETERMINISTIC_RELATIVE,
STYPE_DETERMINISTIC_RELATIVE_2,
STYPE_RANDOMIZED,
STYPE_CB_FAILURE,
};
SpriteType stype = STYPE_NORMAL;
switch (type) {
/* Deterministic Sprite Group */
case 0x81: // Self scope, byte
case 0x82: // Parent scope, byte
case 0x85: // Self scope, word
case 0x86: // Parent scope, word
case 0x89: // Self scope, dword
case 0x8A: // Parent scope, dword
stype = STYPE_DETERMINISTIC;
break;
/* Randomized Sprite Group */
case 0x80: // Self scope
case 0x83: // Parent scope
case 0x84: // Relative scope
stype = STYPE_RANDOMIZED;
break;
/* Extension type */
case 0x87:
if (HasBit(_cur.grffile->observed_feature_tests, GFTOF_MORE_VARACTION2_TYPES)) {
byte subtype = buf->ReadByte();
switch (subtype) {
case 0:
stype = STYPE_CB_FAILURE;
break;
case 1:
stype = STYPE_DETERMINISTIC_RELATIVE;
break;
case 2:
stype = STYPE_DETERMINISTIC_RELATIVE_2;
break;
default:
grfmsg(1, "NewSpriteGroup: Unknown 0x87 extension subtype %02X for feature %s, handling as CB failure", subtype, GetFeatureString(feature));
stype = STYPE_CB_FAILURE;
break;
}
}
break;
default:
break;
}
switch (stype) {
/* Deterministic Sprite Group */
case STYPE_DETERMINISTIC:
case STYPE_DETERMINISTIC_RELATIVE:
case STYPE_DETERMINISTIC_RELATIVE_2:
{
VarSpriteGroupScopeOffset var_scope_count = 0;
if (stype == STYPE_DETERMINISTIC_RELATIVE) {
var_scope_count = ParseRelativeScopeByte(buf->ReadByte());
} else if (stype == STYPE_DETERMINISTIC_RELATIVE_2) {
uint8_t mode = buf->ReadByte();
uint8_t offset = buf->ReadByte();
bool invalid = false;
if ((mode & 0x7F) >= VSGSRM_END) {
invalid = true;
}
if (HasBit(mode, 7)) {
/* Use variable 0x100 */
if (offset != 0) invalid = true;
}
if (invalid) {
grfmsg(1, "NewSpriteGroup: Unknown 0x87 extension subtype 2 relative mode: %02X %02X for feature %s, handling as CB failure", mode, offset, GetFeatureString(feature));
act_group = NewCallbackResultSpriteGroupNoTransform(CALLBACK_FAILED);
break;
}
var_scope_count = (mode << 8) | offset;
}
byte varadjust;
byte varsize;
bool first_adjust = true;
assert(DeterministicSpriteGroup::CanAllocateItem());
DeterministicSpriteGroup *group = new DeterministicSpriteGroup();
group->nfo_line = _cur.nfo_line;
group->feature = feature;
if (_action6_override_active) group->sg_flags |= SGF_ACTION6;
act_group = group;
if (stype == STYPE_DETERMINISTIC_RELATIVE || stype == STYPE_DETERMINISTIC_RELATIVE_2) {
group->var_scope = (feature <= GSF_AIRCRAFT) ? VSG_SCOPE_RELATIVE : VSG_SCOPE_SELF;
group->var_scope_count = var_scope_count;
group->size = DSG_SIZE_DWORD;
varsize = 4;
} else {
group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
switch (GB(type, 2, 2)) {
default: NOT_REACHED();
case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
}
}
const VarAction2AdjustInfo info = { feature, GetGrfSpecFeatureForScope(feature, group->var_scope), varsize };
DeterministicSpriteGroupShadowCopy *shadow = nullptr;
if (unlikely(HasBit(_misc_debug_flags, MDF_NEWGRF_SG_SAVE_RAW))) {
shadow = &(_deterministic_sg_shadows[group]);
}
static std::vector current_adjusts;
current_adjusts.clear();
VarAction2OptimiseState va2_opt_state;
/* The initial value is always the constant 0 */
va2_opt_state.inference = VA2AIF_SIGNED_NON_NEGATIVE | VA2AIF_ONE_OR_ZERO | VA2AIF_HAVE_CONSTANT;
va2_opt_state.current_constant = 0;
/* Loop through the var adjusts. Unfortunately we don't know how many we have
* from the outset, so we shall have to keep reallocing. */
do {
DeterministicSpriteGroupAdjust &adjust = current_adjusts.emplace_back();
/* The first var adjust doesn't have an operation specified, so we set it to add. */
adjust.operation = first_adjust ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
first_adjust = false;
if (adjust.operation > DSGA_OP_END) adjust.operation = DSGA_OP_END;
adjust.variable = buf->ReadByte();
if (adjust.variable == 0x7E) {
/* Link subroutine group */
adjust.subroutine = GetGroupFromGroupIDNoCBResult(setid, type, HasBit(_cur.grffile->observed_feature_tests, GFTOF_MORE_ACTION2_IDS) ? buf->ReadExtendedByte() : buf->ReadByte());
} else {
adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf->ReadByte() : 0;
}
varadjust = buf->ReadByte();
adjust.shift_num = GB(varadjust, 0, 5);
adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
adjust.and_mask = buf->ReadVarSize(varsize);
if (adjust.variable == 0x11) {
for (const GRFVariableMapEntry &remap : _cur.grffile->grf_variable_remaps) {
if (remap.feature == info.scope_feature && remap.input_shift == adjust.shift_num && remap.input_mask == adjust.and_mask) {
adjust.variable = remap.id;
adjust.shift_num = remap.output_shift;
adjust.and_mask = remap.output_mask;
adjust.parameter = remap.output_param;
break;
}
}
} else if (adjust.variable == 0x7B && adjust.parameter == 0x11) {
for (const GRFVariableMapEntry &remap : _cur.grffile->grf_variable_remaps) {
if (remap.feature == info.scope_feature && remap.input_shift == adjust.shift_num && remap.input_mask == adjust.and_mask) {
adjust.parameter = remap.id;
adjust.shift_num = remap.output_shift;
adjust.and_mask = remap.output_mask;
break;
}
}
}
if (info.scope_feature == GSF_ROADSTOPS && HasBit(_cur.grffile->observed_feature_tests, GFTOF_ROAD_STOPS)) {
if (adjust.variable == 0x68) adjust.variable = A2VRI_ROADSTOP_INFO_NEARBY_TILES_EXT;
if (adjust.variable == 0x7B && adjust.parameter == 0x68) adjust.parameter = A2VRI_ROADSTOP_INFO_NEARBY_TILES_EXT;
}
if (adjust.type != DSGA_TYPE_NONE) {
adjust.add_val = buf->ReadVarSize(varsize);
adjust.divmod_val = buf->ReadVarSize(varsize);
} else {
adjust.add_val = 0;
adjust.divmod_val = 0;
}
if (unlikely(shadow != nullptr)) {
shadow->adjusts.push_back(adjust);
/* Pruning was turned off so that the unpruned target could be saved in the shadow, prune now */
if (adjust.subroutine != nullptr) adjust.subroutine = PruneTargetSpriteGroup(adjust.subroutine);
}
OptimiseVarAction2PreCheckAdjust(va2_opt_state, adjust);
/* Continue reading var adjusts while bit 5 is set. */
} while (HasBit(varadjust, 5));
/* shrink_to_fit will be called later */
group->adjusts.reserve(current_adjusts.size());
for (const DeterministicSpriteGroupAdjust &adjust : current_adjusts) {
group->adjusts.push_back(adjust);
OptimiseVarAction2Adjust(va2_opt_state, info, group, group->adjusts.back());
}
std::vector ranges;
ranges.resize(buf->ReadByte());
for (uint i = 0; i < ranges.size(); i++) {
ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
ranges[i].low = buf->ReadVarSize(varsize);
ranges[i].high = buf->ReadVarSize(varsize);
}
group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
if (unlikely(shadow != nullptr)) {
shadow->calculated_result = ranges.size() == 0;
ProcessDeterministicSpriteGroupRanges(ranges, shadow->ranges, group->default_group);
shadow->default_group = group->default_group;
/* Pruning was turned off so that the unpruned targets could be saved in the shadow ranges, prune now */
for (DeterministicSpriteGroupRange &range : ranges) {
range.group = PruneTargetSpriteGroup(range.group);
}
group->default_group = PruneTargetSpriteGroup(group->default_group);
}
group->error_group = ranges.empty() ? group->default_group : ranges[0].group;
/* nvar == 0 is a special case -- we turn our value into a callback result */
group->calculated_result = ranges.empty();
ProcessDeterministicSpriteGroupRanges(ranges, group->ranges, group->default_group);
OptimiseVarAction2DeterministicSpriteGroup(va2_opt_state, info, group, current_adjusts);
current_adjusts.clear();
break;
}
/* Randomized Sprite Group */
case STYPE_RANDOMIZED:
{
assert(RandomizedSpriteGroup::CanAllocateItem());
RandomizedSpriteGroup *group = new RandomizedSpriteGroup();
group->nfo_line = _cur.nfo_line;
if (_action6_override_active) group->sg_flags |= SGF_ACTION6;
act_group = group;
group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
if (HasBit(type, 2)) {
if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
group->var_scope_count = ParseRelativeScopeByte(buf->ReadByte());
}
uint8_t triggers = buf->ReadByte();
group->triggers = GB(triggers, 0, 7);
group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
group->lowest_randbit = buf->ReadByte();
byte num_groups = buf->ReadByte();
if (!HasExactlyOneBit(num_groups)) {
grfmsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
}
for (uint i = 0; i < num_groups; i++) {
group->groups.push_back(GetGroupFromGroupID(setid, type, buf->ReadWord()));
}
if (unlikely(HasBit(_misc_debug_flags, MDF_NEWGRF_SG_SAVE_RAW))) {
RandomizedSpriteGroupShadowCopy *shadow = &(_randomized_sg_shadows[group]);
shadow->groups = group->groups;
/* Pruning was turned off so that the unpruned targets could be saved in the shadow groups, prune now */
for (const SpriteGroup *&group : group->groups) {
group = PruneTargetSpriteGroup(group);
}
}
break;
}
case STYPE_CB_FAILURE:
act_group = NewCallbackResultSpriteGroupNoTransform(CALLBACK_FAILED);
break;
/* Neither a variable or randomized sprite group... must be a real group */
case STYPE_NORMAL:
{
switch (feature) {
case GSF_TRAINS:
case GSF_ROADVEHICLES:
case GSF_SHIPS:
case GSF_AIRCRAFT:
case GSF_STATIONS:
case GSF_CANALS:
case GSF_CARGOES:
case GSF_AIRPORTS:
case GSF_RAILTYPES:
case GSF_ROADTYPES:
case GSF_TRAMTYPES:
case GSF_SIGNALS:
case GSF_NEWLANDSCAPE:
{
byte num_loaded = type;
byte num_loading = buf->ReadByte();
if (!_cur.HasValidSpriteSets(feature)) {
grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
return;
}
if (num_loaded + num_loading == 0) {
grfmsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
break;
}
grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u loaded, %u loading",
setid, num_loaded, num_loading);
if (num_loaded + num_loading == 0) {
grfmsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
break;
}
if (num_loaded + num_loading == 1) {
/* Avoid creating 'Real' sprite group if only one option. */
uint16_t spriteid = buf->ReadWord();
act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
grfmsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset %u", spriteid);
break;
}
std::vector loaded;
std::vector loading;
for (uint i = 0; i < num_loaded; i++) {
loaded.push_back(buf->ReadWord());
grfmsg(8, "NewSpriteGroup: + rg->loaded[%i] = subset %u", i, loaded[i]);
}
for (uint i = 0; i < num_loading; i++) {
loading.push_back(buf->ReadWord());
grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, loading[i]);
}
if (std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end() &&
std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end() &&
loaded[0] == loading[0])
{
/* Both lists only contain the same value, so don't create 'Real' sprite group */
act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
grfmsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset %u", loaded[0]);
break;
}
assert(RealSpriteGroup::CanAllocateItem());
RealSpriteGroup *group = new RealSpriteGroup();
group->nfo_line = _cur.nfo_line;
if (_action6_override_active) group->sg_flags |= SGF_ACTION6;
act_group = group;
for (uint16_t spriteid : loaded) {
const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
group->loaded.push_back(t);
}
for (uint16_t spriteid : loading) {
const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
group->loading.push_back(t);
}
break;
}
case GSF_HOUSES:
case GSF_AIRPORTTILES:
case GSF_OBJECTS:
case GSF_INDUSTRYTILES:
case GSF_ROADSTOPS: {
byte num_building_sprites = std::max((uint8_t)1, type);
assert(TileLayoutSpriteGroup::CanAllocateItem());
TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup();
group->nfo_line = _cur.nfo_line;
if (_action6_override_active) group->sg_flags |= SGF_ACTION6;
act_group = group;
/* On error, bail out immediately. Temporary GRF data was already freed */
if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
break;
}
case GSF_INDUSTRIES: {
if (type > 2) {
grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
break;
}
assert(IndustryProductionSpriteGroup::CanAllocateItem());
IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup();
group->nfo_line = _cur.nfo_line;
if (_action6_override_active) group->sg_flags |= SGF_ACTION6;
act_group = group;
group->version = type;
if (type == 0) {
group->num_input = 3;
for (uint i = 0; i < 3; i++) {
group->subtract_input[i] = (int16_t)buf->ReadWord(); // signed
}
group->num_output = 2;
for (uint i = 0; i < 2; i++) {
group->add_output[i] = buf->ReadWord(); // unsigned
}
group->again = buf->ReadByte();
} else if (type == 1) {
group->num_input = 3;
for (uint i = 0; i < 3; i++) {
group->subtract_input[i] = buf->ReadByte();
}
group->num_output = 2;
for (uint i = 0; i < 2; i++) {
group->add_output[i] = buf->ReadByte();
}
group->again = buf->ReadByte();
} else if (type == 2) {
group->num_input = buf->ReadByte();
if (group->num_input > lengthof(group->subtract_input)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
error->data = "too many inputs (max 16)";
return;
}
for (uint i = 0; i < group->num_input; i++) {
byte rawcargo = buf->ReadByte();
CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
if (cargo == INVALID_CARGO) {
/* The mapped cargo is invalid. This is permitted at this point,
* as long as the result is not used. Mark it invalid so this
* can be tested later. */
group->version = 0xFF;
} else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
error->data = "duplicate input cargo";
return;
}
group->cargo_input[i] = cargo;
group->subtract_input[i] = buf->ReadByte();
}
group->num_output = buf->ReadByte();
if (group->num_output > lengthof(group->add_output)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
error->data = "too many outputs (max 16)";
return;
}
for (uint i = 0; i < group->num_output; i++) {
byte rawcargo = buf->ReadByte();
CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
if (cargo == INVALID_CARGO) {
/* Mark this result as invalid to use */
group->version = 0xFF;
} else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
error->data = "duplicate output cargo";
return;
}
group->cargo_output[i] = cargo;
group->add_output[i] = buf->ReadByte();
}
group->again = buf->ReadByte();
} else {
NOT_REACHED();
}
break;
}
case GSF_FAKE_TOWNS:
act_group = NewCallbackResultSpriteGroupNoTransform(CALLBACK_FAILED);
break;
/* Loading of Tile Layout and Production Callback groups would happen here */
default: grfmsg(1, "NewSpriteGroup: Unsupported feature %s, skipping", GetFeatureString(feature));
}
}
}
if ((size_t)setid >= _cur.spritegroups.size()) _cur.spritegroups.resize(setid + 1);
_cur.spritegroups[setid] = act_group;
}
static CargoID TranslateCargo(uint8_t feature, uint8_t ctype)
{
/* Special cargo types for purchase list and stations */
if ((feature == GSF_STATIONS || feature == GSF_ROADSTOPS) && ctype == 0xFE) return SpriteGroupCargo::SG_DEFAULT_NA;
if (ctype == 0xFF) return SpriteGroupCargo::SG_PURCHASE;
if (_cur.grffile->cargo_list.empty()) {
/* No cargo table, so use bitnum values */
if (ctype >= 32) {
grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
return INVALID_CARGO;
}
for (const CargoSpec *cs : CargoSpec::Iterate()) {
if (cs->bitnum == ctype) {
grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, cs->Index());
return cs->Index();
}
}
grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
return INVALID_CARGO;
}
/* Check if the cargo type is out of bounds of the cargo translation table */
if (ctype >= _cur.grffile->cargo_list.size()) {
grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
return INVALID_CARGO;
}
/* Look up the cargo label from the translation table */
CargoLabel cl = _cur.grffile->cargo_list[ctype];
if (cl == CT_INVALID) {
grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
return INVALID_CARGO;
}
CargoID cid = GetCargoIDByLabel(cl);
if (cid == INVALID_CARGO) {
grfmsg(5, "TranslateCargo: Cargo '%c%c%c%c' unsupported, skipping.", GB(cl.base(), 24, 8), GB(cl.base(), 16, 8), GB(cl.base(), 8, 8), GB(cl.base(), 0, 8));
return INVALID_CARGO;
}
grfmsg(6, "TranslateCargo: Cargo '%c%c%c%c' mapped to cargo type %d.", GB(cl.base(), 24, 8), GB(cl.base(), 16, 8), GB(cl.base(), 8, 8), GB(cl.base(), 0, 8), cid);
return cid;
}
static bool IsValidGroupID(uint16_t groupid, const char *function)
{
if ((size_t)groupid >= _cur.spritegroups.size() || _cur.spritegroups[groupid] == nullptr) {
grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
return false;
}
return true;
}
static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8_t idcount)
{
static EngineID *last_engines;
static uint last_engines_count;
bool wagover = false;
/* Test for 'wagon override' flag */
if (HasBit(idcount, 7)) {
wagover = true;
/* Strip off the flag */
idcount = GB(idcount, 0, 7);
if (last_engines_count == 0) {
grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
return;
}
grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
last_engines_count, idcount);
} else {
if (last_engines_count != idcount) {
last_engines = ReallocT(last_engines, idcount);
last_engines_count = idcount;
}
}
EngineID *engines = AllocaM(EngineID, idcount);
for (uint i = 0; i < idcount; i++) {
Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
if (e == nullptr) {
/* No engine could be allocated?!? Deal with it. Okay,
* this might look bad. Also make sure this NewGRF
* gets disabled, as a half loaded one is bad. */
HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, (GrfSpecFeature)0, 0);
return;
}
engines[i] = e->index;
if (!wagover) last_engines[i] = engines[i];
}
uint8_t cidcount = buf->ReadByte();
for (uint c = 0; c < cidcount; c++) {
uint8_t ctype = buf->ReadByte();
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
CargoID cid = TranslateCargo(feature, ctype);
if (cid == INVALID_CARGO) continue;
for (uint i = 0; i < idcount; i++) {
EngineID engine = engines[i];
grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
if (wagover) {
SetWagonOverrideSprites(engine, cid, GetGroupByID(groupid), last_engines, last_engines_count);
} else {
SetCustomEngineSprites(engine, cid, GetGroupByID(groupid));
}
}
}
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
grfmsg(8, "-- Default group id 0x%04X", groupid);
for (uint i = 0; i < idcount; i++) {
EngineID engine = engines[i];
if (wagover) {
SetWagonOverrideSprites(engine, SpriteGroupCargo::SG_DEFAULT, GetGroupByID(groupid), last_engines, last_engines_count);
} else {
SetCustomEngineSprites(engine, SpriteGroupCargo::SG_DEFAULT, GetGroupByID(groupid));
SetEngineGRF(engine, _cur.grffile);
}
}
}
static void CanalMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
uint16_t *cfs = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
cfs[i] = buf->ReadExtendedByte();
}
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
uint16_t cf = cfs[i];
if (cf >= CF_END) {
grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
continue;
}
_water_feature[cf].grffile = _cur.grffile;
_water_feature[cf].group = GetGroupByID(groupid);
}
}
static void StationMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
if (_cur.grffile->stations.empty()) {
grfmsg(1, "StationMapSpriteGroup: No stations defined, skipping");
return;
}
uint16_t *stations = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
stations[i] = buf->ReadExtendedByte();
}
uint8_t cidcount = buf->ReadByte();
for (uint c = 0; c < cidcount; c++) {
uint8_t ctype = buf->ReadByte();
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
ctype = TranslateCargo(GSF_STATIONS, ctype);
if (ctype == INVALID_CARGO) continue;
for (uint i = 0; i < idcount; i++) {
StationSpec *statspec = stations[i] >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[stations[i]].get();
if (statspec == nullptr) {
grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%X undefined, skipping", stations[i]);
continue;
}
statspec->grf_prop.spritegroup[ctype] = GetGroupByID(groupid);
}
}
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
StationSpec *statspec = stations[i] >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[stations[i]].get();
if (statspec == nullptr) {
grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%X undefined, skipping", stations[i]);
continue;
}
if (statspec->grf_prop.grffile != nullptr) {
grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%X mapped multiple times, skipping", stations[i]);
continue;
}
statspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = GetGroupByID(groupid);
statspec->grf_prop.grffile = _cur.grffile;
statspec->grf_prop.local_id = stations[i];
StationClass::Assign(statspec);
}
}
static void TownHouseMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
if (_cur.grffile->housespec.empty()) {
grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
return;
}
uint16_t *houses = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
houses[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
HouseSpec *hs = houses[i] >= _cur.grffile->housespec.size() ? nullptr : _cur.grffile->housespec[houses[i]].get();
if (hs == nullptr) {
grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
continue;
}
hs->grf_prop.spritegroup[0] = GetGroupByID(groupid);
}
}
static void IndustryMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
if (_cur.grffile->industryspec.empty()) {
grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
return;
}
uint16_t *industries = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
industries[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
IndustrySpec *indsp = industries[i] >= _cur.grffile->industryspec.size() ? nullptr : _cur.grffile->industryspec[industries[i]].get();
if (indsp == nullptr) {
grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
continue;
}
indsp->grf_prop.spritegroup[0] = GetGroupByID(groupid);
}
}
static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
if (_cur.grffile->indtspec.empty()) {
grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
return;
}
uint16_t *indtiles = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
indtiles[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
IndustryTileSpec *indtsp = indtiles[i] >= _cur.grffile->indtspec.size() ? nullptr : _cur.grffile->indtspec[indtiles[i]].get();
if (indtsp == nullptr) {
grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
continue;
}
indtsp->grf_prop.spritegroup[0] = GetGroupByID(groupid);
}
}
static void CargoMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
uint16_t *cargoes = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
cargoes[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
uint16_t cid = cargoes[i];
if (cid >= NUM_CARGO) {
grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
continue;
}
CargoSpec *cs = CargoSpec::Get(cid);
cs->grffile = _cur.grffile;
cs->group = GetGroupByID(groupid);
}
}
static void SignalsMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
uint16_t *ids = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
ids[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "SignalsMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
uint16_t id = ids[i];
switch (id) {
case NSA3ID_CUSTOM_SIGNALS:
_cur.grffile->new_signals_group = GetGroupByID(groupid);
if (!HasBit(_cur.grffile->new_signal_ctrl_flags, NSCF_GROUPSET)) {
SetBit(_cur.grffile->new_signal_ctrl_flags, NSCF_GROUPSET);
_new_signals_grfs.push_back(_cur.grffile);
}
break;
default:
grfmsg(1, "SignalsMapSpriteGroup: ID not implemented: %d", id);
break;
}
}
}
static void ObjectMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
if (_cur.grffile->objectspec.empty()) {
grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
return;
}
uint16_t *objects = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
objects[i] = buf->ReadExtendedByte();
}
uint8_t cidcount = buf->ReadByte();
for (uint c = 0; c < cidcount; c++) {
uint8_t ctype = buf->ReadByte();
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
/* The only valid option here is purchase list sprite groups. */
if (ctype != 0xFF) {
grfmsg(1, "ObjectMapSpriteGroup: Invalid cargo bitnum %d for objects, skipping.", ctype);
continue;
}
for (uint i = 0; i < idcount; i++) {
ObjectSpec *spec = (objects[i] >= _cur.grffile->objectspec.size()) ? nullptr : _cur.grffile->objectspec[objects[i]].get();
if (spec == nullptr) {
grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%X undefined, skipping", objects[i]);
continue;
}
spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_PURCHASE] = GetGroupByID(groupid);
}
}
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
ObjectSpec *spec = (objects[i] >= _cur.grffile->objectspec.size()) ? nullptr : _cur.grffile->objectspec[objects[i]].get();
if (spec == nullptr) {
grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%X undefined, skipping", objects[i]);
continue;
}
if (spec->grf_prop.grffile != nullptr) {
grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%X mapped multiple times, skipping", objects[i]);
continue;
}
spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_DEFAULT] = GetGroupByID(groupid);
spec->grf_prop.grffile = _cur.grffile;
spec->grf_prop.local_id = objects[i];
}
}
static void RailTypeMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
uint8_t *railtypes = AllocaM(uint8_t, idcount);
for (uint i = 0; i < idcount; i++) {
uint16_t id = buf->ReadExtendedByte();
railtypes[i] = id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE;
}
uint8_t cidcount = buf->ReadByte();
for (uint c = 0; c < cidcount; c++) {
uint8_t ctype = buf->ReadByte();
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
if (ctype >= RTSG_END) continue;
extern RailTypeInfo _railtypes[RAILTYPE_END];
for (uint i = 0; i < idcount; i++) {
if (railtypes[i] != INVALID_RAILTYPE) {
RailTypeInfo *rti = &_railtypes[railtypes[i]];
rti->grffile[ctype] = _cur.grffile;
rti->group[ctype] = GetGroupByID(groupid);
}
}
}
/* Railtypes do not use the default group. */
buf->ReadWord();
}
static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8_t idcount, RoadTramType rtt)
{
RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
uint8_t *roadtypes = AllocaM(uint8_t, idcount);
for (uint i = 0; i < idcount; i++) {
uint16_t id = buf->ReadExtendedByte();
roadtypes[i] = id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE;
}
uint8_t cidcount = buf->ReadByte();
for (uint c = 0; c < cidcount; c++) {
uint8_t ctype = buf->ReadByte();
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
if (ctype >= ROTSG_END) continue;
extern RoadTypeInfo _roadtypes[ROADTYPE_END];
for (uint i = 0; i < idcount; i++) {
if (roadtypes[i] != INVALID_ROADTYPE) {
RoadTypeInfo *rti = &_roadtypes[roadtypes[i]];
rti->grffile[ctype] = _cur.grffile;
rti->group[ctype] = GetGroupByID(groupid);
}
}
}
/* Roadtypes do not use the default group. */
buf->ReadWord();
}
static void AirportMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
if (_cur.grffile->airportspec.empty()) {
grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
return;
}
uint16_t *airports = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
airports[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
AirportSpec *as = airports[i] >= _cur.grffile->airportspec.size() ? nullptr : _cur.grffile->airportspec[airports[i]].get();
if (as == nullptr) {
grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
continue;
}
as->grf_prop.spritegroup[0] = GetGroupByID(groupid);
}
}
static void AirportTileMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
if (_cur.grffile->airtspec.empty()) {
grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
return;
}
uint16_t *airptiles = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
airptiles[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
AirportTileSpec *airtsp = airptiles[i] >= _cur.grffile->airtspec.size() ? nullptr : _cur.grffile->airtspec[airptiles[i]].get();
if (airtsp == nullptr) {
grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
continue;
}
airtsp->grf_prop.spritegroup[0] = GetGroupByID(groupid);
}
}
static void RoadStopMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
uint16_t *roadstops = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
roadstops[i] = buf->ReadExtendedByte();
}
uint8_t cidcount = buf->ReadByte();
for (uint c = 0; c < cidcount; c++) {
uint8_t ctype = buf->ReadByte();
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) continue;
ctype = TranslateCargo(GSF_ROADSTOPS, ctype);
if (ctype == INVALID_CARGO) continue;
for (uint i = 0; i < idcount; i++) {
RoadStopSpec *roadstopspec = (roadstops[i] >= _cur.grffile->roadstops.size()) ? nullptr : _cur.grffile->roadstops[roadstops[i]].get();
if (roadstopspec == nullptr) {
grfmsg(1, "RoadStopMapSpriteGroup: Road stop with ID 0x%X does not exist, skipping", roadstops[i]);
continue;
}
roadstopspec->grf_prop.spritegroup[ctype] = GetGroupByID(groupid);
}
}
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) return;
if (_cur.grffile->roadstops.empty()) {
grfmsg(0, "RoadStopMapSpriteGroup: No roadstops defined, skipping.");
return;
}
for (uint i = 0; i < idcount; i++) {
RoadStopSpec *roadstopspec = (roadstops[i] >= _cur.grffile->roadstops.size()) ? nullptr : _cur.grffile->roadstops[roadstops[i]].get();
if (roadstopspec == nullptr) {
grfmsg(1, "RoadStopMapSpriteGroup: Road stop with ID 0x%X does not exist, skipping.", roadstops[i]);
continue;
}
if (roadstopspec->grf_prop.grffile != nullptr) {
grfmsg(1, "RoadStopMapSpriteGroup: Road stop with ID 0x%X mapped multiple times, skipping", roadstops[i]);
continue;
}
roadstopspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = GetGroupByID(groupid);
roadstopspec->grf_prop.grffile = _cur.grffile;
roadstopspec->grf_prop.local_id = roadstops[i];
RoadStopClass::Assign(roadstopspec);
}
}
static void NewLandscapeMapSpriteGroup(ByteReader *buf, uint8_t idcount)
{
uint16_t *ids = AllocaM(uint16_t, idcount);
for (uint i = 0; i < idcount; i++) {
ids[i] = buf->ReadExtendedByte();
}
/* Skip the cargo type section, we only care about the default group */
uint8_t cidcount = buf->ReadByte();
buf->Skip(cidcount * 3);
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "NewLandscapeMapSpriteGroup")) return;
for (uint i = 0; i < idcount; i++) {
uint16_t id = ids[i];
switch (id) {
case NLA3ID_CUSTOM_ROCKS:
_cur.grffile->new_rocks_group = GetGroupByID(groupid);
if (!HasBit(_cur.grffile->new_landscape_ctrl_flags, NLCF_ROCKS_SET)) {
SetBit(_cur.grffile->new_landscape_ctrl_flags, NLCF_ROCKS_SET);
_new_landscape_rocks_grfs.push_back(_cur.grffile);
}
break;
default:
grfmsg(1, "NewLandscapeMapSpriteGroup: ID not implemented: %d", id);
break;
}
}
}
/* Action 0x03 */
static void FeatureMapSpriteGroup(ByteReader *buf)
{
/* <03> ... []...
* id-list := [] [id-list]
* cargo-list := [cargo-list]
*
* B feature see action 0
* B n-id bits 0-6: how many IDs this definition applies to
* bit 7: if set, this is a wagon override definition (see below)
* E ids the IDs for which this definition applies
* B num-cid number of cargo IDs (sprite group IDs) in this definition
* can be zero, in that case the def-cid is used always
* B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
* W cid cargo ID (sprite group ID) for this type of cargo
* W def-cid default cargo ID (sprite group ID) */
GrfSpecFeatureRef feature_ref = ReadFeature(buf->ReadByte());
GrfSpecFeature feature = feature_ref.id;
uint8_t idcount = buf->ReadByte();
if (feature >= GSF_END) {
grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature %s, skipping", GetFeatureString(feature_ref));
return;
}
/* If idcount is zero, this is a feature callback */
if (idcount == 0) {
/* Skip number of cargo ids? */
buf->ReadByte();
uint16_t groupid = buf->ReadWord();
if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature %s", GetFeatureString(feature_ref));
AddGenericCallback(feature, _cur.grffile, GetGroupByID(groupid));
return;
}
/* Mark the feature as used by the grf (generic callbacks do not count) */
SetBit(_cur.grffile->grf_features, feature);
grfmsg(6, "FeatureMapSpriteGroup: Feature %s, %d ids", GetFeatureString(feature_ref), idcount);
switch (feature) {
case GSF_TRAINS:
case GSF_ROADVEHICLES:
case GSF_SHIPS:
case GSF_AIRCRAFT:
VehicleMapSpriteGroup(buf, feature, idcount);
return;
case GSF_CANALS:
CanalMapSpriteGroup(buf, idcount);
return;
case GSF_STATIONS:
StationMapSpriteGroup(buf, idcount);
return;
case GSF_HOUSES:
TownHouseMapSpriteGroup(buf, idcount);
return;
case GSF_INDUSTRIES:
IndustryMapSpriteGroup(buf, idcount);
return;
case GSF_INDUSTRYTILES:
IndustrytileMapSpriteGroup(buf, idcount);
return;
case GSF_CARGOES:
CargoMapSpriteGroup(buf, idcount);
return;
case GSF_AIRPORTS:
AirportMapSpriteGroup(buf, idcount);
return;
case GSF_SIGNALS:
SignalsMapSpriteGroup(buf, idcount);
break;
case GSF_OBJECTS:
ObjectMapSpriteGroup(buf, idcount);
break;
case GSF_RAILTYPES:
RailTypeMapSpriteGroup(buf, idcount);
break;
case GSF_ROADTYPES:
RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
break;
case GSF_TRAMTYPES:
RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
break;
case GSF_AIRPORTTILES:
AirportTileMapSpriteGroup(buf, idcount);
return;
case GSF_ROADSTOPS:
RoadStopMapSpriteGroup(buf, idcount);
return;
case GSF_NEWLANDSCAPE:
NewLandscapeMapSpriteGroup(buf, idcount);
return;
default:
grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature %s, skipping", GetFeatureString(feature_ref));
return;
}
}
/* Action 0x04 */
static void FeatureNewName(ByteReader *buf)
{
/* <04>
*
* B veh-type see action 0 (as 00..07, + 0A
* But IF veh-type = 48, then generic text
* B language-id If bit 6 is set, This is the extended language scheme,
* with up to 64 language.
* Otherwise, it is a mapping where set bits have meaning
* 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
* Bit 7 set means this is a generic text, not a vehicle one (or else)
* B num-veh number of vehicles which are getting a new name
* B/W offset number of the first vehicle that gets a new name
* Byte : ID of vehicle to change
* Word : ID of string to change/add
* S data new texts, each of them zero-terminated, after
* which the next name begins. */
bool new_scheme = _cur.grffile->grf_version >= 7;
GrfSpecFeatureRef feature_ref = ReadFeature(buf->ReadByte(), true);
GrfSpecFeature feature = feature_ref.id;
if (feature >= GSF_END && feature != 0x48) {
grfmsg(1, "FeatureNewName: Unsupported feature %s, skipping", GetFeatureString(feature_ref));
return;
}
uint8_t lang = buf->ReadByte();
uint8_t num = buf->ReadByte();
bool generic = HasBit(lang, 7);
uint16_t id;
if (generic) {
id = buf->ReadWord();
} else if (feature <= GSF_AIRCRAFT) {
id = buf->ReadExtendedByte();
} else {
id = buf->ReadByte();
}
ClrBit(lang, 7);
uint16_t endid = id + num;
grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature %s) in language 0x%02X",
id, endid, GetFeatureString(feature), lang);
for (; id < endid && buf->HasData(); id++) {
const char *name = buf->ReadString();
grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
switch (feature) {
case GSF_TRAINS:
case GSF_ROADVEHICLES:
case GSF_SHIPS:
case GSF_AIRCRAFT:
if (!generic) {
Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
if (e == nullptr) break;
StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
e->info.string_id = string;
} else {
AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
}
break;
default:
if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0x10000)) {
AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
break;
}
switch (GB(id, 8, 8)) {
case 0xC4: // Station class name
if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
} else {
StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
}
break;
case 0xC5: // Station name
if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
} else {
_cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
}
break;
case 0xC7: // Airporttile name
if (GB(id, 0, 8) >= _cur.grffile->airtspec.size() || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
} else {
_cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
}
break;
case 0xC9: // House name
if (GB(id, 0, 8) >= _cur.grffile->housespec.size() || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
} else {
_cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
}
break;
default:
grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
break;
}
break;
}
}
}
/**
* Sanitize incoming sprite offsets for Action 5 graphics replacements.
* @param num The number of sprites to load.
* @param offset Offset from the base.
* @param max_sprites The maximum number of sprites that can be loaded in this action 5.
* @param name Used for error warnings.
* @return The number of sprites that is going to be skipped.
*/
static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const char *name)
{
if (offset >= max_sprites) {
grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
uint orig_num = num;
num = 0;
return orig_num;
}
if (offset + num > max_sprites) {
grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
uint orig_num = num;
num = std::max(max_sprites - offset, 0);
return orig_num - num;
}
return 0;
}
/** The information about action 5 types. */
static const Action5Type _action5_types[] = {
/* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
/* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
/* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
/* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
/* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
/* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
/* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
/* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
/* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
/* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
/* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
/* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
/* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
/* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
/* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
/* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
/* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
/* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
/* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
/* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
/* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
/* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
/* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
/* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
/* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
/* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
};
/* Action 0x05 */
static void GraphicsNew(ByteReader *buf)
{
/* <05>
*
* B graphics-type What set of graphics the sprites define.
* E num-sprites How many sprites are in this set?
* V other data Graphics type specific data. Currently unused. */
uint8_t type = buf->ReadByte();
uint16_t num = buf->ReadExtendedByte();
uint16_t offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
const Action5Type *action5_type;
const Action5TypeRemapSet &remap = _cur.grffile->action5_type_remaps;
if (remap.remapped_ids[type]) {
auto iter = remap.mapping.find(type);
assert(iter != remap.mapping.end());
const Action5TypeRemapEntry &def = iter->second;
if (def.info == nullptr) {
if (def.fallback_mode == GPMFM_ERROR_ON_USE) {
grfmsg(0, "Error: Unimplemented action 5 type: %s, mapped to: %X", def.name, type);
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_UNIMPLEMETED_MAPPED_ACTION5_TYPE);
error->data = stredup(def.name);
error->param_value[1] = type;
} else if (def.fallback_mode == GPMFM_IGNORE) {
grfmsg(2, "Ignoring unimplemented action 5 type: %s, mapped to: %X", def.name, type);
}
_cur.skip_sprites = num;
return;
} else {
action5_type = def.info;
}
} else {
if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
/* Special not-TTDP-compatible case used in openttd.grf
* Missing shore sprites and initialisation of SPR_SHORE_BASE */
grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
return;
}
/* Supported type? */
if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
_cur.skip_sprites = num;
return;
}
action5_type = &_action5_types[type];
}
/* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
* except for the long version of the shore type:
* Ignore offset if not allowed */
if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an field. Ignoring offset.", action5_type->name, type);
offset = 0;
}
/* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
* This does not make sense, if is allowed */
if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
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);
_cur.skip_sprites = num;
return;
}
/* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
uint16_t skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
SpriteID replace = action5_type->sprite_base + offset;
/* Load sprites starting from , then skip sprites. */
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);
if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
if (type == 0x0B) {
static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
}
/* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */
bool dup_oneway_sprites = ((type == 0x09) && (offset + num <= SPR_ONEWAY_SLOPE_N_OFFSET));
for (uint16_t n = num; n > 0; n--) {
_cur.nfo_line++;
int load_index = (replace == 0 ? _cur.spriteid++ : replace++);
LoadNextSprite(load_index, *_cur.file, _cur.nfo_line);
if (dup_oneway_sprites) {
DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_N_OFFSET);
DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_S_OFFSET);
}
}
if (type == 0x04 && ((_cur.grfconfig->ident.grfid & 0x00FFFFFF) == OPENTTD_GRAPHICS_BASE_GRF_ID ||
_cur.grfconfig->ident.grfid == BSWAP32(0xFF4F4701) || _cur.grfconfig->ident.grfid == BSWAP32(0xFFFFFFFE))) {
/* Signal graphics action 5: Fill duplicate signal sprite block if this is a baseset GRF or OpenGFX */
const SpriteID end = offset + num;
for (SpriteID i = offset; i < end; i++) {
DupSprite(SPR_SIGNALS_BASE + i, SPR_DUP_SIGNALS_BASE + i);
}
}
_cur.skip_sprites = skip_num;
}
/* Action 0x05 (SKIP) */
static void SkipAct5(ByteReader *buf)
{
/* Ignore type byte */
buf->ReadByte();
/* Skip the sprites of this action */
_cur.skip_sprites = buf->ReadExtendedByte();
grfmsg(3, "SkipAct5: Skipping %d sprites", _cur.skip_sprites);
}
/**
* Reads a variable common to VarAction2 and Action7/9/D.
*
* Returns VarAction2 variable 'param' resp. Action7/9/D variable '0x80 + param'.
* If a variable is not accessible from all four actions, it is handled in the action specific functions.
*
* @param param variable number (as for VarAction2, for Action7/9/D you have to subtract 0x80 first).
* @param value returns the value of the variable.
* @param grffile NewGRF querying the variable
* @return true iff the variable is known and the value is returned in 'value'.
*/
bool GetGlobalVariable(byte param, uint32_t *value, const GRFFile *grffile)
{
if (_sprite_group_resolve_check_veh_check) {
switch (param) {
case 0x00:
case 0x02:
case 0x09:
case 0x0A:
case 0x20:
case 0x23:
_sprite_group_resolve_check_veh_check = false;
break;
}
}
switch (param) {
case 0x00: // current date
*value = std::max(CalTime::CurDate() - CalTime::DAYS_TILL_ORIGINAL_BASE_YEAR, 0).base();
return true;
case 0x01: // current year
*value = (Clamp(CalTime::CurYear(), CalTime::ORIGINAL_BASE_YEAR, CalTime::ORIGINAL_MAX_YEAR) - CalTime::ORIGINAL_BASE_YEAR).base();
return true;
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)
CalTime::Date start_of_year = CalTime::ConvertYMDToDate(CalTime::CurYear(), 0, 1);
*value = CalTime::CurMonth() | (CalTime::CurDay() - 1) << 8 | (CalTime::IsLeapYear(CalTime::CurYear()) ? 1 << 15 : 0) | (CalTime::CurDate() - start_of_year).base() << 16;
return true;
}
case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
*value = _settings_game.game_creation.landscape;
return true;
case 0x06: // road traffic side, bit 4 clear=left, set=right
*value = _settings_game.vehicle.road_side << 4;
return true;
case 0x09: // date fraction
*value = CalTime::CurDateFract() * 885;
return true;
case 0x0A: // animation counter
*value = GB(_scaled_tick_counter, 0, 16);
return true;
case 0x0B: { // TTDPatch version
uint major = 2;
uint minor = 6;
uint revision = 1; // special case: 2.0.1 is 2.0.10
uint build = 1382;
*value = (major << 24) | (minor << 20) | (revision << 16) | build;
return true;
}
case 0x0D: // TTD Version, 00=DOS, 01=Windows
*value = (_cur.grfconfig->palette & GRFP_USE_MASK) | grffile->var8D_overlay;
return true;
case 0x0E: // Y-offset for train sprites
*value = _cur.grffile->traininfo_vehicle_pitch;
return true;
case 0x0F: // Rail track type cost factors
*value = 0;
SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
if (_settings_game.vehicle.disable_elrails) {
/* skip elrail multiplier - disabled */
SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
} else {
SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
/* Skip monorail multiplier - no space in result */
}
SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
return true;
case 0x11: // current rail tool type
*value = 0; // constant fake value to avoid desync
return true;
case 0x12: // Game mode
*value = _game_mode;
return true;
/* case 0x13: // Tile refresh offset to left not implemented */
/* case 0x14: // Tile refresh offset to right not implemented */
/* case 0x15: // Tile refresh offset upwards not implemented */
/* case 0x16: // Tile refresh offset downwards not implemented */
/* case 0x17: // temperate snow line not implemented */
case 0x1A: // Always -1
*value = UINT_MAX;
return true;
case 0x1B: // Display options
*value = 0x3F; // constant fake value to avoid desync
return true;
case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD, also used for feature tests (bits 31..4)
*value = 1 | grffile->var9D_overlay;
return true;
case 0x1E: // Miscellaneous GRF features
*value = _misc_grf_features;
/* Add the local flags */
assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
return true;
/* case 0x1F: // locale dependent settings not implemented to avoid desync */
case 0x20: { // snow line height
byte snowline = GetSnowLine();
if (_settings_game.game_creation.landscape == LT_ARCTIC && snowline <= _settings_game.construction.map_height_limit) {
*value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
} else {
/* No snow */
*value = 0xFF;
}
return true;
}
case 0x21: // OpenTTD version
*value = _openttd_newgrf_version;
return true;
case 0x22: // difficulty level
*value = SP_CUSTOM;
return true;
case 0x23: // long format date
*value = CalTime::CurDate().base();
return true;
case 0x24: // long format year
*value = CalTime::CurYear().base();
return true;
default: return false;
}
}
static uint32_t GetParamVal(byte param, uint32_t *cond_val)
{
/* First handle variable common with VarAction2 */
uint32_t value;
if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
/* Non-common variable */
switch (param) {
case 0x84: { // GRF loading stage
uint32_t res = 0;
if (_cur.stage > GLS_INIT) SetBit(res, 0);
if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
return res;
}
case 0x85: // TTDPatch flags, only for bit tests
if (cond_val == nullptr) {
/* Supported in Action 0x07 and 0x09, not 0x0D */
return 0;
} else {
uint32_t index = *cond_val / 0x20;
*cond_val %= 0x20;
uint32_t param_val = 0;
if (index < lengthof(_ttdpatch_flags)) {
param_val = _ttdpatch_flags[index];
if (!HasBit(_cur.grfconfig->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
SetBit(_observed_ttdpatch_flags[index], *cond_val);
}
}
return param_val;
}
case 0x88: // GRF ID check
return 0;
/* case 0x99: Global ID offset not implemented */
default:
/* GRF Parameter */
if (param < 0x80) return _cur.grffile->GetParam(param);
/* In-game variable. */
grfmsg(1, "Unsupported in-game variable 0x%02X", param);
return UINT_MAX;
}
}
/* Action 0x06 */
static void CfgApply(ByteReader *buf)
{
/* <06> ...
*
* B param-num Number of parameter to substitute (First = "zero")
* Ignored if that parameter was not specified in newgrf.cfg
* B param-size How many bytes to replace. If larger than 4, the
* bytes of the following parameter are used. In that
* case, nothing is applied unless *all* parameters
* were specified.
* B offset Offset into data from beginning of next sprite
* to place where parameter is to be stored. */
/* Preload the next sprite */
SpriteFile &file = *_cur.file;
size_t pos = file.GetPos();
uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
uint8_t type = file.ReadByte();
/* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
if (type != 0xFF) {
grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
/* Reset the file position to the start of the next sprite */
file.SeekTo(pos, SEEK_SET);
return;
}
/* Get (or create) the override for the next sprite. */
GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
std::unique_ptr &preload_sprite = _grf_line_to_action6_sprite_override[location];
/* Load new sprite data if it hasn't already been loaded. */
if (preload_sprite == nullptr) {
preload_sprite = std::make_unique(num);
file.ReadBlock(preload_sprite.get(), num);
}
/* Reset the file position to the start of the next sprite */
file.SeekTo(pos, SEEK_SET);
/* Now perform the Action 0x06 on our data. */
for (;;) {
uint i;
uint param_num;
uint param_size;
uint offset;
bool add_value;
/* Read the parameter to apply. 0xFF indicates no more data to change. */
param_num = buf->ReadByte();
if (param_num == 0xFF) break;
/* Get the size of the parameter to use. If the size covers multiple
* double words, sequential parameter values are used. */
param_size = buf->ReadByte();
/* Bit 7 of param_size indicates we should add to the original value
* instead of replacing it. */
add_value = HasBit(param_size, 7);
param_size = GB(param_size, 0, 7);
/* Where to apply the data to within the pseudo sprite data. */
offset = buf->ReadExtendedByte();
/* If the parameter is a GRF parameter (not an internal variable) check
* if it (and all further sequential parameters) has been defined. */
if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
break;
}
grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
bool carry = false;
for (i = 0; i < param_size && offset + i < num; i++) {
uint32_t value = GetParamVal(param_num + i / 4, nullptr);
/* Reset carry flag for each iteration of the variable (only really
* matters if param_size is greater than 4) */
if (i % 4 == 0) carry = false;
if (add_value) {
uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
preload_sprite[offset + i] = GB(new_value, 0, 8);
/* Check if the addition overflowed */
carry = new_value >= 256;
} else {
preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
}
}
}
}
/**
* Disable a static NewGRF when it is influencing another (non-static)
* NewGRF as this could cause desyncs.
*
* We could just tell the NewGRF querying that the file doesn't exist,
* but that might give unwanted results. Disabling the NewGRF gives the
* best result as no NewGRF author can complain about that.
* @param c The NewGRF to disable.
*/
static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
{
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
error->data = _cur.grfconfig->GetName();
}
/* Action 0x07
* Action 0x09 */
static void SkipIf(ByteReader *buf)
{
/* <07/09>
*
* B param-num
* B param-size
* B condition-type
* V value
* B num-sprites */
uint32_t cond_val = 0;
uint32_t mask = 0;
bool result;
uint8_t param = buf->ReadByte();
uint8_t paramsize = buf->ReadByte();
uint8_t condtype = buf->ReadByte();
if (condtype < 2) {
/* Always 1 for bit tests, the given value should be ignored. */
paramsize = 1;
}
switch (paramsize) {
case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
default: break;
}
if (param < 0x80 && _cur.grffile->param_end <= param) {
grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
return;
}
grfmsg(7, "SkipIf: Test condtype %d, param 0x%02X, condval 0x%08X", condtype, param, cond_val);
/* condtypes that do not use 'param' are always valid.
* condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
*/
if (condtype >= 0x0B) {
/* Tests that ignore 'param' */
switch (condtype) {
case 0x0B: result = !IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
break;
case 0x0C: result = IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
break;
case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
break;
case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
break;
case 0x0F: {
RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
break;
}
case 0x10: {
RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
break;
}
case 0x11: {
RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
break;
}
case 0x12: {
RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
break;
}
default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
}
} else if (param == 0x88) {
/* GRF ID checks */
GRFConfig *c = GetGRFConfig(cond_val, mask);
if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
c = nullptr;
}
if (condtype != 10 && c == nullptr) {
grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
return;
}
switch (condtype) {
/* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
case 0x06: // Is GRFID active?
result = c->status == GCS_ACTIVATED;
break;
case 0x07: // Is GRFID non-active?
result = c->status != GCS_ACTIVATED;
break;
case 0x08: // GRFID is not but will be active?
result = c->status == GCS_INITIALISED;
break;
case 0x09: // GRFID is or will be active?
result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
break;
case 0x0A: // GRFID is not nor will be active
/* This is the only condtype that doesn't get ignored if the GRFID is not found */
result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
break;
default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
}
} else if (param == 0x91 && (condtype == 0x02 || condtype == 0x03) && cond_val > 0) {
const std::vector &values = _cur.grffile->var91_values;
/* condtype 0x02: skip if test result found
* condtype 0x03: skip if test result not found
*/
bool found = std::find(values.begin(), values.end(), cond_val) != values.end();
result = (found == (condtype == 0x02));
} else {
/* Tests that use 'param' and are not GRF ID checks. */
uint32_t param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
switch (condtype) {
case 0x00: result = !!(param_val & (1 << cond_val));
break;
case 0x01: result = !(param_val & (1 << cond_val));
break;
case 0x02: result = (param_val & mask) == cond_val;
break;
case 0x03: result = (param_val & mask) != cond_val;
break;
case 0x04: result = (param_val & mask) < cond_val;
break;
case 0x05: result = (param_val & mask) > cond_val;
break;
default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
}
}
if (!result) {
grfmsg(2, "SkipIf: Not skipping sprites, test was false");
return;
}
uint8_t numsprites = buf->ReadByte();
/* numsprites can be a GOTO label if it has been defined in the GRF
* file. The jump will always be the first matching label that follows
* the current nfo_line. If no matching label is found, the first matching
* label in the file is used. */
const GRFLabel *choice = nullptr;
for (const auto &label : _cur.grffile->labels) {
if (label.label != numsprites) continue;
/* Remember a goto before the current line */
if (choice == nullptr) choice = &label;
/* If we find a label here, this is definitely good */
if (label.nfo_line > _cur.nfo_line) {
choice = &label;
break;
}
}
if (choice != nullptr) {
grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
_cur.file->SeekTo(choice->pos, SEEK_SET);
_cur.nfo_line = choice->nfo_line;
return;
}
grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
_cur.skip_sprites = numsprites;
if (_cur.skip_sprites == 0) {
/* Zero means there are no sprites to skip, so
* we use -1 to indicate that all further
* sprites should be skipped. */
_cur.skip_sprites = -1;
/* If an action 8 hasn't been encountered yet, disable the grf. */
if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
DisableGrf();
}
}
}
/* Action 0x08 (GLS_FILESCAN) */
static void ScanInfo(ByteReader *buf)
{
uint8_t grf_version = buf->ReadByte();
uint32_t grfid = buf->ReadDWord();
const char *name = buf->ReadString();
_cur.grfconfig->ident.grfid = grfid;
if (grf_version < 2 || grf_version > 8) {
SetBit(_cur.grfconfig->flags, GCF_INVALID);
DEBUG(grf, 0, "%s: NewGRF \"%s\" (GRFID %08X) uses GRF version %d, which is incompatible with this version of OpenTTD.", _cur.grfconfig->GetDisplayPath(), name, BSWAP32(grfid), grf_version);
}
/* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
if (buf->HasData()) {
const char *info = buf->ReadString();
AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
}
/* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
_cur.skip_sprites = -1;
}
/* Action 0x08 */
static void GRFInfo(ByteReader *buf)
{
/* <08>
*
* B version newgrf version, currently 06
* 4*B grf-id globally unique ID of this .grf file
* S name name of this .grf set
* S info string describing the set, and e.g. author and copyright */
uint8_t version = buf->ReadByte();
uint32_t grfid = buf->ReadDWord();
const char *name = buf->ReadString();
if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
return;
}
if (_cur.grffile->grfid != grfid) {
DEBUG(grf, 0, "GRFInfo: GRFID %08X in FILESCAN stage does not match GRFID %08X in INIT/RESERVE/ACTIVATION stage", BSWAP32(_cur.grffile->grfid), BSWAP32(grfid));
_cur.grffile->grfid = grfid;
}
_cur.grffile->grf_version = version;
_cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
/* Do swap the GRFID for displaying purposes since people expect that */
DEBUG(grf, 1, "GRFInfo: Loaded GRFv%d set %08X - %s (palette: %s, version: %i)", version, BSWAP32(grfid), name, (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version);
}
/* Action 0x0A */
static void SpriteReplace(ByteReader *buf)
{
/* <0A> [ ...]
* :
*
* B num-sets How many sets of sprites to replace.
* Each set:
* B num-sprites How many sprites are in this set
* W first-sprite First sprite number to replace */
uint8_t num_sets = buf->ReadByte();
for (uint i = 0; i < num_sets; i++) {
uint8_t num_sprites = buf->ReadByte();
uint16_t first_sprite = buf->ReadWord();
grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
i, num_sprites, first_sprite
);
for (uint j = 0; j < num_sprites; j++) {
int load_index = first_sprite + j;
_cur.nfo_line++;
if (load_index < (int)SPR_PROGSIGNAL_BASE || load_index >= (int)SPR_NEWGRFS_BASE) {
LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
} else {
/* Skip sprite */
grfmsg(0, "SpriteReplace: Ignoring attempt to replace protected sprite ID: %d", load_index);
LoadNextSprite(-1, *_cur.file, _cur.nfo_line);
}
/* Shore sprites now located at different addresses.
* So detect when the old ones get replaced. */
if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
}
}
}
}
/* Action 0x0A (SKIP) */
static void SkipActA(ByteReader *buf)
{
uint8_t num_sets = buf->ReadByte();
for (uint i = 0; i < num_sets; i++) {
/* Skip the sprites this replaces */
_cur.skip_sprites += buf->ReadByte();
/* But ignore where they go */
buf->ReadWord();
}
grfmsg(3, "SkipActA: Skipping %d sprites", _cur.skip_sprites);
}
/* Action 0x0B */
static void GRFLoadError(ByteReader *buf)
{
/* <0B> [ 00] [] 00 []
*
* B severity 00: notice, continue loading grf file
* 01: warning, continue loading grf file
* 02: error, but continue loading grf file, and attempt
* loading grf again when loading or starting next game
* 03: error, abort loading and prevent loading again in
* the future (only when restarting the patch)
* B language-id see action 4, use 1F for built-in error messages
* B message-id message to show, see below
* S message for custom messages (message-id FF), text of the message
* not present for built-in messages.
* V data additional data for built-in (or custom) messages
* B parnum parameter numbers to be shown in the message (maximum of 2) */
static const StringID msgstr[] = {
STR_NEWGRF_ERROR_VERSION_NUMBER,
STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
STR_NEWGRF_ERROR_UNSET_SWITCH,
STR_NEWGRF_ERROR_INVALID_PARAMETER,
STR_NEWGRF_ERROR_LOAD_BEFORE,
STR_NEWGRF_ERROR_LOAD_AFTER,
STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
};
static const StringID sevstr[] = {
STR_NEWGRF_ERROR_MSG_INFO,
STR_NEWGRF_ERROR_MSG_WARNING,
STR_NEWGRF_ERROR_MSG_ERROR,
STR_NEWGRF_ERROR_MSG_FATAL
};
byte severity = buf->ReadByte();
byte lang = buf->ReadByte();
byte message_id = buf->ReadByte();
/* Skip the error if it isn't valid for the current language. */
if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
/* Skip the error until the activation stage unless bit 7 of the severity
* is set. */
if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur.stage);
return;
}
ClrBit(severity, 7);
if (severity >= lengthof(sevstr)) {
grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
severity = 2;
} else if (severity == 3) {
/* This is a fatal error, so make sure the GRF is deactivated and no
* more of it gets loaded. */
DisableGrf();
/* Make sure we show fatal errors, instead of silly infos from before */
_cur.grfconfig->error.reset();
}
if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
grfmsg(7, "GRFLoadError: Invalid message id.");
return;
}
if (buf->Remaining() <= 1) {
grfmsg(7, "GRFLoadError: No message data supplied.");
return;
}
/* For now we can only show one message per newgrf file. */
if (_cur.grfconfig->error.has_value()) return;
_cur.grfconfig->error = {sevstr[severity]};
GRFError *error = &_cur.grfconfig->error.value();
if (message_id == 0xFF) {
/* This is a custom error message. */
if (buf->HasData()) {
const char *message = buf->ReadString();
error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
} else {
grfmsg(7, "GRFLoadError: No custom message supplied.");
error->custom_message.clear();
}
} else {
error->message = msgstr[message_id];
}
if (buf->HasData()) {
const char *data = buf->ReadString();
error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
} else {
grfmsg(7, "GRFLoadError: No message data supplied.");
error->data.clear();
}
/* Only two parameter numbers can be used in the string. */
for (uint i = 0; i < error->param_value.size() && buf->HasData(); i++) {
uint param_number = buf->ReadByte();
error->param_value[i] = _cur.grffile->GetParam(param_number);
}
}
/* Action 0x0C */
static void GRFComment(ByteReader *buf)
{
/* <0C> []
*
* V ignored Anything following the 0C is ignored */
if (!buf->HasData()) return;
const char *text = buf->ReadString();
grfmsg(2, "GRFComment: %s", text);
}
/* Action 0x0D (GLS_SAFETYSCAN) */
static void SafeParamSet(ByteReader *buf)
{
uint8_t target = buf->ReadByte();
/* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
if (target < 0x80 || target == 0x9E) return;
/* GRM could be unsafe, but as here it can only happen after other GRFs
* are loaded, it should be okay. If the GRF tried to use the slots it
* reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
* sprites is considered safe. */
SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
/* Skip remainder of GRF */
_cur.skip_sprites = -1;
}
static uint32_t GetPatchVariable(uint8_t param)
{
switch (param) {
/* start year - 1920 */
case 0x0B: return (std::max(_settings_game.game_creation.starting_year, CalTime::ORIGINAL_BASE_YEAR) - CalTime::ORIGINAL_BASE_YEAR).base();
/* freight trains weight factor */
case 0x0E: return _settings_game.vehicle.freight_trains;
/* empty wagon speed increase */
case 0x0F: return 0;
/* plane speed factor; our patch option is reversed from TTDPatch's,
* the following is good for 1x, 2x and 4x (most common?) and...
* well not really for 3x. */
case 0x10:
switch (_settings_game.vehicle.plane_speed) {
default:
case 4: return 1;
case 3: return 2;
case 2: return 2;
case 1: return 4;
}
/* 2CC colourmap base sprite */
case 0x11: return SPR_2CCMAP_BASE;
/* map size: format = -MABXYSS
* M : the type of map
* bit 0 : set : squared map. Bit 1 is now not relevant
* clear : rectangle map. Bit 1 will indicate the bigger edge of the map
* bit 1 : set : Y is the bigger edge. Bit 0 is clear
* clear : X is the bigger edge.
* A : minimum edge(log2) of the map
* B : maximum edge(log2) of the map
* XY : edges(log2) of each side of the map.
* SS : combination of both X and Y, thus giving the size(log2) of the map
*/
case 0x13: {
byte map_bits = 0;
byte log_X = MapLogX() - 6; // subtraction is required to make the minimal size (64) zero based
byte log_Y = MapLogY() - 6;
byte max_edge = std::max(log_X, log_Y);
if (log_X == log_Y) { // we have a squared map, since both edges are identical
SetBit(map_bits, 0);
} else {
if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
}
return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
(log_X << 12) | (log_Y << 8) | (log_X + log_Y);
}
/* The maximum height of the map. */
case 0x14:
return _settings_game.construction.map_height_limit;
/* Extra foundations base sprite */
case 0x15:
return SPR_SLOPES_BASE;
/* Shore base sprite */
case 0x16:
return SPR_SHORE_BASE;
/* Game map seed */
case 0x17:
return _settings_game.game_creation.generation_seed;
default:
grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
return 0;
}
}
static uint32_t PerformGRM(uint32_t *grm, uint16_t num_ids, uint16_t count, uint8_t op, uint8_t target, const char *type)
{
uint start = 0;
uint size = 0;
if (op == 6) {
/* Return GRFID of set that reserved ID */
return grm[_cur.grffile->GetParam(target)];
}
/* With an operation of 2 or 3, we want to reserve a specific block of IDs */
if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
for (uint i = start; i < num_ids; i++) {
if (grm[i] == 0) {
size++;
} else {
if (op == 2 || op == 3) break;
start = i + 1;
size = 0;
}
if (size == count) break;
}
if (size == count) {
/* Got the slot... */
if (op == 0 || op == 3) {
grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
}
return start;
}
/* Unable to allocate */
if (op != 4 && op != 5) {
/* Deactivate GRF */
grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
return UINT_MAX;
}
grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
return UINT_MAX;
}
/** Action 0x0D: Set parameter */
static void ParamSet(ByteReader *buf)
{
/* <0D> []
*
* B target parameter number where result is stored
* B operation operation to perform, see below
* B source1 first source operand
* B source2 second source operand
* D data data to use in the calculation, not necessary
* if both source1 and source2 refer to actual parameters
*
* Operations
* 00 Set parameter equal to source1
* 01 Addition, source1 + source2
* 02 Subtraction, source1 - source2
* 03 Unsigned multiplication, source1 * source2 (both unsigned)
* 04 Signed multiplication, source1 * source2 (both signed)
* 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
* signed quantity; left shift if positive and right shift if
* negative, source1 is unsigned)
* 06 Signed bit shift, source1 by source2
* (source2 like in 05, and source1 as well)
*/
uint8_t target = buf->ReadByte();
uint8_t oper = buf->ReadByte();
uint32_t src1 = buf->ReadByte();
uint32_t src2 = buf->ReadByte();
uint32_t data = 0;
if (buf->Remaining() >= 4) data = buf->ReadDWord();
/* You can add 80 to the operation to make it apply only if the target
* is not defined yet. In this respect, a parameter is taken to be
* defined if any of the following applies:
* - it has been set to any value in the newgrf(w).cfg parameter list
* - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
* an earlier action D */
if (HasBit(oper, 7)) {
if (target < 0x80 && target < _cur.grffile->param_end) {
grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
return;
}
oper = GB(oper, 0, 7);
}
if (src2 == 0xFE) {
if (GB(data, 0, 8) == 0xFF) {
if (data == 0x0000FFFF) {
/* Patch variables */
src1 = GetPatchVariable(src1);
} else {
/* GRF Resource Management */
uint8_t op = src1;
GrfSpecFeatureRef feature_ref = ReadFeature(GB(data, 8, 8));
GrfSpecFeature feature = feature_ref.id;
uint16_t count = GB(data, 16, 16);
if (_cur.stage == GLS_RESERVE) {
if (feature == 0x08) {
/* General sprites */
if (op == 0) {
/* Check if the allocated sprites will fit below the original sprite limit */
if (_cur.spriteid + count >= 16384) {
grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
return;
}
/* Reserve space at the current sprite ID */
grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur.spriteid);
_grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
_cur.spriteid += count;
}
}
/* Ignore GRM result during reservation */
src1 = 0;
} else if (_cur.stage == GLS_ACTIVATION) {
switch (feature) {
case 0x00: // Trains
case 0x01: // Road Vehicles
case 0x02: // Ships
case 0x03: // Aircraft
if (!_settings_game.vehicle.dynamic_engines) {
src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
if (_cur.skip_sprites == -1) return;
} else {
/* GRM does not apply for dynamic engine allocation. */
switch (op) {
case 2:
case 3:
src1 = _cur.grffile->GetParam(target);
break;
default:
src1 = 0;
break;
}
}
break;
case 0x08: // General sprites
switch (op) {
case 0:
/* Return space reserved during reservation stage */
src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
break;
case 1:
src1 = _cur.spriteid;
break;
default:
grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
return;
}
break;
case 0x0B: // Cargo
/* There are two ranges: one for cargo IDs and one for cargo bitmasks */
src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
if (_cur.skip_sprites == -1) return;
break;
default: grfmsg(1, "ParamSet: GRM: Unsupported feature %s", GetFeatureString(feature_ref)); return;
}
} else {
/* Ignore GRM during initialization */
src1 = 0;
}
}
} else {
/* Read another GRF File's parameter */
const GRFFile *file = GetFileByGRFID(data);
GRFConfig *c = GetGRFConfig(data);
if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
/* Disable the read GRF if it is a static NewGRF. */
DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
src1 = 0;
} else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
src1 = 0;
} else if (src1 == 0xFE) {
src1 = c->version;
} else {
src1 = file->GetParam(src1);
}
}
} else {
/* The source1 and source2 operands refer to the grf parameter number
* like in action 6 and 7. In addition, they can refer to the special
* variables available in action 7, or they can be FF to use the value
* of . If referring to parameters that are undefined, a value
* of 0 is used instead. */
src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
}
uint32_t res;
switch (oper) {
case 0x00:
res = src1;
break;
case 0x01:
res = src1 + src2;
break;
case 0x02:
res = src1 - src2;
break;
case 0x03:
res = src1 * src2;
break;
case 0x04:
res = (int32_t)src1 * (int32_t)src2;
break;
case 0x05:
if ((int32_t)src2 < 0) {
res = src1 >> -(int32_t)src2;
} else {
res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
}
break;
case 0x06:
if ((int32_t)src2 < 0) {
res = (int32_t)src1 >> -(int32_t)src2;
} else {
res = (int32_t)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
}
break;
case 0x07: // Bitwise AND
res = src1 & src2;
break;
case 0x08: // Bitwise OR
res = src1 | src2;
break;
case 0x09: // Unsigned division
if (src2 == 0) {
res = src1;
} else {
res = src1 / src2;
}
break;
case 0x0A: // Signed division
if (src2 == 0) {
res = src1;
} else {
res = (int32_t)src1 / (int32_t)src2;
}
break;
case 0x0B: // Unsigned modulo
if (src2 == 0) {
res = src1;
} else {
res = src1 % src2;
}
break;
case 0x0C: // Signed modulo
if (src2 == 0) {
res = src1;
} else {
res = (int32_t)src1 % (int32_t)src2;
}
break;
default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
}
switch (target) {
case 0x8E: // Y-Offset for train sprites
_cur.grffile->traininfo_vehicle_pitch = res;
break;
case 0x8F: { // Rail track type cost factors
extern RailTypeInfo _railtypes[RAILTYPE_END];
_railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
if (_settings_game.vehicle.disable_elrails) {
_railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
_railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
} else {
_railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
_railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
}
_railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
break;
}
/* not implemented */
case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
case 0x94: // Tile refresh offset to right
case 0x95: // Tile refresh offset upwards
case 0x96: // Tile refresh offset downwards
case 0x97: // Snow line height -- Better supported by feature 8 property 10h (snow line table) TODO: implement by filling the entire snow line table with the given value
case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
break;
case 0x9E: // Miscellaneous GRF features
/* Set train list engine width */
_cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
/* Remove the local flags from the global flags */
ClrBit(res, GMB_TRAIN_WIDTH_32_PIXELS);
/* Only copy safe bits for static grfs */
if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
uint32_t safe_bits = 0;
SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
_misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
} else {
_misc_grf_features = res;
}
break;
case 0x9F: // locale-dependent settings
grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
break;
default:
if (target < 0x80) {
_cur.grffile->param[target] = res;
/* param is zeroed by default */
if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
} else {
grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
}
break;
}
}
/* Action 0x0E (GLS_SAFETYSCAN) */
static void SafeGRFInhibit(ByteReader *buf)
{
/* <0E>
*
* B num Number of GRFIDs that follow
* D grfids GRFIDs of the files to deactivate */
uint8_t num = buf->ReadByte();
for (uint i = 0; i < num; i++) {
uint32_t grfid = buf->ReadDWord();
/* GRF is unsafe it if tries to deactivate other GRFs */
if (grfid != _cur.grfconfig->ident.grfid) {
SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
/* Skip remainder of GRF */
_cur.skip_sprites = -1;
return;
}
}
}
/* Action 0x0E */
static void GRFInhibit(ByteReader *buf)
{
/* <0E>
*
* B num Number of GRFIDs that follow
* D grfids GRFIDs of the files to deactivate */
uint8_t num = buf->ReadByte();
for (uint i = 0; i < num; i++) {
uint32_t grfid = buf->ReadDWord();
GRFConfig *file = GetGRFConfig(grfid);
/* Unset activation flag */
if (file != nullptr && file != _cur.grfconfig) {
grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->GetDisplayPath());
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
error->data = _cur.grfconfig->GetName();
}
}
}
/** Action 0x0F - Define Town names */
static void FeatureTownName(ByteReader *buf)
{
/* <0F>
*
* B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
* V style-name Name of the style (only for final definition)
* B num-parts Number of parts in this definition
* V parts The parts */
uint32_t grfid = _cur.grffile->grfid;
GRFTownName *townname = AddGRFTownName(grfid);
byte id = buf->ReadByte();
grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
if (HasBit(id, 7)) {
/* Final definition */
ClrBit(id, 7);
bool new_scheme = _cur.grffile->grf_version >= 7;
byte lang = buf->ReadByte();
StringID style = STR_UNDEFINED;
do {
ClrBit(lang, 7);
const char *name = buf->ReadString();
std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name.c_str());
style = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
lang = buf->ReadByte();
} while (lang != 0);
townname->styles.emplace_back(style, id);
}
uint8_t parts = buf->ReadByte();
grfmsg(6, "FeatureTownName: %u parts", parts);
townname->partlists[id].reserve(parts);
for (uint partnum = 0; partnum < parts; partnum++) {
NamePartList &partlist = townname->partlists[id].emplace_back();
uint8_t texts = buf->ReadByte();
partlist.bitstart = buf->ReadByte();
partlist.bitcount = buf->ReadByte();
partlist.maxprob = 0;
grfmsg(6, "FeatureTownName: part %u contains %u texts and will use GB(seed, %u, %u)", partnum, texts, partlist.bitstart, partlist.bitcount);
partlist.parts.reserve(texts);
for (uint textnum = 0; textnum < texts; textnum++) {
NamePart &part = partlist.parts.emplace_back();
part.prob = buf->ReadByte();
if (HasBit(part.prob, 7)) {
byte ref_id = buf->ReadByte();
if (ref_id >= GRFTownName::MAX_LISTS || townname->partlists[ref_id].empty()) {
grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
DelGRFTownName(grfid);
DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
return;
}
part.id = ref_id;
grfmsg(6, "FeatureTownName: part %u, text %u, uses intermediate definition 0x%02X (with probability %u)", partnum, textnum, ref_id, part.prob & 0x7F);
} else {
const char *text = buf->ReadString();
part.text = TranslateTTDPatchCodes(grfid, 0, false, text);
grfmsg(6, "FeatureTownName: part %u, text %u, '%s' (with probability %u)", partnum, textnum, part.text.c_str(), part.prob);
}
partlist.maxprob += GB(part.prob, 0, 7);
}
grfmsg(6, "FeatureTownName: part %u, total probability %u", partnum, partlist.maxprob);
}
}
/** Action 0x10 - Define goto label */
static void DefineGotoLabel(ByteReader *buf)
{
/* <10>