OpenTTD Source 20250311-master-g40ddc03423
newgrf_house.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
10#include "stdafx.h"
11#include "debug.h"
12#include "landscape.h"
13#include "newgrf_badge.h"
14#include "newgrf_house.h"
15#include "newgrf_spritegroup.h"
16#include "newgrf_town.h"
17#include "newgrf_sound.h"
18#include "company_func.h"
19#include "company_base.h"
20#include "town.h"
21#include "genworld.h"
23#include "newgrf_cargo.h"
24#include "station_base.h"
25
26#include "safeguards.h"
27
28static BuildingCounts<uint32_t> _building_counts{};
29static std::vector<HouseClassMapping> _class_mapping{};
30
31HouseOverrideManager _house_mngr(NEW_HOUSE_OFFSET, NUM_HOUSES, INVALID_HOUSE_ID);
32
38static const GRFFile *GetHouseSpecGrf(HouseID house_id)
39{
40 const HouseSpec *hs = HouseSpec::Get(house_id);
41 return (hs != nullptr) ? hs->grf_prop.grffile : nullptr;
42}
43
44extern const HouseSpec _original_house_specs[NEW_HOUSE_OFFSET];
45std::vector<HouseSpec> _house_specs;
46
51std::vector<HouseSpec> &HouseSpec::Specs()
52{
53 return _house_specs;
54}
55
61{
62 return static_cast<HouseID>(this - _house_specs.data());
63}
64
70HouseSpec *HouseSpec::Get(size_t house_id)
71{
72 /* Empty house if index is out of range -- this might happen if NewGRFs are changed. */
73 static HouseSpec empty = {};
74
75 assert(house_id < NUM_HOUSES);
76 if (house_id >= _house_specs.size()) return &empty;
77 return &_house_specs[house_id];
78}
79
80/* Reset and initialise house specs. */
81void ResetHouses()
82{
83 _house_specs.clear();
84 _house_specs.reserve(std::size(_original_house_specs));
85
86 ResetHouseClassIDs();
87
88 /* Copy default houses. */
89 _house_specs.insert(std::end(_house_specs), std::begin(_original_house_specs), std::end(_original_house_specs));
90
91 /* Reset any overrides that have been set. */
92 _house_mngr.ResetOverride();
93}
94
108 CallbackID callback, uint32_t param1, uint32_t param2,
109 bool not_yet_constructed, uint8_t initial_random_bits, CargoTypes watched_cargo_triggers, int view)
110 : ResolverObject(GetHouseSpecGrf(house_id), callback, param1, param2),
111 house_scope(*this, house_id, tile, town, not_yet_constructed, initial_random_bits, watched_cargo_triggers, view),
112 town_scope(*this, town, not_yet_constructed) // Don't access StorePSA if house is not yet constructed.
113{
114 /* Tile must be valid and a house tile, unless not yet constructed in which case it may also be INVALID_TILE. */
115 assert((IsValidTile(tile) && (not_yet_constructed || IsTileType(tile, MP_HOUSE))) || (not_yet_constructed && tile == INVALID_TILE));
116
118}
119
121{
122 return GSF_HOUSES;
123}
124
126{
127 return HouseSpec::Get(this->house_scope.house_id)->grf_prop.local_id;
128}
129
130void ResetHouseClassIDs()
131{
132 _class_mapping.clear();
133
134 /* Add initial entry for HOUSE_NO_CLASS. */
135 _class_mapping.emplace_back();
136}
137
138HouseClassID AllocateHouseClassID(uint8_t grf_class_id, uint32_t grfid)
139{
140 /* Start from 1 because 0 means that no class has been assigned. */
141 auto it = std::find_if(std::next(std::begin(_class_mapping)), std::end(_class_mapping), [grf_class_id, grfid](const HouseClassMapping &map) { return map.class_id == grf_class_id && map.grfid == grfid; });
142
143 /* HouseClass not found, allocate a new one. */
144 if (it == std::end(_class_mapping)) it = _class_mapping.insert(it, {.grfid = grfid, .class_id = grf_class_id});
145
146 return static_cast<HouseClassID>(std::distance(std::begin(_class_mapping), it));
147}
148
154{
155 t->cache.building_counts.id_count.clear();
156 t->cache.building_counts.class_count.clear();
157 t->cache.building_counts.id_count.resize(HouseSpec::Specs().size());
158 t->cache.building_counts.class_count.resize(_class_mapping.size());
159}
160
165{
166 _building_counts.id_count.clear();
167 _building_counts.class_count.clear();
168 _building_counts.id_count.resize(HouseSpec::Specs().size());
169 _building_counts.class_count.resize(_class_mapping.size());
170
171 for (Town *t : Town::Iterate()) {
173 }
174}
175
180std::span<const uint> GetBuildingHouseIDCounts()
181{
182 return _building_counts.id_count;
183}
184
192{
193 HouseClassID class_id = HouseSpec::Get(house_id)->class_id;
194
195 t->cache.building_counts.id_count[house_id]++;
196 _building_counts.id_count[house_id]++;
197
198 if (class_id == HOUSE_NO_CLASS) return;
199
200 t->cache.building_counts.class_count[class_id]++;
201 _building_counts.class_count[class_id]++;
202}
203
211{
212 HouseClassID class_id = HouseSpec::Get(house_id)->class_id;
213
214 if (t->cache.building_counts.id_count[house_id] > 0) t->cache.building_counts.id_count[house_id]--;
215 if (_building_counts.id_count[house_id] > 0) _building_counts.id_count[house_id]--;
216
217 if (class_id == HOUSE_NO_CLASS) return;
218
219 if (t->cache.building_counts.class_count[class_id] > 0) t->cache.building_counts.class_count[class_id]--;
220 if (_building_counts.class_count[class_id] > 0) _building_counts.class_count[class_id]--;
221}
222
223/* virtual */ uint32_t HouseScopeResolver::GetRandomBits() const
224{
225 /* Note: Towns build houses over houses. So during construction checks 'tile' may be a valid but unrelated house. */
227}
228
229/* virtual */ uint32_t HouseScopeResolver::GetTriggers() const
230{
231 /* Note: Towns build houses over houses. So during construction checks 'tile' may be a valid but unrelated house. */
232 return this->not_yet_constructed ? 0 : GetHouseTriggers(this->tile);
233}
234
235static uint32_t GetNumHouses(HouseID house_id, const Town *town)
236{
237 HouseClassID class_id = HouseSpec::Get(house_id)->class_id;
238
239 uint8_t map_id_count = ClampTo<uint8_t>(_building_counts.id_count[house_id]);
240 uint8_t map_class_count = ClampTo<uint8_t>(_building_counts.class_count[class_id]);
241 uint8_t town_id_count = ClampTo<uint8_t>(town->cache.building_counts.id_count[house_id]);
242 uint8_t town_class_count = ClampTo<uint8_t>(town->cache.building_counts.class_count[class_id]);
243
244 return map_class_count << 24 | town_class_count << 16 | map_id_count << 8 | town_id_count;
245}
246
254static uint32_t GetNearbyTileInformation(uint8_t parameter, TileIndex tile, bool grf_version8)
255{
256 tile = GetNearbyTile(parameter, tile);
257 return GetNearbyTileInformation(tile, grf_version8);
258}
259
265
272static bool SearchNearbyHouseID(TileIndex tile, void *user_data)
273{
274 if (IsTileType(tile, MP_HOUSE)) {
275 HouseID house = GetHouseType(tile); // tile been examined
276 const HouseSpec *hs = HouseSpec::Get(house);
277 if (hs->grf_prop.HasGrfFile()) { // must be one from a grf file
278 SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data;
279
280 TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'!
281 if (north_tile == nbhd->north_tile) return false; // Always ignore origin house
282
283 return hs->grf_prop.local_id == nbhd->hs->grf_prop.local_id && // same local id as the one requested
284 hs->grf_prop.grfid == nbhd->hs->grf_prop.grfid; // from the same grf
285 }
286 }
287 return false;
288}
289
296static bool SearchNearbyHouseClass(TileIndex tile, void *user_data)
297{
298 if (IsTileType(tile, MP_HOUSE)) {
299 HouseID house = GetHouseType(tile); // tile been examined
300 const HouseSpec *hs = HouseSpec::Get(house);
301 if (hs->grf_prop.HasGrfFile()) { // must be one from a grf file
302 SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data;
303
304 TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'!
305 if (north_tile == nbhd->north_tile) return false; // Always ignore origin house
306
307 return hs->class_id == nbhd->hs->class_id && // same classid as the one requested
308 hs->grf_prop.grfid == nbhd->hs->grf_prop.grfid; // from the same grf
309 }
310 }
311 return false;
312}
313
320static bool SearchNearbyHouseGRFID(TileIndex tile, void *user_data)
321{
322 if (IsTileType(tile, MP_HOUSE)) {
323 HouseID house = GetHouseType(tile); // tile been examined
324 const HouseSpec *hs = HouseSpec::Get(house);
325 if (hs->grf_prop.HasGrfFile()) { // must be one from a grf file
326 SearchNearbyHouseData *nbhd = (SearchNearbyHouseData *)user_data;
327
328 TileIndex north_tile = tile + GetHouseNorthPart(house); // modifies 'house'!
329 if (north_tile == nbhd->north_tile) return false; // Always ignore origin house
330
331 return hs->grf_prop.grfid == nbhd->hs->grf_prop.grfid; // from the same grf
332 }
333 }
334 return false;
335}
336
347static uint32_t GetDistanceFromNearbyHouse(uint8_t parameter, TileIndex tile, HouseID house)
348{
349 static TestTileOnSearchProc * const search_procs[3] = {
353 };
354 TileIndex found_tile = tile;
355 uint8_t searchtype = GB(parameter, 6, 2);
356 uint8_t searchradius = GB(parameter, 0, 6);
357 if (searchtype >= lengthof(search_procs)) return 0; // do not run on ill-defined code
358 if (searchradius < 1) return 0; // do not use a too low radius
359
361 nbhd.hs = HouseSpec::Get(house);
362 nbhd.north_tile = tile + GetHouseNorthPart(house); // modifies 'house'!
363
364 /* Use a pointer for the tile to start the search. Will be required for calculating the distance*/
365 if (CircularTileSearch(&found_tile, 2 * searchradius + 1, search_procs[searchtype], &nbhd)) {
366 return DistanceManhattan(found_tile, tile);
367 }
368 return 0;
369}
370
374/* virtual */ uint32_t HouseScopeResolver::GetVariable(uint8_t variable, [[maybe_unused]] uint32_t parameter, bool &available) const
375{
376 if (this->tile == INVALID_TILE) {
377 /* House does not yet exist, nor is it being planned to exist. Provide some default values instead. */
378 switch (variable) {
379 case 0x40: return TOWN_HOUSE_COMPLETED | this->view << 2; /* Construction stage. */
380 case 0x41: return 0;
381 case 0x42: return 0;
382 case 0x43: return 0;
383 case 0x44: return 0;
384 case 0x45: return _generating_world ? 1 : 0;
385 case 0x46: return 0;
386 case 0x47: return 0;
387 case 0x60: return 0;
388 case 0x61: return 0;
389 case 0x62: return 0;
390 case 0x63: return 0;
391 case 0x64: return 0;
392 case 0x65: return 0;
393 case 0x66: return 0xFFFFFFFF; /* Class and ID of nearby house. */
394 case 0x67: return 0;
395
396 case 0x7A: return GetBadgeVariableResult(*this->ro.grffile, HouseSpec::Get(this->house_id)->badges, parameter);
397 }
398
399 Debug(grf, 1, "Unhandled house variable 0x{:X}", variable);
400 available = false;
401 return UINT_MAX;
402 }
403
404 switch (variable) {
405 /* Construction stage. */
406 case 0x40: return (IsTileType(this->tile, MP_HOUSE) ? GetHouseBuildingStage(this->tile) : 0) | TileHash2Bit(TileX(this->tile), TileY(this->tile)) << 2;
407
408 /* Building age. */
409 case 0x41: return IsTileType(this->tile, MP_HOUSE) ? GetHouseAge(this->tile).base() : 0;
410
411 /* Town zone */
412 case 0x42: return GetTownRadiusGroup(this->town, this->tile);
413
414 /* Terrain type */
415 case 0x43: return GetTerrainType(this->tile);
416
417 /* Number of this type of building on the map. */
418 case 0x44: return GetNumHouses(this->house_id, this->town);
419
420 /* Whether the town is being created or just expanded. */
421 case 0x45: return _generating_world ? 1 : 0;
422
423 /* Current animation frame. */
424 case 0x46: return IsTileType(this->tile, MP_HOUSE) ? GetAnimationFrame(this->tile) : 0;
425
426 /* Position of the house */
427 case 0x47: return TileY(this->tile) << 16 | TileX(this->tile);
428
429 /* Building counts for old houses with id = parameter. */
430 case 0x60: return parameter < NEW_HOUSE_OFFSET ? GetNumHouses(parameter, this->town) : 0;
431
432 /* Building counts for new houses with id = parameter. */
433 case 0x61: {
434 const HouseSpec *hs = HouseSpec::Get(this->house_id);
435 if (!hs->grf_prop.HasGrfFile()) return 0;
436
437 HouseID new_house = _house_mngr.GetID(parameter, hs->grf_prop.grfid);
438 return new_house == INVALID_HOUSE_ID ? 0 : GetNumHouses(new_house, this->town);
439 }
440
441 /* Land info for nearby tiles. */
442 case 0x62: return GetNearbyTileInformation(parameter, this->tile, this->ro.grffile->grf_version >= 8);
443
444 /* Current animation frame of nearby house tiles */
445 case 0x63: {
446 TileIndex testtile = GetNearbyTile(parameter, this->tile);
447 return IsTileType(testtile, MP_HOUSE) ? GetAnimationFrame(testtile) : 0;
448 }
449
450 /* Cargo acceptance history of nearby stations */
451 case 0x64: {
452 CargoType cargo_type = GetCargoTranslation(parameter, this->ro.grffile);
453 if (!IsValidCargoType(cargo_type)) return 0;
454
455 /* Extract tile offset. */
456 int8_t x_offs = GB(GetRegister(0x100), 0, 8);
457 int8_t y_offs = GB(GetRegister(0x100), 8, 8);
458 TileIndex testtile = Map::WrapToMap(this->tile + TileDiffXY(x_offs, y_offs));
459
460 StationFinder stations(TileArea(testtile, 1, 1));
461
462 /* Collect acceptance stats. */
463 uint32_t res = 0;
464 for (Station *st : stations.GetStations()) {
465 if (HasBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED)) SetBit(res, 0);
466 if (HasBit(st->goods[cargo_type].status, GoodsEntry::GES_LAST_MONTH)) SetBit(res, 1);
467 if (HasBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH)) SetBit(res, 2);
468 if (HasBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(res, 3);
469 }
470
471 /* Cargo triggered CB 148? */
472 if (HasBit(this->watched_cargo_triggers, cargo_type)) SetBit(res, 4);
473
474 return res;
475 }
476
477 /* Distance test for some house types */
478 case 0x65: return GetDistanceFromNearbyHouse(parameter, this->tile, this->house_id);
479
480 /* Class and ID of nearby house tile */
481 case 0x66: {
482 TileIndex testtile = GetNearbyTile(parameter, this->tile);
483 if (!IsTileType(testtile, MP_HOUSE)) return 0xFFFFFFFF;
484 HouseID nearby_house_id = GetHouseType(testtile);
485 HouseSpec *hs = HouseSpec::Get(nearby_house_id);
486 /* Information about the grf local classid if the house has a class */
487 uint houseclass = 0;
488 if (hs->class_id != HOUSE_NO_CLASS) {
489 houseclass = (hs->grf_prop.grffile == this->ro.grffile ? 1 : 2) << 8;
490 houseclass |= _class_mapping[hs->class_id].class_id;
491 }
492 /* old house type or grf-local houseid */
493 uint local_houseid = 0;
494 if (nearby_house_id < NEW_HOUSE_OFFSET) {
495 local_houseid = nearby_house_id;
496 } else {
497 local_houseid = (hs->grf_prop.grffile == this->ro.grffile ? 1 : 2) << 8;
498 local_houseid |= ClampTo<uint8_t>(hs->grf_prop.local_id); // Spec only allows 8 bits, so all local-ids above 254 are clamped.
499 }
500 return houseclass << 16 | local_houseid;
501 }
502
503 /* GRFID of nearby house tile */
504 case 0x67: {
505 TileIndex testtile = GetNearbyTile(parameter, this->tile);
506 if (!IsTileType(testtile, MP_HOUSE)) return 0xFFFFFFFF;
507 HouseID house_id = GetHouseType(testtile);
508 if (house_id < NEW_HOUSE_OFFSET) return 0;
509 /* Checking the grffile information via HouseSpec doesn't work
510 * in case the newgrf was removed. */
511 return _house_mngr.GetGRFID(house_id);
512 }
513
514 case 0x7A: return GetBadgeVariableResult(*this->ro.grffile, HouseSpec::Get(this->house_id)->badges, parameter);
515 }
516
517 Debug(grf, 1, "Unhandled house variable 0x{:X}", variable);
518
519 available = false;
520 return UINT_MAX;
521}
522
523uint16_t GetHouseCallback(CallbackID callback, uint32_t param1, uint32_t param2, HouseID house_id, Town *town, TileIndex tile,
524 bool not_yet_constructed, uint8_t initial_random_bits, CargoTypes watched_cargo_triggers, int view)
525{
526 HouseResolverObject object(house_id, tile, town, callback, param1, param2,
527 not_yet_constructed, initial_random_bits, watched_cargo_triggers, view);
528 return object.ResolveCallback();
529}
530
531static void DrawTileLayout(const TileInfo *ti, const TileLayoutSpriteGroup *group, uint8_t stage, HouseID house_id)
532{
533 const DrawTileSprites *dts = group->ProcessRegisters(&stage);
534
535 const HouseSpec *hs = HouseSpec::Get(house_id);
536 PaletteID palette = GENERAL_SPRITE_COLOUR(hs->random_colour[TileHash2Bit(ti->x, ti->y)]);
538 uint16_t callback = GetHouseCallback(CBID_HOUSE_COLOUR, 0, 0, house_id, Town::GetByTile(ti->tile), ti->tile);
539 if (callback != CALLBACK_FAILED) {
540 /* If bit 14 is set, we should use a 2cc colour map, else use the callback value. */
541 palette = HasBit(callback, 14) ? GB(callback, 0, 8) + SPR_2CCMAP_BASE : callback;
542 }
543 }
544
545 SpriteID image = dts->ground.sprite;
546 PaletteID pal = dts->ground.pal;
547
548 if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) image += stage;
549 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += stage;
550
551 if (GB(image, 0, SPRITE_WIDTH) != 0) {
552 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
553 }
554
555 DrawNewGRFTileSeq(ti, dts, TO_HOUSES, stage, palette);
556}
557
558void DrawNewHouseTile(TileInfo *ti, HouseID house_id)
559{
560 const HouseSpec *hs = HouseSpec::Get(house_id);
561
562 if (ti->tileh != SLOPE_FLAT) {
563 bool draw_old_one = true;
565 /* Called to determine the type (if any) of foundation to draw for the house tile */
566 uint32_t callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, house_id, Town::GetByTile(ti->tile), ti->tile);
567 if (callback_res != CALLBACK_FAILED) draw_old_one = ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res);
568 }
569
570 if (draw_old_one) DrawFoundation(ti, FOUNDATION_LEVELED);
571 }
572
573 HouseResolverObject object(house_id, ti->tile, Town::GetByTile(ti->tile));
574
575 const SpriteGroup *group = object.Resolve();
576 if (group != nullptr && group->type == SGT_TILELAYOUT) {
577 /* Limit the building stage to the number of stages supplied. */
578 const TileLayoutSpriteGroup *tlgroup = (const TileLayoutSpriteGroup *)group;
579 uint8_t stage = GetHouseBuildingStage(ti->tile);
580 DrawTileLayout(ti, tlgroup, stage, house_id);
581 }
582}
583
584/* Simple wrapper for GetHouseCallback to keep the animation unified. */
585uint16_t GetSimpleHouseCallback(CallbackID callback, uint32_t param1, uint32_t param2, const HouseSpec *spec, Town *town, TileIndex tile, CargoTypes extra_data)
586{
587 return GetHouseCallback(callback, param1, param2, spec - HouseSpec::Get(0), town, tile, false, 0, extra_data);
588}
589
591struct HouseAnimationBase : public AnimationBase<HouseAnimationBase, HouseSpec, Town, CargoTypes, GetSimpleHouseCallback, TileAnimationFrameAnimationHelper<Town> > {
592 static constexpr CallbackID cb_animation_speed = CBID_HOUSE_ANIMATION_SPEED;
593 static constexpr CallbackID cb_animation_next_frame = CBID_HOUSE_ANIMATION_NEXT_FRAME;
594
595 static constexpr HouseCallbackMask cbm_animation_speed = HouseCallbackMask::AnimationSpeed;
596 static constexpr HouseCallbackMask cbm_animation_next_frame = HouseCallbackMask::AnimationNextFrame;
597};
598
599void AnimateNewHouseTile(TileIndex tile)
600{
601 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
602 if (hs == nullptr) return;
603
605}
606
607void AnimateNewHouseConstruction(TileIndex tile)
608{
609 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
610
613 }
614}
615
616bool CanDeleteHouse(TileIndex tile)
617{
618 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
619
620 /* Humans are always allowed to remove buildings, as is water and disasters and
621 * anyone using the scenario editor. */
623 return true;
624 }
625
627 uint16_t callback_res = GetHouseCallback(CBID_HOUSE_DENY_DESTRUCTION, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
628 return (callback_res == CALLBACK_FAILED || !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DENY_DESTRUCTION, callback_res));
629 } else {
630 return !IsHouseProtected(tile);
631 }
632}
633
634static void AnimationControl(TileIndex tile, uint16_t random_bits)
635{
636 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
637
639 uint32_t param = hs->extra_flags.Test(HouseExtraFlag::SynchronisedCallback1B) ? (GB(Random(), 0, 16) | random_bits << 16) : Random();
640 HouseAnimationBase::ChangeAnimationFrame(CBID_HOUSE_ANIMATION_START_STOP, hs, Town::GetByTile(tile), tile, param, 0);
641 }
642}
643
644bool NewHouseTileLoop(TileIndex tile)
645{
646 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
647
648 if (GetHouseProcessingTime(tile) > 0) {
650 return true;
651 }
652
653 TriggerHouse(tile, HOUSE_TRIGGER_TILE_LOOP);
654 if (hs->building_flags.Any(BUILDING_HAS_1_TILE)) TriggerHouse(tile, HOUSE_TRIGGER_TILE_LOOP_TOP);
655
657 /* If this house is marked as having a synchronised callback, all the
658 * tiles will have the callback called at once, rather than when the
659 * tile loop reaches them. This should only be enabled for the northern
660 * tile, or strange things will happen (here, and in TTDPatch). */
662 uint16_t random = GB(Random(), 0, 16);
663
664 if (hs->building_flags.Any(BUILDING_HAS_1_TILE)) AnimationControl(tile, random);
665 if (hs->building_flags.Any(BUILDING_2_TILES_Y)) AnimationControl(TileAddXY(tile, 0, 1), random);
666 if (hs->building_flags.Any(BUILDING_2_TILES_X)) AnimationControl(TileAddXY(tile, 1, 0), random);
667 if (hs->building_flags.Any(BUILDING_HAS_4_TILES)) AnimationControl(TileAddXY(tile, 1, 1), random);
668 } else {
669 AnimationControl(tile, 0);
670 }
671 }
672
673 /* Check callback 21, which determines if a house should be destroyed. */
675 uint16_t callback_res = GetHouseCallback(CBID_HOUSE_DESTRUCTION, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
676 if (callback_res != CALLBACK_FAILED && Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DESTRUCTION, callback_res)) {
677 ClearTownHouse(Town::GetByTile(tile), tile);
678 return false;
679 }
680 }
681
684 return true;
685}
686
687static void DoTriggerHouse(TileIndex tile, HouseTrigger trigger, uint8_t base_random, bool first)
688{
689 /* We can't trigger a non-existent building... */
690 assert(IsTileType(tile, MP_HOUSE));
691
692 HouseID hid = GetHouseType(tile);
693 HouseSpec *hs = HouseSpec::Get(hid);
694
695 if (hs->grf_prop.GetSpriteGroup() == nullptr) return;
696
697 HouseResolverObject object(hid, tile, Town::GetByTile(tile), CBID_RANDOM_TRIGGER);
698 object.waiting_triggers = GetHouseTriggers(tile) | trigger;
699 SetHouseTriggers(tile, object.waiting_triggers); // store now for var 5F
700
701 const SpriteGroup *group = object.Resolve();
702 if (group == nullptr) return;
703
704 /* Store remaining triggers. */
705 SetHouseTriggers(tile, object.GetRemainingTriggers());
706
707 /* Rerandomise bits. Scopes other than SELF are invalid for houses. For bug-to-bug-compatibility with TTDP we ignore the scope. */
708 uint8_t new_random_bits = Random();
709 uint8_t random_bits = GetHouseRandomBits(tile);
710 uint32_t reseed = object.GetReseedSum();
711 random_bits &= ~reseed;
712 random_bits |= (first ? new_random_bits : base_random) & reseed;
713 SetHouseRandomBits(tile, random_bits);
714
715 switch (trigger) {
716 case HOUSE_TRIGGER_TILE_LOOP:
717 /* Random value already set. */
718 break;
719
720 case HOUSE_TRIGGER_TILE_LOOP_TOP:
721 if (!first) {
722 /* The top tile is marked dirty by the usual TileLoop */
724 break;
725 }
726 /* Random value of first tile already set. */
727 if (hs->building_flags.Any(BUILDING_2_TILES_Y)) DoTriggerHouse(TileAddXY(tile, 0, 1), trigger, random_bits, false);
728 if (hs->building_flags.Any(BUILDING_2_TILES_X)) DoTriggerHouse(TileAddXY(tile, 1, 0), trigger, random_bits, false);
729 if (hs->building_flags.Any(BUILDING_HAS_4_TILES)) DoTriggerHouse(TileAddXY(tile, 1, 1), trigger, random_bits, false);
730 break;
731 }
732}
733
734void TriggerHouse(TileIndex t, HouseTrigger trigger)
735{
736 DoTriggerHouse(t, trigger, 0, true);
737}
738
746void DoWatchedCargoCallback(TileIndex tile, TileIndex origin, CargoTypes trigger_cargoes, uint16_t random)
747{
748 TileIndexDiffC diff = TileIndexToTileIndexDiffC(origin, tile);
749 uint32_t cb_info = random << 16 | (uint8_t)diff.y << 8 | (uint8_t)diff.x;
750 HouseAnimationBase::ChangeAnimationFrame(CBID_HOUSE_WATCHED_CARGO_ACCEPTED, HouseSpec::Get(GetHouseType(tile)), Town::GetByTile(tile), tile, 0, cb_info, trigger_cargoes);
751}
752
759void WatchedCargoCallback(TileIndex tile, CargoTypes trigger_cargoes)
760{
761 assert(IsTileType(tile, MP_HOUSE));
762 HouseID id = GetHouseType(tile);
763 const HouseSpec *hs = HouseSpec::Get(id);
764
765 trigger_cargoes &= hs->watched_cargoes;
766 /* None of the trigger cargoes is watched? */
767 if (trigger_cargoes == 0) return;
768
769 /* Same random value for all tiles of a multi-tile house. */
770 uint16_t r = Random();
771
772 /* Do the callback, start at northern tile. */
773 TileIndex north = tile + GetHouseNorthPart(id);
774 hs = HouseSpec::Get(id);
775
776 DoWatchedCargoCallback(north, tile, trigger_cargoes, r);
777 if (hs->building_flags.Any(BUILDING_2_TILES_Y)) DoWatchedCargoCallback(TileAddXY(north, 0, 1), tile, trigger_cargoes, r);
778 if (hs->building_flags.Any(BUILDING_2_TILES_X)) DoWatchedCargoCallback(TileAddXY(north, 1, 0), tile, trigger_cargoes, r);
779 if (hs->building_flags.Any(BUILDING_HAS_4_TILES)) DoWatchedCargoCallback(TileAddXY(north, 1, 1), tile, trigger_cargoes, r);
780}
781
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.
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:23
bool IsValidCargoType(CargoType t)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:106
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
uint32_t GetGRFID(uint16_t entity_id) const
Gives the GRFID of the file the entity belongs to.
virtual uint16_t GetID(uint16_t grf_local_id, uint32_t grfid) const
Return the ID (if ever available) of a previously inserted entity.
void ResetOverride()
Resets the override, which is used while initializing game.
Structure contains cached list of stations nearby.
const StationList & GetStations()
Run a tile loop to find stations around a tile, on demand.
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner OWNER_WATER
The tile/execution is done by "water".
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:72
Functions related to world/map generation.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
@ SynchronisedCallback1B
synchronized callback 1B will be performed, on multi tile houses
@ Callback1ARandomBits
callback 1A needs random bits
static const HouseID NUM_HOUSES
Total number of houses.
Definition house.h:29
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition house.h:28
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition house.h:25
uint16_t HouseClassID
Classes of houses.
Definition house_type.h:14
uint16_t HouseID
OpenTTD ID of house types.
Definition house_type.h:13
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Functions related to OTTD's landscape.
@ Random
Randomise borders.
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition map.cpp:243
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:142
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition map_func.h:469
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:388
bool TestTileOnSearchProc(TileIndex tile, void *user_data)
A callback function type for searching tiles.
Definition map_func.h:642
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:424
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:414
TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition map_func.h:530
GrfSpecFeature
Definition newgrf.h:68
Function implementations related to NewGRF animation.
uint32_t GetBadgeVariableResult(const GRFFile &grffile, std::span< const BadgeID > badges, uint32_t parameter)
Test for a matching badge in a list of badges, returning the number of matching bits.
Functions related to NewGRF badges.
@ DrawTileLayout
Use callback to select a tile layout to use when drawing.
CallbackID
List of implemented NewGRF callbacks.
@ CBID_HOUSE_ANIMATION_START_STOP
Called for periodically starting or stopping the animation.
@ CBID_HOUSE_CONSTRUCTION_STATE_CHANGE
Called whenever the construction state of a house changes.
@ CBID_HOUSE_COLOUR
Called to determine the colour of a town building.
@ CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house tile.
@ CBID_HOUSE_ANIMATION_SPEED
Called to indicate how long the current animation frame should last.
@ CBID_HOUSE_ANIMATION_NEXT_FRAME
Determine the next animation frame for a house.
@ CBID_HOUSE_DENY_DESTRUCTION
Called to determine whether a town building can be destroyed.
@ CBID_HOUSE_WATCHED_CARGO_ACCEPTED
Called when a cargo type specified in property 20 is accepted.
@ CBID_RANDOM_TRIGGER
Set when calling a randomizing trigger (almost undocumented).
@ CBID_HOUSE_DESTRUCTION
Called periodically to determine if a house should be destroyed.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
HouseCallbackMask
Callback masks for houses.
@ Destruction
trigger destruction of building
@ AnimationStartStop
periodically start/stop the animation
@ DrawFoundations
decides if default foundations need to be drawn
@ AnimationNextFrame
decides next animation frame
@ DenyDestruction
conditional protection
@ AnimationSpeed
decides animation speed
@ ConstructionStateChange
change animation when construction state changes
@ Colour
decide the colour of the building
CargoType GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoType.
Cargo support for NewGRFs.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
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.
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
static bool SearchNearbyHouseClass(TileIndex tile, void *user_data)
Callback function to search a house by its classID.
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town.
static uint32_t GetDistanceFromNearbyHouse(uint8_t parameter, TileIndex tile, HouseID house)
This function will activate a search around a central tile, looking for some houses that fit the requ...
void WatchedCargoCallback(TileIndex tile, CargoTypes trigger_cargoes)
Run watched cargo accepted callback for a house.
std::span< const uint > GetBuildingHouseIDCounts()
Get read-only span of total HouseID building counts.
void DoWatchedCargoCallback(TileIndex tile, TileIndex origin, CargoTypes trigger_cargoes, uint16_t random)
Run the watched cargo accepted callback for a single house tile.
void InitializeBuildingCounts()
Initialise global building counts and all town building counts.
static const GRFFile * GetHouseSpecGrf(HouseID house_id)
Retrieve the grf file associated with a house.
static bool SearchNearbyHouseID(TileIndex tile, void *user_data)
Callback function to search a house by its HouseID.
static bool SearchNearbyHouseGRFID(TileIndex tile, void *user_data)
Callback function to search a house by its grfID.
static uint32_t GetNearbyTileInformation(uint8_t parameter, TileIndex tile, bool grf_version8)
Get information about a nearby tile.
Functions related to NewGRF houses.
Functions related to NewGRF provided sounds.
Action 2 handling.
uint32_t GetRegister(uint i)
Gets the value of a so-called newgrf "register".
Functions to handle the town part of NewGRF towns.
A number of safeguards to prevent using unsafe methods.
@ SLOPE_FLAT
a flat tile
Definition slope_type.h:49
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition slope_type.h:95
void DrawNewGRFTileSeq(const struct TileInfo *ti, const DrawTileSprites *dts, TransparencyOption to, uint32_t stage, PaletteID default_palette)
Draw NewGRF industrytile or house sprite layout.
Definition sprite.h:130
PaletteID GroundSpritePaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_COLOUR to a palette entry of a ground sprite.
Definition sprite.h:174
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1549
static constexpr uint8_t SPRITE_WIDTH
number of bits for the sprite number
Definition sprites.h:1539
Base classes/functions for stations.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:277
Helper class for a unified approach to NewGRF animation.
static void AnimateTile(const HouseSpec *spec, Town *obj, TileIndex tile, bool random_animation, CargoTypes extra_data=0)
Animate a single tile.
static void ChangeAnimationFrame(CallbackID cb, const HouseSpec *spec, Town *obj, TileIndex tile, uint32_t random_bits, uint32_t trigger, CargoTypes extra_data=0)
Check a callback to determine what the next animation step is and execute that step.
static bool IsValidHumanID(auto index)
Is this company a valid company, not controlled by a NoAI program?
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:46
PalSpriteID ground
Palette and sprite for the ground.
Definition sprite.h:47
const struct SpriteGroup * GetSpriteGroup(size_t index=0) const
Get the SpriteGroup at the specified index.
const struct GRFFile * grffile
grf file that introduced this entity
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.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:111
@ GES_LAST_MONTH
Set when cargo was delivered for final delivery last month.
@ GES_CURRENT_MONTH
Set when cargo was delivered for final delivery this month.
@ GES_EVER_ACCEPTED
Set when a vehicle ever delivered cargo to the station for final delivery.
@ GES_ACCEPTED_BIGTICK
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
Helper class for animation control.
Makes class IDs unique to each GRF file.
uint8_t class_id
The class id within the grf file.
uint32_t grfid
The GRF ID of the file this class belongs to.
Resolver object to be used for houses (feature 07 spritegroups).
HouseResolverObject(HouseID house_id, TileIndex tile, Town *town, CallbackID callback=CBID_NO_CALLBACK, uint32_t param1=0, uint32_t param2=0, bool not_yet_constructed=false, uint8_t initial_random_bits=0, CargoTypes watched_cargo_triggers=0, int view=0)
Construct a resolver for a house.
uint32_t GetDebugID() const override
Get an identifier for the item being resolved.
GrfSpecFeature GetFeature() const override
Get the feature number being resolved for.
int view
View when house does yet exist.
Town * town
Town of this house.
TileIndex tile
Tile of this house.
CargoTypes watched_cargo_triggers
Cargo types that triggered the watched cargo callback.
uint32_t GetVariable(uint8_t variable, uint32_t parameter, bool &available) const override
uint16_t initial_random_bits
Random bits during construction checks.
uint32_t GetRandomBits() const override
Get a few random bits.
HouseID house_id
Type of house being queried.
uint32_t GetTriggers() const override
Get the triggers.
bool not_yet_constructed
True for construction check.
CargoTypes watched_cargoes
Cargo types watched for acceptance.
Definition house.h:118
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition house.h:104
uint8_t processing_time
Periodic refresh multiplier.
Definition house.h:116
HouseCallbackMasks callback_mask
Bitmask of house callbacks that have to be called.
Definition house.h:110
HouseExtraFlags extra_flags
some more flags
Definition house.h:113
HouseID Index() const
Gets the index of this spec.
HouseClassID class_id
defines the class this house has (not grf file based)
Definition house.h:114
GRFFileProps grf_prop
Properties related the the grf file.
Definition house.h:109
Colours random_colour[4]
4 "random" colours
Definition house.h:111
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
static TileIndex WrapToMap(TileIndex tile)
'Wraps' the given "tile" so it is within the map.
Definition map_func.h:316
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:23
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition gfx_type.h:24
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Interface for SpriteGroup-s to access the gamestate.
const GRFFile * grffile
GRFFile the resolved SpriteGroup belongs to.
const SpriteGroup * root_spritegroup
Root SpriteGroup to use for resolving.
ResolverObject & ro
Surrounding resolver object.
Structure with user-data for SearchNearbyHouseXXX - functions.
TileIndex north_tile
Northern tile of the house.
const HouseSpec * hs
Specs of the house that started the search.
virtual const SpriteGroup * Resolve(ResolverObject &object) const
Base sprite group resolver.
Station data structure.
A pair-construct of a TileIndexDiff.
Definition map_type.h:31
int16_t x
The x value of the coordinate.
Definition map_type.h:32
int16_t y
The y value of the coordinate.
Definition map_type.h:33
Tile information, used while rendering the tile.
Definition tile_cmd.h:43
int x
X position of the tile in unit coordinates.
Definition tile_cmd.h:44
Slope tileh
Slope of the tile.
Definition tile_cmd.h:46
TileIndex tile
Tile index.
Definition tile_cmd.h:47
int y
Y position of the tile in unit coordinates.
Definition tile_cmd.h:45
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
const DrawTileSprites * ProcessRegisters(uint8_t *stage) const
Process registers and the construction stage into the sprite layout.
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
Definition town.h:46
Town data structure.
Definition town.h:52
TownCache cache
Container for all cacheable data.
Definition town.h:55
uint8_t GetAnimationFrame(Tile t)
Get the current animation frame.
Definition tile_map.h:250
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition tile_map.h:161
uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition tile_map.h:342
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
@ MP_HOUSE
A house by a town.
Definition tile_type.h:51
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Base of the town class.
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
void ClearTownHouse(Town *t, TileIndex tile)
Clear a town house.
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
Definition town_map.h:60
void SetHouseRandomBits(Tile t, uint8_t random)
Set the random bits for this house.
Definition town_map.h:284
uint8_t GetHouseRandomBits(Tile t)
Get the random bits for this house.
Definition town_map.h:297
void SetHouseTriggers(Tile t, uint8_t triggers)
Set the activated triggers bits for this house.
Definition town_map.h:310
TimerGameCalendar::Year GetHouseAge(Tile t)
Get the age of the house.
Definition town_map.h:271
void DecHouseProcessingTime(Tile t)
Decrease the amount of time remaining before the tile loop processes this tile.
Definition town_map.h:358
uint8_t GetHouseBuildingStage(Tile t)
House Construction Scheme.
Definition town_map.h:205
uint8_t GetHouseTriggers(Tile t)
Get the already activated triggers bits for this house.
Definition town_map.h:323
void SetHouseProcessingTime(Tile t, uint8_t time)
Set the amount of time remaining before the tile loop processes this tile.
Definition town_map.h:347
bool IsHouseProtected(Tile t)
Check if the house is protected from removal by towns.
Definition town_map.h:82
uint8_t GetHouseProcessingTime(Tile t)
Get the amount of time remaining before the tile loop processes this tile.
Definition town_map.h:335
@ TO_HOUSES
town buildings
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition viewport.cpp:589