Update: Translations from eints
[openttd-github.git] / src / newgrf_commons.cpp
blob822b641cbebad85a8d03ebbcef7900d66bb70974
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /**
9 * @file newgrf_commons.cpp Implementation of the class %OverrideManagerBase
10 * and its descendance, present and future.
13 #include "stdafx.h"
14 #include "debug.h"
15 #include "landscape.h"
16 #include "house.h"
17 #include "industrytype.h"
18 #include "newgrf_config.h"
19 #include "clear_map.h"
20 #include "station_map.h"
21 #include "tree_map.h"
22 #include "tunnelbridge_map.h"
23 #include "newgrf_object.h"
24 #include "genworld.h"
25 #include "newgrf_spritegroup.h"
26 #include "newgrf_text.h"
27 #include "company_base.h"
28 #include "error.h"
29 #include "strings_func.h"
30 #include "string_func.h"
32 #include "table/strings.h"
34 #include "safeguards.h"
36 /**
37 * Constructor of generic class
38 * @param offset end of original data for this entity. i.e: houses = 110
39 * @param maximum of entities this manager can deal with. i.e: houses = 512
40 * @param invalid is the ID used to identify an invalid entity id
42 OverrideManagerBase::OverrideManagerBase(uint16_t offset, uint16_t maximum, uint16_t invalid)
44 this->max_offset = offset;
45 this->max_entities = maximum;
46 this->invalid_id = invalid;
48 this->mappings.resize(this->max_entities);
49 this->entity_overrides.resize(this->max_offset);
50 std::fill(this->entity_overrides.begin(), this->entity_overrides.end(), this->invalid_id);
51 this->grfid_overrides.resize(this->max_offset);
54 /**
55 * Since the entity IDs defined by the GRF file does not necessarily correlate
56 * to those used by the game, the IDs used for overriding old entities must be
57 * translated when the entity spec is set.
58 * @param local_id ID in grf file
59 * @param grfid ID of the grf file
60 * @param entity_type original entity type
62 void OverrideManagerBase::Add(uint16_t local_id, uint32_t grfid, uint entity_type)
64 assert(entity_type < this->max_offset);
65 /* An override can be set only once */
66 if (this->entity_overrides[entity_type] != this->invalid_id) return;
67 this->entity_overrides[entity_type] = local_id;
68 this->grfid_overrides[entity_type] = grfid;
71 /** Resets the mapping, which is used while initializing game */
72 void OverrideManagerBase::ResetMapping()
74 std::fill(this->mappings.begin(), this->mappings.end(), EntityIDMapping{});
77 /** Resets the override, which is used while initializing game */
78 void OverrideManagerBase::ResetOverride()
80 std::fill(this->entity_overrides.begin(), this->entity_overrides.end(), this->invalid_id);
81 std::fill(this->grfid_overrides.begin(), this->grfid_overrides.end(), uint32_t());
84 /**
85 * Return the ID (if ever available) of a previously inserted entity.
86 * @param grf_local_id ID of this entity within the grfID
87 * @param grfid ID of the grf file
88 * @return the ID of the candidate, of the Invalid flag item ID
90 uint16_t OverrideManagerBase::GetID(uint16_t grf_local_id, uint32_t grfid) const
92 for (uint16_t id = 0; id < this->max_entities; id++) {
93 const EntityIDMapping *map = &this->mappings[id];
94 if (map->entity_id == grf_local_id && map->grfid == grfid) {
95 return id;
99 return this->invalid_id;
103 * Reserves a place in the mapping array for an entity to be installed
104 * @param grf_local_id is an arbitrary id given by the grf's author. Also known as setid
105 * @param grfid is the id of the grf file itself
106 * @param substitute_id is the original entity from which data is copied for the new one
107 * @return the proper usable slot id, or invalid marker if none is found
109 uint16_t OverrideManagerBase::AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
111 uint16_t id = this->GetID(grf_local_id, grfid);
113 /* Look to see if this entity has already been added. This is done
114 * separately from the loop below in case a GRF has been deleted, and there
115 * are any gaps in the array.
117 if (id != this->invalid_id) return id;
119 /* This entity hasn't been defined before, so give it an ID now. */
120 for (id = this->max_offset; id < this->max_entities; id++) {
121 EntityIDMapping *map = &this->mappings[id];
123 if (CheckValidNewID(id) && map->entity_id == 0 && map->grfid == 0) {
124 map->entity_id = grf_local_id;
125 map->grfid = grfid;
126 map->substitute_id = substitute_id;
127 return id;
131 return this->invalid_id;
135 * Gives the GRFID of the file the entity belongs to.
136 * @param entity_id ID of the entity being queried.
137 * @return GRFID.
139 uint32_t OverrideManagerBase::GetGRFID(uint16_t entity_id) const
141 return this->mappings[entity_id].grfid;
145 * Gives the substitute of the entity, as specified by the grf file
146 * @param entity_id of the entity being queried
147 * @return mapped id
149 uint16_t OverrideManagerBase::GetSubstituteID(uint16_t entity_id) const
151 return this->mappings[entity_id].substitute_id;
155 * Install the specs into the HouseSpecs array
156 * It will find itself the proper slot on which it will go
157 * @param hs HouseSpec read from the grf file, ready for inclusion
159 void HouseOverrideManager::SetEntitySpec(const HouseSpec *hs)
161 HouseID house_id = this->AddEntityID(hs->grf_prop.local_id, hs->grf_prop.grffile->grfid, hs->grf_prop.subst_id);
163 if (house_id == this->invalid_id) {
164 GrfMsg(1, "House.SetEntitySpec: Too many houses allocated. Ignoring.");
165 return;
168 auto &house_specs = HouseSpec::Specs();
170 /* Now that we know we can use the given id, copy the spec to its final destination. */
171 if (house_id >= house_specs.size()) house_specs.resize(house_id + 1);
172 house_specs[house_id] = *hs;
174 /* Now add the overrides. */
175 for (int i = 0; i < this->max_offset; i++) {
176 HouseSpec *overridden_hs = HouseSpec::Get(i);
178 if (this->entity_overrides[i] != hs->grf_prop.local_id || this->grfid_overrides[i] != hs->grf_prop.grffile->grfid) continue;
180 overridden_hs->grf_prop.override = house_id;
181 this->entity_overrides[i] = this->invalid_id;
182 this->grfid_overrides[i] = 0;
187 * Return the ID (if ever available) of a previously inserted entity.
188 * @param grf_local_id ID of this entity within the grfID
189 * @param grfid ID of the grf file
190 * @return the ID of the candidate, of the Invalid flag item ID
192 uint16_t IndustryOverrideManager::GetID(uint16_t grf_local_id, uint32_t grfid) const
194 uint16_t id = OverrideManagerBase::GetID(grf_local_id, grfid);
195 if (id != this->invalid_id) return id;
197 /* No mapping found, try the overrides */
198 for (id = 0; id < this->max_offset; id++) {
199 if (this->entity_overrides[id] == grf_local_id && this->grfid_overrides[id] == grfid) return id;
202 return this->invalid_id;
206 * Method to find an entity ID and to mark it as reserved for the Industry to be included.
207 * @param grf_local_id ID used by the grf file for pre-installation work (equivalent of TTDPatch's setid
208 * @param grfid ID of the current grf file
209 * @param substitute_id industry from which data has been copied
210 * @return a free entity id (slotid) if ever one has been found, or Invalid_ID marker otherwise
212 uint16_t IndustryOverrideManager::AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
214 /* This entity hasn't been defined before, so give it an ID now. */
215 for (uint16_t id = 0; id < this->max_entities; id++) {
216 /* Skip overridden industries */
217 if (id < this->max_offset && this->entity_overrides[id] != this->invalid_id) continue;
219 /* Get the real live industry */
220 const IndustrySpec *inds = GetIndustrySpec(id);
222 /* This industry must be one that is not available(enabled), mostly because of climate.
223 * And it must not already be used by a grf (grffile == nullptr).
224 * So reserve this slot here, as it is the chosen one */
225 if (!inds->enabled && inds->grf_prop.grffile == nullptr) {
226 EntityIDMapping *map = &this->mappings[id];
228 if (map->entity_id == 0 && map->grfid == 0) {
229 /* winning slot, mark it as been used */
230 map->entity_id = grf_local_id;
231 map->grfid = grfid;
232 map->substitute_id = substitute_id;
233 return id;
238 return this->invalid_id;
242 * Method to install the new industry data in its proper slot
243 * The slot assignment is internal of this method, since it requires
244 * checking what is available
245 * @param inds Industryspec that comes from the grf decoding process
247 void IndustryOverrideManager::SetEntitySpec(IndustrySpec *inds)
249 /* First step : We need to find if this industry is already specified in the savegame data. */
250 IndustryType ind_id = this->GetID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid);
252 if (ind_id == this->invalid_id) {
253 /* Not found.
254 * Or it has already been overridden, so you've lost your place.
255 * Or it is a simple substitute.
256 * We need to find a free available slot */
257 ind_id = this->AddEntityID(inds->grf_prop.local_id, inds->grf_prop.grffile->grfid, inds->grf_prop.subst_id);
258 inds->grf_prop.override = this->invalid_id; // make sure it will not be detected as overridden
261 if (ind_id == this->invalid_id) {
262 GrfMsg(1, "Industry.SetEntitySpec: Too many industries allocated. Ignoring.");
263 return;
266 /* Now that we know we can use the given id, copy the spec to its final destination... */
267 _industry_specs[ind_id] = *inds;
268 /* ... and mark it as usable*/
269 _industry_specs[ind_id].enabled = true;
272 void IndustryTileOverrideManager::SetEntitySpec(const IndustryTileSpec *its)
274 IndustryGfx indt_id = this->AddEntityID(its->grf_prop.local_id, its->grf_prop.grffile->grfid, its->grf_prop.subst_id);
276 if (indt_id == this->invalid_id) {
277 GrfMsg(1, "IndustryTile.SetEntitySpec: Too many industry tiles allocated. Ignoring.");
278 return;
281 _industry_tile_specs[indt_id] = *its;
283 /* Now add the overrides. */
284 for (int i = 0; i < this->max_offset; i++) {
285 IndustryTileSpec *overridden_its = &_industry_tile_specs[i];
287 if (this->entity_overrides[i] != its->grf_prop.local_id || this->grfid_overrides[i] != its->grf_prop.grffile->grfid) continue;
289 overridden_its->grf_prop.override = indt_id;
290 overridden_its->enabled = false;
291 this->entity_overrides[i] = this->invalid_id;
292 this->grfid_overrides[i] = 0;
297 * Method to install the new object data in its proper slot
298 * The slot assignment is internal of this method, since it requires
299 * checking what is available
300 * @param spec ObjectSpec that comes from the grf decoding process
302 void ObjectOverrideManager::SetEntitySpec(ObjectSpec *spec)
304 /* First step : We need to find if this object is already specified in the savegame data. */
305 ObjectType type = this->GetID(spec->grf_prop.local_id, spec->grf_prop.grffile->grfid);
307 if (type == this->invalid_id) {
308 /* Not found.
309 * Or it has already been overridden, so you've lost your place.
310 * Or it is a simple substitute.
311 * We need to find a free available slot */
312 type = this->AddEntityID(spec->grf_prop.local_id, spec->grf_prop.grffile->grfid, OBJECT_TRANSMITTER);
315 if (type == this->invalid_id) {
316 GrfMsg(1, "Object.SetEntitySpec: Too many objects allocated. Ignoring.");
317 return;
320 extern std::vector<ObjectSpec> _object_specs;
322 /* Now that we know we can use the given id, copy the spec to its final destination. */
323 if (type >= _object_specs.size()) _object_specs.resize(type + 1);
324 _object_specs[type] = *spec;
328 * Function used by houses (and soon industries) to get information
329 * on type of "terrain" the tile it is queries sits on.
330 * @param tile TileIndex of the tile been queried
331 * @param context The context of the tile.
332 * @return value corresponding to the grf expected format:
333 * Terrain type: 0 normal, 1 desert, 2 rainforest, 4 on or above snowline
335 uint32_t GetTerrainType(TileIndex tile, TileContext context)
337 switch (_settings_game.game_creation.landscape) {
338 case LT_TROPIC: return GetTropicZone(tile);
339 case LT_ARCTIC: {
340 bool has_snow;
341 switch (GetTileType(tile)) {
342 case MP_CLEAR:
343 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
344 if (_generating_world) goto genworld;
345 has_snow = IsSnowTile(tile) && GetClearDensity(tile) >= 2;
346 break;
348 case MP_RAILWAY: {
349 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
350 if (_generating_world) goto genworld; // we do not care about foundations here
351 RailGroundType ground = GetRailGroundType(tile);
352 has_snow = (ground == RAIL_GROUND_ICE_DESERT || (context == TCX_UPPER_HALFTILE && ground == RAIL_GROUND_HALF_SNOW));
353 break;
356 case MP_ROAD:
357 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
358 if (_generating_world) goto genworld; // we do not care about foundations here
359 has_snow = IsOnSnow(tile);
360 break;
362 case MP_TREES: {
363 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
364 if (_generating_world) goto genworld;
365 TreeGround ground = GetTreeGround(tile);
366 has_snow = (ground == TREE_GROUND_SNOW_DESERT || ground == TREE_GROUND_ROUGH_SNOW) && GetTreeDensity(tile) >= 2;
367 break;
370 case MP_TUNNELBRIDGE:
371 if (context == TCX_ON_BRIDGE) {
372 has_snow = (GetBridgeHeight(tile) > GetSnowLine());
373 } else {
374 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
375 if (_generating_world) goto genworld; // we do not care about foundations here
376 has_snow = HasTunnelBridgeSnowOrDesert(tile);
378 break;
380 case MP_STATION:
381 case MP_HOUSE:
382 case MP_INDUSTRY:
383 case MP_OBJECT:
384 /* These tiles usually have a levelling foundation. So use max Z */
385 has_snow = (GetTileMaxZ(tile) > GetSnowLine());
386 break;
388 case MP_VOID:
389 case MP_WATER:
390 genworld:
391 has_snow = (GetTileZ(tile) > GetSnowLine());
392 break;
394 default: NOT_REACHED();
396 return has_snow ? 4 : 0;
398 default: return 0;
403 * Get the tile at the given offset.
404 * @param parameter The NewGRF "encoded" offset.
405 * @param tile The tile to base the offset from.
406 * @param signed_offsets Whether the offsets are to be interpreted as signed or not.
407 * @param axis Axis of a railways station.
408 * @return The tile at the offset.
410 TileIndex GetNearbyTile(uint8_t parameter, TileIndex tile, bool signed_offsets, Axis axis)
412 int8_t x = GB(parameter, 0, 4);
413 int8_t y = GB(parameter, 4, 4);
415 if (signed_offsets && x >= 8) x -= 16;
416 if (signed_offsets && y >= 8) y -= 16;
418 /* Swap width and height depending on axis for railway stations */
419 if (axis == INVALID_AXIS && HasStationTileRail(tile)) axis = GetRailStationAxis(tile);
420 if (axis == AXIS_Y) Swap(x, y);
422 /* Make sure we never roam outside of the map, better wrap in that case */
423 return Map::WrapToMap(tile + TileDiffXY(x, y));
427 * Common part of station var 0x67, house var 0x62, indtile var 0x60, industry var 0x62.
429 * @param tile the tile of interest.
430 * @param grf_version8 True, if we are dealing with a new NewGRF which uses GRF version >= 8.
431 * @return 0czzbbss: c = TileType; zz = TileZ; bb: 7-3 zero, 4-2 TerrainType, 1 water/shore, 0 zero; ss = TileSlope
433 uint32_t GetNearbyTileInformation(TileIndex tile, bool grf_version8)
435 TileType tile_type = GetTileType(tile);
437 /* Fake tile type for trees on shore */
438 if (IsTileType(tile, MP_TREES) && GetTreeGround(tile) == TREE_GROUND_SHORE) tile_type = MP_WATER;
440 /* Fake tile type for road waypoints */
441 if (IsRoadWaypointTile(tile)) tile_type = MP_ROAD;
443 auto [tileh, z] = GetTilePixelSlope(tile);
444 /* Return 0 if the tile is a land tile */
445 uint8_t terrain_type = (HasTileWaterClass(tile) ? (GetWaterClass(tile) + 1) & 3 : 0) << 5 | GetTerrainType(tile) << 2 | (tile_type == MP_WATER ? 1 : 0) << 1;
446 if (grf_version8) z /= TILE_HEIGHT;
447 return tile_type << 24 | ClampTo<uint8_t>(z) << 16 | terrain_type << 8 | tileh;
451 * Returns company information like in vehicle var 43 or station var 43.
452 * @param owner Owner of the object.
453 * @param l Livery of the object; nullptr to use default.
454 * @return NewGRF company information.
456 uint32_t GetCompanyInfo(CompanyID owner, const Livery *l)
458 if (l == nullptr && Company::IsValidID(owner)) l = &Company::Get(owner)->livery[LS_DEFAULT];
459 return owner | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != nullptr ? (l->colour1 << 24) | (l->colour2 << 28) : 0);
463 * Get the error message from a shape/location/slope check callback result.
464 * @param cb_res Callback result to translate. If bit 10 is set this is a standard error message, otherwise a NewGRF provided string.
465 * @param grffile NewGRF to use to resolve a custom error message.
466 * @param default_error Error message to use for the generic error.
467 * @return CommandCost indicating success or the error message.
469 CommandCost GetErrorMessageFromLocationCallbackResult(uint16_t cb_res, const GRFFile *grffile, StringID default_error)
471 CommandCost res;
473 if (cb_res < 0x400) {
474 res = CommandCost(GetGRFStringID(grffile->grfid, 0xD000 + cb_res));
475 } else {
476 switch (cb_res) {
477 case 0x400: return res; // No error.
479 default: // unknown reason -> default error
480 case 0x401: res = CommandCost(default_error); break;
482 case 0x402: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST); break;
483 case 0x403: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT); break;
484 case 0x404: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_ABOVE_SNOW_LINE); break;
485 case 0x405: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_BELOW_SNOW_LINE); break;
486 case 0x406: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_SEA); break;
487 case 0x407: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_CANAL); break;
488 case 0x408: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_RIVER); break;
492 /* Copy some parameters from the registers to the error message text ref. stack */
493 res.UseTextRefStack(grffile, 4);
495 return res;
499 * Record that a NewGRF returned an unknown/invalid callback result.
500 * Also show an error to the user.
501 * @param grfid ID of the NewGRF causing the problem.
502 * @param cbid Callback causing the problem.
503 * @param cb_res Invalid result returned by the callback.
505 void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
507 GRFConfig *grfconfig = GetGRFConfig(grfid);
509 if (!HasBit(grfconfig->grf_bugs, GBUG_UNKNOWN_CB_RESULT)) {
510 SetBit(grfconfig->grf_bugs, GBUG_UNKNOWN_CB_RESULT);
511 SetDParamStr(0, grfconfig->GetName());
512 SetDParam(1, cbid);
513 SetDParam(2, cb_res);
514 ShowErrorMessage(STR_NEWGRF_BUGGY, STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT, WL_CRITICAL);
517 /* debug output */
518 SetDParamStr(0, grfconfig->GetName());
519 Debug(grf, 0, "{}", StrMakeValid(GetString(STR_NEWGRF_BUGGY)));
521 SetDParam(1, cbid);
522 SetDParam(2, cb_res);
523 Debug(grf, 0, "{}", StrMakeValid(GetString(STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT)));
527 * Converts a callback result into a boolean.
528 * For grf version < 8 the result is checked for zero or non-zero.
529 * For grf version >= 8 the callback result must be 0 or 1.
530 * @param grffile NewGRF returning the value.
531 * @param cbid Callback returning the value.
532 * @param cb_res Callback result.
533 * @return Boolean value. True if cb_res != 0.
535 bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
537 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
539 if (grffile->grf_version < 8) return cb_res != 0;
541 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
542 return cb_res != 0;
546 * Converts a callback result into a boolean.
547 * For grf version < 8 the first 8 bit of the result are checked for zero or non-zero.
548 * For grf version >= 8 the callback result must be 0 or 1.
549 * @param grffile NewGRF returning the value.
550 * @param cbid Callback returning the value.
551 * @param cb_res Callback result.
552 * @return Boolean value. True if cb_res != 0.
554 bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
556 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
558 if (grffile->grf_version < 8) return GB(cb_res, 0, 8) != 0;
560 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
561 return cb_res != 0;
565 /* static */ std::vector<DrawTileSeqStruct> NewGRFSpriteLayout::result_seq;
568 * Clone the building sprites of a spritelayout.
569 * @param source The building sprites to copy.
571 void NewGRFSpriteLayout::Clone(const DrawTileSeqStruct *source)
573 assert(this->seq == nullptr);
574 assert(source != nullptr);
576 size_t count = 1; // 1 for the terminator
577 const DrawTileSeqStruct *element;
578 foreach_draw_tile_seq(element, source) count++;
580 DrawTileSeqStruct *sprites = MallocT<DrawTileSeqStruct>(count);
581 MemCpyT(sprites, source, count);
582 this->seq = sprites;
586 * Clone a spritelayout.
587 * @param source The spritelayout to copy.
589 void NewGRFSpriteLayout::Clone(const NewGRFSpriteLayout *source)
591 this->Clone((const DrawTileSprites*)source);
593 if (source->registers != nullptr) {
594 size_t count = 1; // 1 for the ground sprite
595 const DrawTileSeqStruct *element;
596 foreach_draw_tile_seq(element, source->seq) count++;
598 TileLayoutRegisters *regs = MallocT<TileLayoutRegisters>(count);
599 MemCpyT(regs, source->registers, count);
600 this->registers = regs;
606 * Allocate a spritelayout for \a num_sprites building sprites.
607 * @param num_sprites Number of building sprites to allocate memory for. (not counting the terminator)
609 void NewGRFSpriteLayout::Allocate(uint num_sprites)
611 assert(this->seq == nullptr);
613 DrawTileSeqStruct *sprites = CallocT<DrawTileSeqStruct>(num_sprites + 1);
614 sprites[num_sprites].MakeTerminator();
615 this->seq = sprites;
619 * Allocate memory for register modifiers.
621 void NewGRFSpriteLayout::AllocateRegisters()
623 assert(this->seq != nullptr);
624 assert(this->registers == nullptr);
626 size_t count = 1; // 1 for the ground sprite
627 const DrawTileSeqStruct *element;
628 foreach_draw_tile_seq(element, this->seq) count++;
630 this->registers = CallocT<TileLayoutRegisters>(count);
634 * Prepares a sprite layout before resolving action-1-2-3 chains.
635 * Integrates offsets into the layout and determines which chains to resolve.
636 * @note The function uses statically allocated temporary storage, which is reused every time when calling the function.
637 * That means, you have to use the sprite layout before calling #PrepareLayout() the next time.
638 * @param orig_offset Offset to apply to non-action-1 sprites.
639 * @param newgrf_ground_offset Offset to apply to action-1 ground sprites.
640 * @param newgrf_offset Offset to apply to action-1 non-ground sprites.
641 * @param constr_stage Construction stage (0-3) to apply to all action-1 sprites.
642 * @param separate_ground Whether the ground sprite shall be resolved by a separate action-1-2-3 chain by default.
643 * @return Bitmask of values for variable 10 to resolve action-1-2-3 chains for.
645 uint32_t NewGRFSpriteLayout::PrepareLayout(uint32_t orig_offset, uint32_t newgrf_ground_offset, uint32_t newgrf_offset, uint constr_stage, bool separate_ground) const
647 result_seq.clear();
648 uint32_t var10_values = 0;
650 /* Create a copy of the spritelayout, so we can modify some values.
651 * Also include the groundsprite into the sequence for easier processing. */
652 DrawTileSeqStruct *result = &result_seq.emplace_back();
653 result->image = ground;
654 result->delta_x = 0;
655 result->delta_y = 0;
656 result->delta_z = (int8_t)0x80;
658 const DrawTileSeqStruct *dtss;
659 foreach_draw_tile_seq(dtss, this->seq) {
660 result_seq.push_back(*dtss);
662 result_seq.emplace_back().MakeTerminator();
663 /* Determine the var10 values the action-1-2-3 chains needs to be resolved for,
664 * and apply the default sprite offsets (unless disabled). */
665 const TileLayoutRegisters *regs = this->registers;
666 bool ground = true;
667 foreach_draw_tile_seq(result, result_seq.data()) {
668 TileLayoutFlags flags = TLF_NOTHING;
669 if (regs != nullptr) flags = regs->flags;
671 /* Record var10 value for the sprite */
672 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
673 uint8_t var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
674 SetBit(var10_values, var10);
677 /* Add default sprite offset, unless there is a custom one */
678 if (!(flags & TLF_SPRITE)) {
679 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
680 result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
681 if (constr_stage > 0 && regs != nullptr) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_sprite_offset);
682 } else {
683 result->image.sprite += orig_offset;
687 /* Record var10 value for the palette */
688 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS)) {
689 uint8_t var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
690 SetBit(var10_values, var10);
693 /* Add default palette offset, unless there is a custom one */
694 if (!(flags & TLF_PALETTE)) {
695 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
696 result->image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
697 if (constr_stage > 0 && regs != nullptr) result->image.sprite += GetConstructionStageOffset(constr_stage, regs->max_palette_offset);
701 ground = false;
702 if (regs != nullptr) regs++;
705 return var10_values;
709 * Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
710 * @pre #PrepareLayout() needs calling first.
711 * @param resolved_var10 The value of var10 the action-1-2-3 chain was evaluated for.
712 * @param resolved_sprite Result sprite of the action-1-2-3 chain.
713 * @param separate_ground Whether the ground sprite is resolved by a separate action-1-2-3 chain.
714 * @return Resulting spritelayout after processing the registers.
716 void NewGRFSpriteLayout::ProcessRegisters(uint8_t resolved_var10, uint32_t resolved_sprite, bool separate_ground) const
718 DrawTileSeqStruct *result;
719 const TileLayoutRegisters *regs = this->registers;
720 bool ground = true;
721 foreach_draw_tile_seq(result, result_seq.data()) {
722 TileLayoutFlags flags = TLF_NOTHING;
723 if (regs != nullptr) flags = regs->flags;
725 /* Is the sprite or bounding box affected by an action-1-2-3 chain? */
726 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
727 /* Does the var10 value apply to this sprite? */
728 uint8_t var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
729 if (var10 == resolved_var10) {
730 /* Apply registers */
731 if ((flags & TLF_DODRAW) && GetRegister(regs->dodraw) == 0) {
732 result->image.sprite = 0;
733 } else {
734 if (HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) result->image.sprite += resolved_sprite;
735 if (flags & TLF_SPRITE) {
736 int16_t offset = (int16_t)GetRegister(regs->sprite); // mask to 16 bits to avoid trouble
737 if (!HasBit(result->image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_sprite_offset)) {
738 result->image.sprite += offset;
739 } else {
740 result->image.sprite = SPR_IMG_QUERY;
744 if (result->IsParentSprite()) {
745 if (flags & TLF_BB_XY_OFFSET) {
746 result->delta_x += (int32_t)GetRegister(regs->delta.parent[0]);
747 result->delta_y += (int32_t)GetRegister(regs->delta.parent[1]);
749 if (flags & TLF_BB_Z_OFFSET) result->delta_z += (int32_t)GetRegister(regs->delta.parent[2]);
750 } else {
751 if (flags & TLF_CHILD_X_OFFSET) result->delta_x += (int32_t)GetRegister(regs->delta.child[0]);
752 if (flags & TLF_CHILD_Y_OFFSET) result->delta_y += (int32_t)GetRegister(regs->delta.child[1]);
758 /* Is the palette affected by an action-1-2-3 chain? */
759 if (result->image.sprite != 0 && (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS))) {
760 /* Does the var10 value apply to this sprite? */
761 uint8_t var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
762 if (var10 == resolved_var10) {
763 /* Apply registers */
764 if (HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) result->image.pal += resolved_sprite;
765 if (flags & TLF_PALETTE) {
766 int16_t offset = (int16_t)GetRegister(regs->palette); // mask to 16 bits to avoid trouble
767 if (!HasBit(result->image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_palette_offset)) {
768 result->image.pal += offset;
769 } else {
770 result->image.sprite = SPR_IMG_QUERY;
771 result->image.pal = PAL_NONE;
777 ground = false;
778 if (regs != nullptr) regs++;