OpenTTD Source 20250218-master-g53dd1258a7
newgrf_commons.cpp
Go to the documentation of this file.
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 */
7
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 "company_func.h"
20#include "clear_map.h"
21#include "station_map.h"
22#include "tree_map.h"
23#include "tunnelbridge_map.h"
24#include "newgrf_object.h"
25#include "genworld.h"
26#include "newgrf_spritegroup.h"
27#include "newgrf_text.h"
28#include "company_base.h"
29#include "error.h"
30#include "strings_func.h"
31#include "string_func.h"
32
33#include "table/strings.h"
34
35#include "safeguards.h"
36
43OverrideManagerBase::OverrideManagerBase(uint16_t offset, uint16_t maximum, uint16_t invalid)
44{
45 this->max_offset = offset;
46 this->max_entities = maximum;
47 this->invalid_id = invalid;
48
49 this->mappings.resize(this->max_entities);
50 this->entity_overrides.resize(this->max_offset);
51 std::fill(this->entity_overrides.begin(), this->entity_overrides.end(), this->invalid_id);
52 this->grfid_overrides.resize(this->max_offset);
53}
54
63void OverrideManagerBase::Add(uint16_t local_id, uint32_t grfid, uint entity_type)
64{
65 assert(entity_type < this->max_offset);
66 /* An override can be set only once */
67 if (this->entity_overrides[entity_type] != this->invalid_id) return;
68 this->entity_overrides[entity_type] = local_id;
69 this->grfid_overrides[entity_type] = grfid;
70}
71
74{
75 std::fill(this->mappings.begin(), this->mappings.end(), EntityIDMapping{});
76}
77
80{
81 std::fill(this->entity_overrides.begin(), this->entity_overrides.end(), this->invalid_id);
82 std::fill(this->grfid_overrides.begin(), this->grfid_overrides.end(), uint32_t());
83}
84
91uint16_t OverrideManagerBase::GetID(uint16_t grf_local_id, uint32_t grfid) const
92{
93 for (uint16_t id = 0; id < this->max_entities; id++) {
94 const EntityIDMapping *map = &this->mappings[id];
95 if (map->entity_id == grf_local_id && map->grfid == grfid) {
96 return id;
97 }
98 }
99
100 return this->invalid_id;
101}
102
110uint16_t OverrideManagerBase::AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
111{
112 uint16_t id = this->GetID(grf_local_id, grfid);
113
114 /* Look to see if this entity has already been added. This is done
115 * separately from the loop below in case a GRF has been deleted, and there
116 * are any gaps in the array.
117 */
118 if (id != this->invalid_id) return id;
119
120 /* This entity hasn't been defined before, so give it an ID now. */
121 for (id = this->max_offset; id < this->max_entities; id++) {
122 EntityIDMapping *map = &this->mappings[id];
123
124 if (CheckValidNewID(id) && map->entity_id == 0 && map->grfid == 0) {
125 map->entity_id = grf_local_id;
126 map->grfid = grfid;
127 map->substitute_id = substitute_id;
128 return id;
129 }
130 }
131
132 return this->invalid_id;
133}
134
140uint32_t OverrideManagerBase::GetGRFID(uint16_t entity_id) const
141{
142 return this->mappings[entity_id].grfid;
143}
144
150uint16_t OverrideManagerBase::GetSubstituteID(uint16_t entity_id) const
151{
152 return this->mappings[entity_id].substitute_id;
153}
154
161{
162 HouseID house_id = this->AddEntityID(hs->grf_prop.local_id, hs->grf_prop.grfid, hs->grf_prop.subst_id);
163
164 if (house_id == this->invalid_id) {
165 GrfMsg(1, "House.SetEntitySpec: Too many houses allocated. Ignoring.");
166 return;
167 }
168
169 auto &house_specs = HouseSpec::Specs();
170
171 /* Now that we know we can use the given id, copy the spec to its final destination. */
172 if (house_id >= house_specs.size()) house_specs.resize(house_id + 1);
173 house_specs[house_id] = *hs;
174
175 /* Now add the overrides. */
176 for (int i = 0; i < this->max_offset; i++) {
177 HouseSpec *overridden_hs = HouseSpec::Get(i);
178
179 if (this->entity_overrides[i] != hs->grf_prop.local_id || this->grfid_overrides[i] != hs->grf_prop.grfid) continue;
180
181 overridden_hs->grf_prop.override = house_id;
182 this->entity_overrides[i] = this->invalid_id;
183 this->grfid_overrides[i] = 0;
184 }
185}
186
193uint16_t IndustryOverrideManager::GetID(uint16_t grf_local_id, uint32_t grfid) const
194{
195 uint16_t id = OverrideManagerBase::GetID(grf_local_id, grfid);
196 if (id != this->invalid_id) return id;
197
198 /* No mapping found, try the overrides */
199 for (id = 0; id < this->max_offset; id++) {
200 if (this->entity_overrides[id] == grf_local_id && this->grfid_overrides[id] == grfid) return id;
201 }
202
203 return this->invalid_id;
204}
205
213uint16_t IndustryOverrideManager::AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
214{
215 /* This entity hasn't been defined before, so give it an ID now. */
216 for (uint16_t id = 0; id < this->max_entities; id++) {
217 /* Skip overridden industries */
218 if (id < this->max_offset && this->entity_overrides[id] != this->invalid_id) continue;
219
220 /* Get the real live industry */
221 const IndustrySpec *inds = GetIndustrySpec(id);
222
223 /* This industry must be one that is not available(enabled), mostly because of climate.
224 * And it must not already be used by a grf (grffile == nullptr).
225 * So reserve this slot here, as it is the chosen one */
226 if (!inds->enabled && !inds->grf_prop.HasGrfFile()) {
227 EntityIDMapping *map = &this->mappings[id];
228
229 if (map->entity_id == 0 && map->grfid == 0) {
230 /* winning slot, mark it as been used */
231 map->entity_id = grf_local_id;
232 map->grfid = grfid;
233 map->substitute_id = substitute_id;
234 return id;
235 }
236 }
237 }
238
239 return this->invalid_id;
240}
241
249{
250 /* First step : We need to find if this industry is already specified in the savegame data. */
251 IndustryType ind_id = this->GetID(inds->grf_prop.local_id, inds->grf_prop.grfid);
252
253 if (ind_id == this->invalid_id) {
254 /* Not found.
255 * Or it has already been overridden, so you've lost your place.
256 * Or it is a simple substitute.
257 * We need to find a free available slot */
258 ind_id = this->AddEntityID(inds->grf_prop.local_id, inds->grf_prop.grfid, inds->grf_prop.subst_id);
259 inds->grf_prop.override = this->invalid_id; // make sure it will not be detected as overridden
260 }
261
262 if (ind_id == this->invalid_id) {
263 GrfMsg(1, "Industry.SetEntitySpec: Too many industries allocated. Ignoring.");
264 return;
265 }
266
267 /* Now that we know we can use the given id, copy the spec to its final destination... */
268 _industry_specs[ind_id] = *inds;
269 /* ... and mark it as usable*/
270 _industry_specs[ind_id].enabled = true;
271}
272
273void IndustryTileOverrideManager::SetEntitySpec(const IndustryTileSpec *its)
274{
275 IndustryGfx indt_id = this->AddEntityID(its->grf_prop.local_id, its->grf_prop.grfid, its->grf_prop.subst_id);
276
277 if (indt_id == this->invalid_id) {
278 GrfMsg(1, "IndustryTile.SetEntitySpec: Too many industry tiles allocated. Ignoring.");
279 return;
280 }
281
282 _industry_tile_specs[indt_id] = *its;
283
284 /* Now add the overrides. */
285 for (int i = 0; i < this->max_offset; i++) {
286 IndustryTileSpec *overridden_its = &_industry_tile_specs[i];
287
288 if (this->entity_overrides[i] != its->grf_prop.local_id || this->grfid_overrides[i] != its->grf_prop.grfid) continue;
289
290 overridden_its->grf_prop.override = indt_id;
291 overridden_its->enabled = false;
292 this->entity_overrides[i] = this->invalid_id;
293 this->grfid_overrides[i] = 0;
294 }
295}
296
304{
305 /* First step : We need to find if this object is already specified in the savegame data. */
306 ObjectType type = this->GetID(spec->grf_prop.local_id, spec->grf_prop.grfid);
307
308 if (type == this->invalid_id) {
309 /* Not found.
310 * Or it has already been overridden, so you've lost your place.
311 * Or it is a simple substitute.
312 * We need to find a free available slot */
313 type = this->AddEntityID(spec->grf_prop.local_id, spec->grf_prop.grfid, OBJECT_TRANSMITTER);
314 }
315
316 if (type == this->invalid_id) {
317 GrfMsg(1, "Object.SetEntitySpec: Too many objects allocated. Ignoring.");
318 return;
319 }
320
321 extern std::vector<ObjectSpec> _object_specs;
322
323 /* Now that we know we can use the given id, copy the spec to its final destination. */
324 if (type >= _object_specs.size()) _object_specs.resize(type + 1);
325 _object_specs[type] = *spec;
326}
327
336uint32_t GetTerrainType(TileIndex tile, TileContext context)
337{
339 case LandscapeType::Tropic: return GetTropicZone(tile);
340 case LandscapeType::Arctic: {
341 bool has_snow;
342 switch (GetTileType(tile)) {
343 case MP_CLEAR:
344 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
345 if (_generating_world) goto genworld;
346 has_snow = IsSnowTile(tile) && GetClearDensity(tile) >= 2;
347 break;
348
349 case MP_RAILWAY: {
350 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
351 if (_generating_world) goto genworld; // we do not care about foundations here
352 RailGroundType ground = GetRailGroundType(tile);
353 has_snow = (ground == RAIL_GROUND_ICE_DESERT || (context == TCX_UPPER_HALFTILE && ground == RAIL_GROUND_HALF_SNOW));
354 break;
355 }
356
357 case MP_ROAD:
358 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
359 if (_generating_world) goto genworld; // we do not care about foundations here
360 has_snow = IsOnSnow(tile);
361 break;
362
363 case MP_TREES: {
364 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
365 if (_generating_world) goto genworld;
366 TreeGround ground = GetTreeGround(tile);
367 has_snow = (ground == TREE_GROUND_SNOW_DESERT || ground == TREE_GROUND_ROUGH_SNOW) && GetTreeDensity(tile) >= 2;
368 break;
369 }
370
371 case MP_TUNNELBRIDGE:
372 if (context == TCX_ON_BRIDGE) {
373 has_snow = (GetBridgeHeight(tile) > GetSnowLine());
374 } else {
375 /* During map generation the snowstate may not be valid yet, as the tileloop may not have run yet. */
376 if (_generating_world) goto genworld; // we do not care about foundations here
377 has_snow = HasTunnelBridgeSnowOrDesert(tile);
378 }
379 break;
380
381 case MP_STATION:
382 case MP_HOUSE:
383 case MP_INDUSTRY:
384 case MP_OBJECT:
385 /* These tiles usually have a levelling foundation. So use max Z */
386 has_snow = (GetTileMaxZ(tile) > GetSnowLine());
387 break;
388
389 case MP_VOID:
390 case MP_WATER:
391 genworld:
392 has_snow = (GetTileZ(tile) > GetSnowLine());
393 break;
394
395 default: NOT_REACHED();
396 }
397 return has_snow ? 4 : 0;
398 }
399 default: return 0;
400 }
401}
402
411TileIndex GetNearbyTile(uint8_t parameter, TileIndex tile, bool signed_offsets, Axis axis)
412{
413 int8_t x = GB(parameter, 0, 4);
414 int8_t y = GB(parameter, 4, 4);
415
416 if (signed_offsets && x >= 8) x -= 16;
417 if (signed_offsets && y >= 8) y -= 16;
418
419 /* Swap width and height depending on axis for railway stations */
420 if (axis == INVALID_AXIS && HasStationTileRail(tile)) axis = GetRailStationAxis(tile);
421 if (axis == AXIS_Y) Swap(x, y);
422
423 /* Make sure we never roam outside of the map, better wrap in that case */
424 return Map::WrapToMap(tile + TileDiffXY(x, y));
425}
426
434uint32_t GetNearbyTileInformation(TileIndex tile, bool grf_version8)
435{
436 TileType tile_type = GetTileType(tile);
437
438 /* Fake tile type for trees on shore */
439 if (IsTileType(tile, MP_TREES) && GetTreeGround(tile) == TREE_GROUND_SHORE) tile_type = MP_WATER;
440
441 /* Fake tile type for road waypoints */
442 if (IsRoadWaypointTile(tile)) tile_type = MP_ROAD;
443
444 auto [tileh, z] = GetTilePixelSlope(tile);
445 /* Return 0 if the tile is a land tile */
446 uint8_t terrain_type = (HasTileWaterClass(tile) ? (GetWaterClass(tile) + 1) & 3 : 0) << 5 | GetTerrainType(tile) << 2 | (tile_type == MP_WATER ? 1 : 0) << 1;
447 if (grf_version8) z /= TILE_HEIGHT;
448 return tile_type << 24 | ClampTo<uint8_t>(z) << 16 | terrain_type << 8 | tileh;
449}
450
457uint32_t GetCompanyInfo(CompanyID owner, const Livery *l)
458{
459 if (l == nullptr && Company::IsValidID(owner)) l = &Company::Get(owner)->livery[LS_DEFAULT];
460 return owner.base() | (Company::IsValidAiID(owner) ? 0x10000 : 0) | (l != nullptr ? (l->colour1 << 24) | (l->colour2 << 28) : 0);
461}
462
470CommandCost GetErrorMessageFromLocationCallbackResult(uint16_t cb_res, const GRFFile *grffile, StringID default_error)
471{
472 CommandCost res;
473
474 if (cb_res < 0x400) {
475 res = CommandCost(GetGRFStringID(grffile->grfid, GRFSTR_MISC_GRF_TEXT + cb_res));
476 } else {
477 switch (cb_res) {
478 case 0x400: return res; // No error.
479
480 default: // unknown reason -> default error
481 case 0x401: res = CommandCost(default_error); break;
482
483 case 0x402: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST); break;
484 case 0x403: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT); break;
485 case 0x404: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_ABOVE_SNOW_LINE); break;
486 case 0x405: res = CommandCost(STR_ERROR_CAN_ONLY_BE_BUILT_BELOW_SNOW_LINE); break;
487 case 0x406: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_SEA); break;
488 case 0x407: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_CANAL); break;
489 case 0x408: res = CommandCost(STR_ERROR_CAN_T_BUILD_ON_RIVER); break;
490 }
491 }
492
493 /* If this error isn't for the local player then it won't be seen, so don't bother encoding anything. */
494 if (!IsLocalCompany()) return res;
495
496 /* Copy some parameters from the registers to the error message text ref. stack */
497 std::array<StringParameter, 20> params{};
498 res.UseTextRefStack(grffile, 4);
500
501 return res;
502}
503
511void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
512{
513 GRFConfig *grfconfig = GetGRFConfig(grfid);
514
515 if (grfconfig->grf_bugs.Test(GRFBug::UnknownCbResult)) {
517 ShowErrorMessage(GetEncodedString(STR_NEWGRF_BUGGY, grfconfig->GetName()),
518 GetEncodedString(STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT, std::monostate{}, cbid, cb_res),
520 }
521
522 /* debug output */
523 Debug(grf, 0, "{}", StrMakeValid(GetString(STR_NEWGRF_BUGGY, grfconfig->GetName())));
524
525 Debug(grf, 0, "{}", StrMakeValid(GetString(STR_NEWGRF_BUGGY_UNKNOWN_CALLBACK_RESULT, cbid, cb_res)));
526}
527
537bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
538{
539 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
540
541 if (grffile->grf_version < 8) return cb_res != 0;
542
543 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
544 return cb_res != 0;
545}
546
556bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
557{
558 assert(cb_res != CALLBACK_FAILED); // We do not know what to return
559
560 if (grffile->grf_version < 8) return GB(cb_res, 0, 8) != 0;
561
562 if (cb_res > 1) ErrorUnknownCallbackResult(grffile->grfid, cbid, cb_res);
563 return cb_res != 0;
564}
565
566
567/* static */ std::vector<DrawTileSeqStruct> NewGRFSpriteLayout::result_seq;
568
569
574void NewGRFSpriteLayout::Allocate(uint num_sprites)
575{
576 assert(this->seq.empty());
577
578 this->seq.resize(num_sprites, {});
579}
580
585{
586 assert(this->registers.empty());
587
588 this->registers.resize(1 + this->seq.size(), {}); // 1 for the ground sprite
589}
590
603uint32_t NewGRFSpriteLayout::PrepareLayout(uint32_t orig_offset, uint32_t newgrf_ground_offset, uint32_t newgrf_offset, uint constr_stage, bool separate_ground) const
604{
605 result_seq.clear();
606 uint32_t var10_values = 0;
607
608 /* Create a copy of the spritelayout, so we can modify some values.
609 * Also include the groundsprite into the sequence for easier processing. */
610 DrawTileSeqStruct &copy = result_seq.emplace_back();
611 copy.image = ground;
612 copy.delta_z = static_cast<int8_t>(0x80);
613
614 for (const DrawTileSeqStruct &dtss : this->seq) {
615 result_seq.emplace_back(dtss);
616 }
617 /* Determine the var10 values the action-1-2-3 chains needs to be resolved for,
618 * and apply the default sprite offsets (unless disabled). */
619 const TileLayoutRegisters *regs = this->registers.empty() ? nullptr : this->registers.data();
620 bool ground = true;
621 for (DrawTileSeqStruct result : result_seq) {
622 TileLayoutFlags flags = TLF_NOTHING;
623 if (regs != nullptr) flags = regs->flags;
624
625 /* Record var10 value for the sprite */
626 if (HasBit(result.image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
627 uint8_t var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
628 SetBit(var10_values, var10);
629 }
630
631 /* Add default sprite offset, unless there is a custom one */
632 if (!(flags & TLF_SPRITE)) {
633 if (HasBit(result.image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
634 result.image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
635 if (constr_stage > 0 && regs != nullptr) result.image.sprite += GetConstructionStageOffset(constr_stage, regs->max_sprite_offset);
636 } else {
637 result.image.sprite += orig_offset;
638 }
639 }
640
641 /* Record var10 value for the palette */
642 if (HasBit(result.image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS)) {
643 uint8_t var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
644 SetBit(var10_values, var10);
645 }
646
647 /* Add default palette offset, unless there is a custom one */
648 if (!(flags & TLF_PALETTE)) {
649 if (HasBit(result.image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
650 result.image.sprite += ground ? newgrf_ground_offset : newgrf_offset;
651 if (constr_stage > 0 && regs != nullptr) result.image.sprite += GetConstructionStageOffset(constr_stage, regs->max_palette_offset);
652 }
653 }
654
655 ground = false;
656 if (regs != nullptr) regs++;
657 }
658
659 return var10_values;
660}
661
670void NewGRFSpriteLayout::ProcessRegisters(uint8_t resolved_var10, uint32_t resolved_sprite, bool separate_ground) const
671{
672 const TileLayoutRegisters *regs = this->registers.empty() ? nullptr : this->registers.data();
673 bool ground = true;
674 for (DrawTileSeqStruct &result : result_seq) {
675 TileLayoutFlags flags = TLF_NOTHING;
676 if (regs != nullptr) flags = regs->flags;
677
678 /* Is the sprite or bounding box affected by an action-1-2-3 chain? */
679 if (HasBit(result.image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_SPRITE_REG_FLAGS)) {
680 /* Does the var10 value apply to this sprite? */
681 uint8_t var10 = (flags & TLF_SPRITE_VAR10) ? regs->sprite_var10 : (ground && separate_ground ? 1 : 0);
682 if (var10 == resolved_var10) {
683 /* Apply registers */
684 if ((flags & TLF_DODRAW) && GetRegister(regs->dodraw) == 0) {
685 result.image.sprite = 0;
686 } else {
687 if (HasBit(result.image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) result.image.sprite += resolved_sprite;
688 if (flags & TLF_SPRITE) {
689 int16_t offset = (int16_t)GetRegister(regs->sprite); // mask to 16 bits to avoid trouble
690 if (!HasBit(result.image.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_sprite_offset)) {
691 result.image.sprite += offset;
692 } else {
693 result.image.sprite = SPR_IMG_QUERY;
694 }
695 }
696
697 if (result.IsParentSprite()) {
698 if (flags & TLF_BB_XY_OFFSET) {
699 result.delta_x += static_cast<int32_t>(GetRegister(regs->delta.parent[0]));
700 result.delta_y += static_cast<int32_t>(GetRegister(regs->delta.parent[1]));
701 }
702 if (flags & TLF_BB_Z_OFFSET) result.delta_z += static_cast<int32_t>(GetRegister(regs->delta.parent[2]));
703 } else {
704 if (flags & TLF_CHILD_X_OFFSET) result.delta_x += static_cast<int32_t>(GetRegister(regs->delta.child[0]));
705 if (flags & TLF_CHILD_Y_OFFSET) result.delta_y += static_cast<int32_t>(GetRegister(regs->delta.child[1]));
706 }
707 }
708 }
709 }
710
711 /* Is the palette affected by an action-1-2-3 chain? */
712 if (result.image.sprite != 0 && (HasBit(result.image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (flags & TLF_PALETTE_REG_FLAGS))) {
713 /* Does the var10 value apply to this sprite? */
714 uint8_t var10 = (flags & TLF_PALETTE_VAR10) ? regs->palette_var10 : (ground && separate_ground ? 1 : 0);
715 if (var10 == resolved_var10) {
716 /* Apply registers */
717 if (HasBit(result.image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) result.image.pal += resolved_sprite;
718 if (flags & TLF_PALETTE) {
719 int16_t offset = (int16_t)GetRegister(regs->palette); // mask to 16 bits to avoid trouble
720 if (!HasBit(result.image.pal, SPRITE_MODIFIER_CUSTOM_SPRITE) || (offset >= 0 && offset < regs->max_palette_offset)) {
721 result.image.pal += offset;
722 } else {
723 result.image.sprite = SPR_IMG_QUERY;
724 result.image.pal = PAL_NONE;
725 }
726 }
727 }
728 }
729
730 ground = false;
731 if (regs != nullptr) regs++;
732 }
733}
734
741{
742 auto it = std::ranges::lower_bound(this->spritegroups, index, std::less{}, &CargoSpriteGroup::first);
743 if (it == std::end(this->spritegroups) || it->first != index) return nullptr;
744 return it->second;
745}
746
752void VariableGRFFileProps::SetSpriteGroup(size_t index, const SpriteGroup *spritegroup)
753{
754 auto it = std::ranges::lower_bound(this->spritegroups, index, std::less{}, &CargoSpriteGroup::first);
755 if (it == std::end(this->spritegroups) || it->first != index) {
756 this->spritegroups.emplace(it, index, spritegroup);
757 } else {
758 it->second = spritegroup;
759 }
760}
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
int GetBridgeHeight(TileIndex t)
Get the height ('z') of a bridge.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
Common return value for all commands.
static void SetEncodedMessage(EncodedString &&message)
Set the encoded message string.
void UseTextRefStack(const GRFFile *grffile, uint num_registers)
Activate usage of the NewGRF TextRefStack for the error message.
Definition command.cpp:424
StringID GetErrorMessage() const
Returns the error message of a command.
void SetEntitySpec(const HouseSpec *hs)
Install the specs into the HouseSpecs array It will find itself the proper slot on which it will go.
uint16_t AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id) override
Method to find an entity ID and to mark it as reserved for the Industry to be included.
void SetEntitySpec(IndustrySpec *inds)
Method to install the new industry data in its proper slot The slot assignment is internal of this me...
uint16_t GetID(uint16_t grf_local_id, uint32_t grfid) const override
Return the ID (if ever available) of a previously inserted entity.
void SetEntitySpec(ObjectSpec *spec)
Method to install the new object data in its proper slot The slot assignment is internal of this meth...
uint32_t GetGRFID(uint16_t entity_id) const
Gives the GRFID of the file the entity belongs to.
void ResetMapping()
Resets the mapping, which is used while initializing game.
uint16_t max_entities
what is the amount of entities, old and new summed
virtual uint16_t GetID(uint16_t grf_local_id, uint32_t grfid) const
Return the ID (if ever available) of a previously inserted entity.
uint16_t invalid_id
ID used to detected invalid entities.
void Add(uint16_t local_id, uint32_t grfid, uint entity_type)
Since the entity IDs defined by the GRF file does not necessarily correlate to those used by the game...
OverrideManagerBase(uint16_t offset, uint16_t maximum, uint16_t invalid)
Constructor of generic class.
std::vector< EntityIDMapping > mappings
mapping of ids from grf files. Public out of convenience
void ResetOverride()
Resets the override, which is used while initializing game.
uint16_t GetSubstituteID(uint16_t entity_id) const
Gives the substitute of the entity, as specified by the grf file.
uint16_t max_offset
what is the length of the original entity's array of specs
virtual uint16_t AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
Reserves a place in the mapping array for an entity to be installed.
Map accessors for 'clear' tiles.
bool IsSnowTile(Tile t)
Test if a tile is covered with snow.
Definition clear_map.h:35
uint GetClearDensity(Tile t)
Get the density of a non-field clear tile.
Definition clear_map.h:83
Definition of stuff that is very close to a company, like the company struct itself.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
Axis
Allow incrementing of DiagDirDiff variables.
@ INVALID_AXIS
Flag for an invalid Axis.
@ AXIS_Y
The y axis.
Functions related to errors.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, const CommandCost &cc)
Display an error message in a window.
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:72
Functions related to world/map generation.
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
definition of HouseSpec and accessors
uint16_t HouseID
OpenTTD ID of house types.
Definition house_type.h:13
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
Industry type specs.
Functions related to OTTD's landscape.
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:388
constexpr void Swap(T &a, T &b)
Type safe swap operation.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
CommandCost GetErrorMessageFromLocationCallbackResult(uint16_t cb_res, const GRFFile *grffile, StringID default_error)
Get the error message from a shape/location/slope check callback result.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
uint32_t GetCompanyInfo(CompanyID owner, const Livery *l)
Returns company information like in vehicle var 43 or station var 43.
uint32_t GetNearbyTileInformation(TileIndex tile, bool grf_version8)
Common part of station var 0x67, house var 0x62, indtile var 0x60, industry var 0x62.
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
uint32_t GetTerrainType(TileIndex tile, TileContext context)
Function used by houses (and soon industries) to get information on type of "terrain" the tile it is ...
TileIndex GetNearbyTile(uint8_t parameter, TileIndex tile, bool signed_offsets, Axis axis)
Get the tile at the given offset.
TileContext
Context for tile accesses.
@ TCX_UPPER_HALFTILE
Querying information about the upper part of a tile with halftile foundation.
@ TCX_ON_BRIDGE
Querying information about stuff on the bridge (via some bridgehead).
TileLayoutFlags
Flags to enable register usage in sprite layouts.
@ TLF_BB_Z_OFFSET
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta....
@ TLF_SPRITE
Add signed offset to sprite from register TileLayoutRegisters::sprite.
@ TLF_CHILD_X_OFFSET
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta....
@ TLF_DODRAW
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
@ TLF_PALETTE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the palette, even if it is no action-1 palet...
@ TLF_BB_XY_OFFSET
Add signed offset to bounding box X and Y positions from register TileLayoutRegisters::delta....
@ TLF_SPRITE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the sprite, even if it is no action-1 sprite...
@ TLF_PALETTE_VAR10
Resolve palette with a specific value in variable 10.
@ TLF_SPRITE_VAR10
Resolve sprite with a specific value in variable 10.
@ TLF_PALETTE
Add signed offset to palette from register TileLayoutRegisters::palette.
@ TLF_CHILD_Y_OFFSET
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta....
uint GetConstructionStageOffset(uint construction_stage, uint num_sprites)
Determines which sprite to use from a spriteset for a specific construction stage.
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Functions to find and configure NewGRFs.
@ UnknownCbResult
A callback returned an unknown/invalid result.
std::vector< ObjectSpec > _object_specs
All the object specifications.
Functions related to NewGRF objects.
Action 2 handling.
uint32_t GetRegister(uint i)
Gets the value of a so-called newgrf "register".
StringID GetGRFStringID(uint32_t grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
uint16_t ObjectType
Types of objects.
Definition object_type.h:16
static const ObjectType OBJECT_TRANSMITTER
The large antenna.
Definition object_type.h:18
RailGroundType
The ground 'under' the rail.
Definition rail_map.h:485
@ RAIL_GROUND_ICE_DESERT
Icy or sandy.
Definition rail_map.h:498
@ RAIL_GROUND_HALF_SNOW
Snow only on higher part of slope (steep or one corner raised)
Definition rail_map.h:500
bool IsOnSnow(Tile t)
Check if a road tile has snow/desert.
Definition road_map.h:459
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:58
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1545
Maps accessors for stations.
bool HasStationTileRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
bool IsRoadWaypointTile(Tile t)
Is this tile a station tile and a road waypoint?
Definition of base types and functions in a cross-platform compatible way.
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition string.cpp:126
Functions related to low-level strings.
EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
Definition strings.cpp:115
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:103
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition strings.cpp:420
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static bool IsValidAiID(auto index)
Is this company a valid company, controlled by the computer (a NoAI program)?
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition sprite.h:25
int8_t delta_z
0x80 identifies child sprites
Definition sprite.h:28
PalSpriteID ground
Palette and sprite for the ground.
Definition sprite.h:47
Maps an entity id stored on the map to a GRF file.
uint16_t substitute_id
The (original) entity ID to use if this GRF is not available.
uint32_t grfid
The GRF ID of the file the entity belongs to.
uint16_t entity_id
The entity ID within the GRF file.
Information about GRF, used in the game and (part of it) in savegames.
GRFBugs grf_bugs
NOSAVE: bugs in this GRF in this run,.
const char * GetName() const
Get the name of this grf.
uint16_t local_id
id defined by the grf file for this entity
uint32_t grfid
grfid that introduced this entity.
bool HasGrfFile() const
Test if this entity was introduced by NewGRF.
uint16_t override
id of the entity been replaced by
Dynamic data of a loaded NewGRF.
Definition newgrf.h:112
LandscapeType landscape
the landscape we're currently in
GameCreationSettings game_creation
settings used during the creation of a game (map)
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
GRFFileProps grf_prop
Properties related the the grf file.
Definition house.h:109
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
Defines the data structure for constructing industry.
GRFFileProps grf_prop
properties related to the grf file
bool enabled
entity still available (by default true).newgrf can disable it, though
Defines the data structure of each individual tile of an industry.
GRFFileProps grf_prop
properties related to the grf file
bool enabled
entity still available (by default true).newgrf can disable it, though
Information about a particular livery.
Definition livery.h:78
Colours colour2
Second colour, for vehicles with 2CC support.
Definition livery.h:81
Colours colour1
First colour, for all vehicles.
Definition livery.h:80
static TileIndex WrapToMap(TileIndex tile)
'Wraps' the given "tile" so it is within the map.
Definition map_func.h:316
void Allocate(uint num_sprites)
Allocate a spritelayout for num_sprites building sprites.
uint32_t PrepareLayout(uint32_t orig_offset, uint32_t newgrf_ground_offset, uint32_t newgrf_offset, uint constr_stage, bool separate_ground) const
Prepares a sprite layout before resolving action-1-2-3 chains.
void ProcessRegisters(uint8_t resolved_var10, uint32_t resolved_sprite, bool separate_ground) const
Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
void AllocateRegisters()
Allocate memory for register modifiers.
static std::vector< DrawTileSeqStruct > result_seq
Temporary storage when preprocessing spritelayouts.
Allow incrementing of ObjectClassID variables.
FixedGRFFileProps< 2 > grf_prop
Properties related the the grf file.
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:23
static Titem * Get(auto index)
Returns Titem with given index.
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Additional modifiers for items in sprite layouts.
uint8_t parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
TileLayoutFlags flags
Flags defining which members are valid and to be used.
uint8_t dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
uint16_t max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset)
uint8_t palette
Register specifying a signed offset for the palette.
uint8_t sprite_var10
Value for variable 10 when resolving the sprite.
uint16_t max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset)
uint8_t palette_var10
Value for variable 10 when resolving the palette.
uint8_t child[2]
Registers for signed offsets for the position of child sprites.
uint8_t sprite
Register specifying a signed offset for the sprite.
void SetSpriteGroup(size_t index, const struct SpriteGroup *spritegroup)
Set the SpriteGroup at the specified index.
std::vector< CargoSpriteGroup > spritegroups
pointers to the different sprite groups of the entity
const struct SpriteGroup * GetSpriteGroup(size_t index) const
Get the SpriteGroup at the specified index.
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition tile_map.cpp:136
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.cpp:116
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
std::tuple< Slope, int > GetTilePixelSlope(TileIndex tile)
Return the slope of a given tile.
Definition tile_map.h:289
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition tile_map.h:238
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
TileType
The different types of tiles.
Definition tile_type.h:47
@ MP_TREES
Tile got trees.
Definition tile_type.h:52
@ MP_ROAD
A tile with road (or tram tracks)
Definition tile_type.h:50
@ MP_STATION
A tile of a station.
Definition tile_type.h:53
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition tile_type.h:57
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition tile_type.h:48
@ MP_HOUSE
A house by a town.
Definition tile_type.h:51
@ MP_WATER
Water tile.
Definition tile_type.h:54
@ MP_RAILWAY
A railway.
Definition tile_type.h:49
@ MP_INDUSTRY
Part of an industry.
Definition tile_type.h:56
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition tile_type.h:55
@ MP_OBJECT
Contains objects such as transmitters and owned land.
Definition tile_type.h:58
Map accessors for tree tiles.
TreeGround GetTreeGround(Tile t)
Returns the groundtype for tree tiles.
Definition tree_map.h:102
TreeGround
Enumeration for ground types of tiles with trees.
Definition tree_map.h:52
@ TREE_GROUND_SHORE
shore
Definition tree_map.h:56
@ TREE_GROUND_ROUGH_SNOW
A snow tile that is rough underneath.
Definition tree_map.h:57
@ TREE_GROUND_SNOW_DESERT
a desert or snow tile, depend on landscape
Definition tree_map.h:55
uint GetTreeDensity(Tile t)
Returns the 'density' of a tile with trees.
Definition tree_map.h:127
Functions that have tunnels and bridges in common.
bool HasTunnelBridgeSnowOrDesert(Tile t)
Tunnel: Is this tunnel entrance in a snowy or desert area? Bridge: Does the bridge ramp lie in a snow...
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
Definition water_map.h:101
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition water_map.h:112