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/>.
9 * @file newgrf_commons.cpp Implementation of the class %OverrideManagerBase
10 * and its descendance, present and future.
15 #include "landscape.h"
17 #include "industrytype.h"
18 #include "newgrf_config.h"
19 #include "clear_map.h"
20 #include "station_map.h"
22 #include "tunnelbridge_map.h"
23 #include "newgrf_object.h"
25 #include "newgrf_spritegroup.h"
26 #include "newgrf_text.h"
27 #include "company_base.h"
29 #include "strings_func.h"
30 #include "string_func.h"
32 #include "table/strings.h"
34 #include "safeguards.h"
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
);
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());
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
) {
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
;
126 map
->substitute_id
= substitute_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.
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
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.");
168 *HouseSpec::Get(house_id
) = *hs
;
170 /* Now add the overrides. */
171 for (int i
= 0; i
< this->max_offset
; i
++) {
172 HouseSpec
*overridden_hs
= HouseSpec::Get(i
);
174 if (this->entity_overrides
[i
] != hs
->grf_prop
.local_id
|| this->grfid_overrides
[i
] != hs
->grf_prop
.grffile
->grfid
) continue;
176 overridden_hs
->grf_prop
.override
= house_id
;
177 this->entity_overrides
[i
] = this->invalid_id
;
178 this->grfid_overrides
[i
] = 0;
183 * Return the ID (if ever available) of a previously inserted entity.
184 * @param grf_local_id ID of this entity within the grfID
185 * @param grfid ID of the grf file
186 * @return the ID of the candidate, of the Invalid flag item ID
188 uint16_t IndustryOverrideManager::GetID(uint16_t grf_local_id
, uint32_t grfid
) const
190 uint16_t id
= OverrideManagerBase::GetID(grf_local_id
, grfid
);
191 if (id
!= this->invalid_id
) return id
;
193 /* No mapping found, try the overrides */
194 for (id
= 0; id
< this->max_offset
; id
++) {
195 if (this->entity_overrides
[id
] == grf_local_id
&& this->grfid_overrides
[id
] == grfid
) return id
;
198 return this->invalid_id
;
202 * Method to find an entity ID and to mark it as reserved for the Industry to be included.
203 * @param grf_local_id ID used by the grf file for pre-installation work (equivalent of TTDPatch's setid
204 * @param grfid ID of the current grf file
205 * @param substitute_id industry from which data has been copied
206 * @return a free entity id (slotid) if ever one has been found, or Invalid_ID marker otherwise
208 uint16_t IndustryOverrideManager::AddEntityID(uint16_t grf_local_id
, uint32_t grfid
, uint16_t substitute_id
)
210 /* This entity hasn't been defined before, so give it an ID now. */
211 for (uint16_t id
= 0; id
< this->max_entities
; id
++) {
212 /* Skip overridden industries */
213 if (id
< this->max_offset
&& this->entity_overrides
[id
] != this->invalid_id
) continue;
215 /* Get the real live industry */
216 const IndustrySpec
*inds
= GetIndustrySpec(id
);
218 /* This industry must be one that is not available(enabled), mostly because of climate.
219 * And it must not already be used by a grf (grffile == nullptr).
220 * So reserve this slot here, as it is the chosen one */
221 if (!inds
->enabled
&& inds
->grf_prop
.grffile
== nullptr) {
222 EntityIDMapping
*map
= &this->mappings
[id
];
224 if (map
->entity_id
== 0 && map
->grfid
== 0) {
225 /* winning slot, mark it as been used */
226 map
->entity_id
= grf_local_id
;
228 map
->substitute_id
= substitute_id
;
234 return this->invalid_id
;
238 * Method to install the new industry data in its proper slot
239 * The slot assignment is internal of this method, since it requires
240 * checking what is available
241 * @param inds Industryspec that comes from the grf decoding process
243 void IndustryOverrideManager::SetEntitySpec(IndustrySpec
*inds
)
245 /* First step : We need to find if this industry is already specified in the savegame data. */
246 IndustryType ind_id
= this->GetID(inds
->grf_prop
.local_id
, inds
->grf_prop
.grffile
->grfid
);
248 if (ind_id
== this->invalid_id
) {
250 * Or it has already been overridden, so you've lost your place.
251 * Or it is a simple substitute.
252 * We need to find a free available slot */
253 ind_id
= this->AddEntityID(inds
->grf_prop
.local_id
, inds
->grf_prop
.grffile
->grfid
, inds
->grf_prop
.subst_id
);
254 inds
->grf_prop
.override
= this->invalid_id
; // make sure it will not be detected as overridden
257 if (ind_id
== this->invalid_id
) {
258 GrfMsg(1, "Industry.SetEntitySpec: Too many industries allocated. Ignoring.");
262 /* Now that we know we can use the given id, copy the spec to its final destination... */
263 _industry_specs
[ind_id
] = *inds
;
264 /* ... and mark it as usable*/
265 _industry_specs
[ind_id
].enabled
= true;
268 void IndustryTileOverrideManager::SetEntitySpec(const IndustryTileSpec
*its
)
270 IndustryGfx indt_id
= this->AddEntityID(its
->grf_prop
.local_id
, its
->grf_prop
.grffile
->grfid
, its
->grf_prop
.subst_id
);
272 if (indt_id
== this->invalid_id
) {
273 GrfMsg(1, "IndustryTile.SetEntitySpec: Too many industry tiles allocated. Ignoring.");
277 _industry_tile_specs
[indt_id
] = *its
;
279 /* Now add the overrides. */
280 for (int i
= 0; i
< this->max_offset
; i
++) {
281 IndustryTileSpec
*overridden_its
= &_industry_tile_specs
[i
];
283 if (this->entity_overrides
[i
] != its
->grf_prop
.local_id
|| this->grfid_overrides
[i
] != its
->grf_prop
.grffile
->grfid
) continue;
285 overridden_its
->grf_prop
.override
= indt_id
;
286 overridden_its
->enabled
= false;
287 this->entity_overrides
[i
] = this->invalid_id
;
288 this->grfid_overrides
[i
] = 0;
293 * Method to install the new object data in its proper slot
294 * The slot assignment is internal of this method, since it requires
295 * checking what is available
296 * @param spec ObjectSpec that comes from the grf decoding process
298 void ObjectOverrideManager::SetEntitySpec(ObjectSpec
*spec
)
300 /* First step : We need to find if this object is already specified in the savegame data. */
301 ObjectType type
= this->GetID(spec
->grf_prop
.local_id
, spec
->grf_prop
.grffile
->grfid
);
303 if (type
== this->invalid_id
) {
305 * Or it has already been overridden, so you've lost your place.
306 * Or it is a simple substitute.
307 * We need to find a free available slot */
308 type
= this->AddEntityID(spec
->grf_prop
.local_id
, spec
->grf_prop
.grffile
->grfid
, OBJECT_TRANSMITTER
);
311 if (type
== this->invalid_id
) {
312 GrfMsg(1, "Object.SetEntitySpec: Too many objects allocated. Ignoring.");
316 extern std::vector
<ObjectSpec
> _object_specs
;
318 /* Now that we know we can use the given id, copy the spec to its final destination. */
319 if (type
>= _object_specs
.size()) _object_specs
.resize(type
+ 1);
320 _object_specs
[type
] = *spec
;
324 * Function used by houses (and soon industries) to get information
325 * on type of "terrain" the tile it is queries sits on.
326 * @param tile TileIndex of the tile been queried
327 * @param context The context of the tile.
328 * @return value corresponding to the grf expected format:
329 * Terrain type: 0 normal, 1 desert, 2 rainforest, 4 on or above snowline
331 uint32_t GetTerrainType(TileIndex tile
, TileContext context
)
333 switch (_settings_game
.game_creation
.landscape
) {
334 case LT_TROPIC
: return GetTropicZone(tile
);
337 switch (GetTileType(tile
)) {
339 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
340 if (_generating_world
) goto genworld
;
341 has_snow
= IsSnowTile(tile
) && GetClearDensity(tile
) >= 2;
345 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
346 if (_generating_world
) goto genworld
; // we do not care about foundations here
347 RailGroundType ground
= GetRailGroundType(tile
);
348 has_snow
= (ground
== RAIL_GROUND_ICE_DESERT
|| (context
== TCX_UPPER_HALFTILE
&& ground
== RAIL_GROUND_HALF_SNOW
));
353 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
354 if (_generating_world
) goto genworld
; // we do not care about foundations here
355 has_snow
= IsOnSnow(tile
);
359 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
360 if (_generating_world
) goto genworld
;
361 TreeGround ground
= GetTreeGround(tile
);
362 has_snow
= (ground
== TREE_GROUND_SNOW_DESERT
|| ground
== TREE_GROUND_ROUGH_SNOW
) && GetTreeDensity(tile
) >= 2;
366 case MP_TUNNELBRIDGE
:
367 if (context
== TCX_ON_BRIDGE
) {
368 has_snow
= (GetBridgeHeight(tile
) > GetSnowLine());
370 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
371 if (_generating_world
) goto genworld
; // we do not care about foundations here
372 has_snow
= HasTunnelBridgeSnowOrDesert(tile
);
380 /* These tiles usually have a levelling foundation. So use max Z */
381 has_snow
= (GetTileMaxZ(tile
) > GetSnowLine());
387 has_snow
= (GetTileZ(tile
) > GetSnowLine());
390 default: NOT_REACHED();
392 return has_snow
? 4 : 0;
399 * Get the tile at the given offset.
400 * @param parameter The NewGRF "encoded" offset.
401 * @param tile The tile to base the offset from.
402 * @param signed_offsets Whether the offsets are to be interpreted as signed or not.
403 * @param axis Axis of a railways station.
404 * @return The tile at the offset.
406 TileIndex
GetNearbyTile(byte parameter
, TileIndex tile
, bool signed_offsets
, Axis axis
)
408 int8_t x
= GB(parameter
, 0, 4);
409 int8_t y
= GB(parameter
, 4, 4);
411 if (signed_offsets
&& x
>= 8) x
-= 16;
412 if (signed_offsets
&& y
>= 8) y
-= 16;
414 /* Swap width and height depending on axis for railway stations */
415 if (axis
== INVALID_AXIS
&& HasStationTileRail(tile
)) axis
= GetRailStationAxis(tile
);
416 if (axis
== AXIS_Y
) Swap(x
, y
);
418 /* Make sure we never roam outside of the map, better wrap in that case */
419 return Map::WrapToMap(tile
+ TileDiffXY(x
, y
));
423 * Common part of station var 0x67, house var 0x62, indtile var 0x60, industry var 0x62.
425 * @param tile the tile of interest.
426 * @param grf_version8 True, if we are dealing with a new NewGRF which uses GRF version >= 8.
427 * @return 0czzbbss: c = TileType; zz = TileZ; bb: 7-3 zero, 4-2 TerrainType, 1 water/shore, 0 zero; ss = TileSlope
429 uint32_t GetNearbyTileInformation(TileIndex tile
, bool grf_version8
)
431 TileType tile_type
= GetTileType(tile
);
433 /* Fake tile type for trees on shore */
434 if (IsTileType(tile
, MP_TREES
) && GetTreeGround(tile
) == TREE_GROUND_SHORE
) tile_type
= MP_WATER
;
437 Slope tileh
= GetTilePixelSlope(tile
, &z
);
438 /* Return 0 if the tile is a land tile */
439 byte terrain_type
= (HasTileWaterClass(tile
) ? (GetWaterClass(tile
) + 1) & 3 : 0) << 5 | GetTerrainType(tile
) << 2 | (tile_type
== MP_WATER
? 1 : 0) << 1;
440 if (grf_version8
) z
/= TILE_HEIGHT
;
441 return tile_type
<< 24 | ClampTo
<uint8_t>(z
) << 16 | terrain_type
<< 8 | tileh
;
445 * Returns company information like in vehicle var 43 or station var 43.
446 * @param owner Owner of the object.
447 * @param l Livery of the object; nullptr to use default.
448 * @return NewGRF company information.
450 uint32_t GetCompanyInfo(CompanyID owner
, const Livery
*l
)
452 if (l
== nullptr && Company::IsValidID(owner
)) l
= &Company::Get(owner
)->livery
[LS_DEFAULT
];
453 return owner
| (Company::IsValidAiID(owner
) ? 0x10000 : 0) | (l
!= nullptr ? (l
->colour1
<< 24) | (l
->colour2
<< 28) : 0);
457 * Get the error message from a shape/location/slope check callback result.
458 * @param cb_res Callback result to translate. If bit 10 is set this is a standard error message, otherwise a NewGRF provided string.
459 * @param grffile NewGRF to use to resolve a custom error message.
460 * @param default_error Error message to use for the generic error.
461 * @return CommandCost indicating success or the error message.
463 CommandCost
GetErrorMessageFromLocationCallbackResult(uint16_t cb_res
, const GRFFile
*grffile
, StringID default_error
)
467 if (cb_res
< 0x400) {
468 res
= CommandCost(GetGRFStringID(grffile
->grfid
, 0xD000 + cb_res
));
471 case 0x400: return res
; // No error.
473 default: // unknown reason -> default error
474 case 0x401: res
= CommandCost(default_error
); break;
476 case 0x402: res
= CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST
); break;
477 case 0x403: res
= CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT
); break;
478 case 0x404: res
= CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_ABOVE_SNOW_LINE
); break;
479 case 0x405: res
= CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_BELOW_SNOW_LINE
); break;
480 case 0x406: res
= CommandCost(STR_ERROR_CAN_T_BUILD_ON_SEA
); break;
481 case 0x407: res
= CommandCost(STR_ERROR_CAN_T_BUILD_ON_CANAL
); break;
482 case 0x408: res
= CommandCost(STR_ERROR_CAN_T_BUILD_ON_RIVER
); break;
486 /* Copy some parameters from the registers to the error message text ref. stack */
487 res
.UseTextRefStack(grffile
, 4);
493 * Record that a NewGRF returned an unknown/invalid callback result.
494 * Also show an error to the user.
495 * @param grfid ID of the NewGRF causing the problem.
496 * @param cbid Callback causing the problem.
497 * @param cb_res Invalid result returned by the callback.
499 void ErrorUnknownCallbackResult(uint32_t grfid
, uint16_t cbid
, uint16_t cb_res
)
501 GRFConfig
*grfconfig
= GetGRFConfig(grfid
);
503 if (!HasBit(grfconfig
->grf_bugs
, GBUG_UNKNOWN_CB_RESULT
)) {
504 SetBit(grfconfig
->grf_bugs
, GBUG_UNKNOWN_CB_RESULT
);
505 SetDParamStr(0, grfconfig
->GetName());
507 SetDParam(2, cb_res
);
508 ShowErrorMessage(STR_NEWGRF_BUGGY
, STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT
, WL_CRITICAL
);
512 SetDParamStr(0, grfconfig
->GetName());
513 Debug(grf
, 0, "{}", StrMakeValid(GetString(STR_NEWGRF_BUGGY
)));
516 SetDParam(2, cb_res
);
517 Debug(grf
, 0, "{}", StrMakeValid(GetString(STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT
)));
521 * Converts a callback result into a boolean.
522 * For grf version < 8 the result is checked for zero or non-zero.
523 * For grf version >= 8 the callback result must be 0 or 1.
524 * @param grffile NewGRF returning the value.
525 * @param cbid Callback returning the value.
526 * @param cb_res Callback result.
527 * @return Boolean value. True if cb_res != 0.
529 bool ConvertBooleanCallback(const GRFFile
*grffile
, uint16_t cbid
, uint16_t cb_res
)
531 assert(cb_res
!= CALLBACK_FAILED
); // We do not know what to return
533 if (grffile
->grf_version
< 8) return cb_res
!= 0;
535 if (cb_res
> 1) ErrorUnknownCallbackResult(grffile
->grfid
, cbid
, cb_res
);
540 * Converts a callback result into a boolean.
541 * For grf version < 8 the first 8 bit of the result are checked for zero or non-zero.
542 * For grf version >= 8 the callback result must be 0 or 1.
543 * @param grffile NewGRF returning the value.
544 * @param cbid Callback returning the value.
545 * @param cb_res Callback result.
546 * @return Boolean value. True if cb_res != 0.
548 bool Convert8bitBooleanCallback(const GRFFile
*grffile
, uint16_t cbid
, uint16_t cb_res
)
550 assert(cb_res
!= CALLBACK_FAILED
); // We do not know what to return
552 if (grffile
->grf_version
< 8) return GB(cb_res
, 0, 8) != 0;
554 if (cb_res
> 1) ErrorUnknownCallbackResult(grffile
->grfid
, cbid
, cb_res
);
559 /* static */ std::vector
<DrawTileSeqStruct
> NewGRFSpriteLayout::result_seq
;
562 * Clone the building sprites of a spritelayout.
563 * @param source The building sprites to copy.
565 void NewGRFSpriteLayout::Clone(const DrawTileSeqStruct
*source
)
567 assert(this->seq
== nullptr);
568 assert(source
!= nullptr);
570 size_t count
= 1; // 1 for the terminator
571 const DrawTileSeqStruct
*element
;
572 foreach_draw_tile_seq(element
, source
) count
++;
574 DrawTileSeqStruct
*sprites
= MallocT
<DrawTileSeqStruct
>(count
);
575 MemCpyT(sprites
, source
, count
);
580 * Clone a spritelayout.
581 * @param source The spritelayout to copy.
583 void NewGRFSpriteLayout::Clone(const NewGRFSpriteLayout
*source
)
585 this->Clone((const DrawTileSprites
*)source
);
587 if (source
->registers
!= nullptr) {
588 size_t count
= 1; // 1 for the ground sprite
589 const DrawTileSeqStruct
*element
;
590 foreach_draw_tile_seq(element
, source
->seq
) count
++;
592 TileLayoutRegisters
*regs
= MallocT
<TileLayoutRegisters
>(count
);
593 MemCpyT(regs
, source
->registers
, count
);
594 this->registers
= regs
;
600 * Allocate a spritelayout for \a num_sprites building sprites.
601 * @param num_sprites Number of building sprites to allocate memory for. (not counting the terminator)
603 void NewGRFSpriteLayout::Allocate(uint num_sprites
)
605 assert(this->seq
== nullptr);
607 DrawTileSeqStruct
*sprites
= CallocT
<DrawTileSeqStruct
>(num_sprites
+ 1);
608 sprites
[num_sprites
].MakeTerminator();
613 * Allocate memory for register modifiers.
615 void NewGRFSpriteLayout::AllocateRegisters()
617 assert(this->seq
!= nullptr);
618 assert(this->registers
== nullptr);
620 size_t count
= 1; // 1 for the ground sprite
621 const DrawTileSeqStruct
*element
;
622 foreach_draw_tile_seq(element
, this->seq
) count
++;
624 this->registers
= CallocT
<TileLayoutRegisters
>(count
);
628 * Prepares a sprite layout before resolving action-1-2-3 chains.
629 * Integrates offsets into the layout and determines which chains to resolve.
630 * @note The function uses statically allocated temporary storage, which is reused every time when calling the function.
631 * That means, you have to use the sprite layout before calling #PrepareLayout() the next time.
632 * @param orig_offset Offset to apply to non-action-1 sprites.
633 * @param newgrf_ground_offset Offset to apply to action-1 ground sprites.
634 * @param newgrf_offset Offset to apply to action-1 non-ground sprites.
635 * @param constr_stage Construction stage (0-3) to apply to all action-1 sprites.
636 * @param separate_ground Whether the ground sprite shall be resolved by a separate action-1-2-3 chain by default.
637 * @return Bitmask of values for variable 10 to resolve action-1-2-3 chains for.
639 uint32_t NewGRFSpriteLayout::PrepareLayout(uint32_t orig_offset
, uint32_t newgrf_ground_offset
, uint32_t newgrf_offset
, uint constr_stage
, bool separate_ground
) const
642 uint32_t var10_values
= 0;
644 /* Create a copy of the spritelayout, so we can modify some values.
645 * Also include the groundsprite into the sequence for easier processing. */
646 DrawTileSeqStruct
*result
= &result_seq
.emplace_back();
647 result
->image
= ground
;
650 result
->delta_z
= (int8_t)0x80;
652 const DrawTileSeqStruct
*dtss
;
653 foreach_draw_tile_seq(dtss
, this->seq
) {
654 result_seq
.push_back(*dtss
);
656 result_seq
.emplace_back().MakeTerminator();
657 /* Determine the var10 values the action-1-2-3 chains needs to be resolved for,
658 * and apply the default sprite offsets (unless disabled). */
659 const TileLayoutRegisters
*regs
= this->registers
;
661 foreach_draw_tile_seq(result
, result_seq
.data()) {
662 TileLayoutFlags flags
= TLF_NOTHING
;
663 if (regs
!= nullptr) flags
= regs
->flags
;
665 /* Record var10 value for the sprite */
666 if (HasBit(result
->image
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
) || (flags
& TLF_SPRITE_REG_FLAGS
)) {
667 uint8_t var10
= (flags
& TLF_SPRITE_VAR10
) ? regs
->sprite_var10
: (ground
&& separate_ground
? 1 : 0);
668 SetBit(var10_values
, var10
);
671 /* Add default sprite offset, unless there is a custom one */
672 if (!(flags
& TLF_SPRITE
)) {
673 if (HasBit(result
->image
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) {
674 result
->image
.sprite
+= ground
? newgrf_ground_offset
: newgrf_offset
;
675 if (constr_stage
> 0 && regs
!= nullptr) result
->image
.sprite
+= GetConstructionStageOffset(constr_stage
, regs
->max_sprite_offset
);
677 result
->image
.sprite
+= orig_offset
;
681 /* Record var10 value for the palette */
682 if (HasBit(result
->image
.pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
) || (flags
& TLF_PALETTE_REG_FLAGS
)) {
683 uint8_t var10
= (flags
& TLF_PALETTE_VAR10
) ? regs
->palette_var10
: (ground
&& separate_ground
? 1 : 0);
684 SetBit(var10_values
, var10
);
687 /* Add default palette offset, unless there is a custom one */
688 if (!(flags
& TLF_PALETTE
)) {
689 if (HasBit(result
->image
.pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) {
690 result
->image
.sprite
+= ground
? newgrf_ground_offset
: newgrf_offset
;
691 if (constr_stage
> 0 && regs
!= nullptr) result
->image
.sprite
+= GetConstructionStageOffset(constr_stage
, regs
->max_palette_offset
);
696 if (regs
!= nullptr) regs
++;
703 * Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
704 * @pre #PrepareLayout() needs calling first.
705 * @param resolved_var10 The value of var10 the action-1-2-3 chain was evaluated for.
706 * @param resolved_sprite Result sprite of the action-1-2-3 chain.
707 * @param separate_ground Whether the ground sprite is resolved by a separate action-1-2-3 chain.
708 * @return Resulting spritelayout after processing the registers.
710 void NewGRFSpriteLayout::ProcessRegisters(uint8_t resolved_var10
, uint32_t resolved_sprite
, bool separate_ground
) const
712 DrawTileSeqStruct
*result
;
713 const TileLayoutRegisters
*regs
= this->registers
;
715 foreach_draw_tile_seq(result
, result_seq
.data()) {
716 TileLayoutFlags flags
= TLF_NOTHING
;
717 if (regs
!= nullptr) flags
= regs
->flags
;
719 /* Is the sprite or bounding box affected by an action-1-2-3 chain? */
720 if (HasBit(result
->image
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
) || (flags
& TLF_SPRITE_REG_FLAGS
)) {
721 /* Does the var10 value apply to this sprite? */
722 uint8_t var10
= (flags
& TLF_SPRITE_VAR10
) ? regs
->sprite_var10
: (ground
&& separate_ground
? 1 : 0);
723 if (var10
== resolved_var10
) {
724 /* Apply registers */
725 if ((flags
& TLF_DODRAW
) && GetRegister(regs
->dodraw
) == 0) {
726 result
->image
.sprite
= 0;
728 if (HasBit(result
->image
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) result
->image
.sprite
+= resolved_sprite
;
729 if (flags
& TLF_SPRITE
) {
730 int16_t offset
= (int16_t)GetRegister(regs
->sprite
); // mask to 16 bits to avoid trouble
731 if (!HasBit(result
->image
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
) || (offset
>= 0 && offset
< regs
->max_sprite_offset
)) {
732 result
->image
.sprite
+= offset
;
734 result
->image
.sprite
= SPR_IMG_QUERY
;
738 if (result
->IsParentSprite()) {
739 if (flags
& TLF_BB_XY_OFFSET
) {
740 result
->delta_x
+= (int32_t)GetRegister(regs
->delta
.parent
[0]);
741 result
->delta_y
+= (int32_t)GetRegister(regs
->delta
.parent
[1]);
743 if (flags
& TLF_BB_Z_OFFSET
) result
->delta_z
+= (int32_t)GetRegister(regs
->delta
.parent
[2]);
745 if (flags
& TLF_CHILD_X_OFFSET
) result
->delta_x
+= (int32_t)GetRegister(regs
->delta
.child
[0]);
746 if (flags
& TLF_CHILD_Y_OFFSET
) result
->delta_y
+= (int32_t)GetRegister(regs
->delta
.child
[1]);
752 /* Is the palette affected by an action-1-2-3 chain? */
753 if (result
->image
.sprite
!= 0 && (HasBit(result
->image
.pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
) || (flags
& TLF_PALETTE_REG_FLAGS
))) {
754 /* Does the var10 value apply to this sprite? */
755 uint8_t var10
= (flags
& TLF_PALETTE_VAR10
) ? regs
->palette_var10
: (ground
&& separate_ground
? 1 : 0);
756 if (var10
== resolved_var10
) {
757 /* Apply registers */
758 if (HasBit(result
->image
.pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) result
->image
.pal
+= resolved_sprite
;
759 if (flags
& TLF_PALETTE
) {
760 int16_t offset
= (int16_t)GetRegister(regs
->palette
); // mask to 16 bits to avoid trouble
761 if (!HasBit(result
->image
.pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
) || (offset
>= 0 && offset
< regs
->max_palette_offset
)) {
762 result
->image
.pal
+= offset
;
764 result
->image
.sprite
= SPR_IMG_QUERY
;
765 result
->image
.pal
= PAL_NONE
;
772 if (regs
!= nullptr) regs
++;