OpenTTD Source 20261112-master-gbcbec5e63f
town_cmd.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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "bridge.h"
12#include "misc/history_type.hpp"
13#include "misc/history_func.hpp"
14#include "road.h"
15#include "road_internal.h" /* Cleaning up road bits */
16#include "road_cmd.h"
17#include "landscape.h"
18#include "tilearea_spiral.h"
19#include "tilearea_type.h"
20#include "viewport_func.h"
21#include "viewport_kdtree.h"
22#include "command_func.h"
23#include "company_func.h"
24#include "industry.h"
25#include "station_base.h"
26#include "station_func.h"
27#include "waypoint_base.h"
28#include "station_kdtree.h"
29#include "company_base.h"
30#include "news_func.h"
31#include "error.h"
32#include "object.h"
33#include "genworld.h"
34#include "newgrf_debug.h"
35#include "newgrf_house.h"
36#include "newgrf_text.h"
37#include "autoslope.h"
38#include "tunnelbridge_map.h"
39#include "strings_func.h"
40#include "window_func.h"
41#include "string_func.h"
42#include "newgrf_cargo.h"
43#include "cheat_type.h"
44#include "animated_tile_func.h"
45#include "subsidy_func.h"
46#include "core/pool_func.hpp"
47#include "town.h"
48#include "town_kdtree.h"
49#include "townname_func.h"
50#include "core/random_func.hpp"
51#include "core/backup_type.hpp"
52#include "depot_base.h"
53#include "object_base.h"
54#include "ai/ai.hpp"
55#include "game/game.hpp"
56#include "town_cmd.h"
57#include "landscape_cmd.h"
58#include "road_cmd.h"
59#include "terraform_cmd.h"
60#include "tunnelbridge_cmd.h"
61#include "clear_map.h"
62#include "tree_map.h"
63#include "map_func.h"
64#include "script/api/script_event_types.hpp"
65#include "timer/timer.h"
69
70#include "table/strings.h"
71#include "table/town_land.h"
72
73#include "safeguards.h"
74
75/* Initialize the town-pool */
76TownPool _town_pool("Town");
78
79
80TownKdtree _town_kdtree{};
81
82void RebuildTownKdtree()
83{
84 std::vector<TownID> townids;
85 for (const Town *town : Town::Iterate()) {
86 townids.push_back(town->index);
87 }
88 _town_kdtree.Build(townids.begin(), townids.end());
89}
90
92static bool _generating_town = false;
93
103static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
104{
105 if (!IsTileOwner(tile, OWNER_TOWN)) return false;
106
108 bool town_owned = IsTileType(adjacent, TileType::Road) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
109
110 if (!town_owned) {
111 /* Or other adjacent road */
113 town_owned = IsTileType(adjacent, TileType::Road) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
114 }
115
116 return town_owned;
117}
118
120{
121 if (CleaningPool()) return;
122
123 /* Delete town authority window
124 * and remove from list of sorted towns */
125 CloseWindowById(WindowClass::TownView, this->index);
126 CloseWindowById(WindowClass::TownCargoGraph, this->index);
127
128#ifdef WITH_ASSERT
129 /* Check no industry is related to us. */
130 for (const Industry *i : Industry::Iterate()) {
131 assert(i->town != this);
132 }
133
134 /* ... and no object is related to us. */
135 for (const Object *o : Object::Iterate()) {
136 assert(o->town != this);
137 }
138
139 /* Check no tile is related to us. */
140 for (const auto tile : Map::Iterate()) {
141 switch (GetTileType(tile)) {
142 case TileType::House:
143 assert(GetTownIndex(tile) != this->index);
144 break;
145
146 case TileType::Road:
147 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
148 break;
149
151 assert(!TestTownOwnsBridge(tile, this));
152 break;
153
154 default:
155 break;
156 }
157 }
158#endif /* WITH_ASSERT */
159
160 /* Clear the persistent storage list. */
161 for (auto &psa : this->psa_list) {
162 delete psa;
163 }
164 this->psa_list.clear();
165
166 Source src{this->index, SourceType::Town};
171}
172
173
179void Town::PostDestructor([[maybe_unused]] size_t index)
180{
181 InvalidateWindowData(WindowClass::TownDirectory, 0, TDIWD_FORCE_REBUILD);
183
184 /* Give objects a new home! */
185 for (Object *o : Object::Iterate()) {
186 if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
187 }
188}
189
195{
196 if (layout != TownLayout::Random) {
197 this->layout = layout;
198 return;
199 }
200
201 this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (to_underlying(TownLayout::End) - 1));
202}
203
208/* static */ Town *Town::GetRandom()
209{
210 if (Town::GetNumItems() == 0) return nullptr;
211 int num = RandomRange((uint16_t)Town::GetNumItems());
212 size_t index = std::numeric_limits<size_t>::max();
213
214 while (num >= 0) {
215 num--;
216 index++;
217
218 /* Make sure we have a valid town */
219 while (!Town::IsValidID(index)) {
220 index++;
221 assert(index < Town::GetPoolSize());
222 }
223 }
224
225 return Town::Get(index);
226}
227
228void Town::FillCachedName() const
229{
230 this->cached_name = GetTownName(this);
231}
232
238{
239 return (_price[Price::ClearHouse] * this->removal_cost) >> 8;
240}
241
242static bool TryBuildTownHouse(Town *t, TileIndex tile, TownExpandModes modes);
243static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout);
244
245static void TownDrawHouseLift(const TileInfo *ti)
246{
247 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
248}
249
250typedef void TownDrawTileProc(const TileInfo *ti);
251static TownDrawTileProc * const _town_draw_tile_procs[1] = {
252 TownDrawHouseLift
253};
254
256static void DrawTile_Town(TileInfo *ti)
257{
258 HouseID house_id = GetHouseType(ti->tile);
259
260 if (house_id >= NEW_HOUSE_OFFSET) {
261 /* Houses don't necessarily need new graphics. If they don't have a
262 * spritegroup associated with them, then the sprite for the substitute
263 * house id is drawn instead. */
264 if (HouseSpec::Get(house_id)->grf_prop.HasSpriteGroups()) {
265 DrawNewHouseTile(ti, house_id);
266 return;
267 } else {
268 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
269 }
270 }
271
272 /* Retrieve pointer to the draw town tile struct */
273 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
274
276
277 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
278
279 /* If houses are invisible, do not draw the upper part */
281
282 /* Add a house on top of the ground? */
283 SpriteID image = dcts->building.sprite;
284 if (image != 0) {
285 AddSortableSpriteToDraw(image, dcts->building.pal, *ti, *dcts, IsTransparencySet(TransparencyOption::Houses));
286
288 }
289
290 {
291 int proc = dcts->draw_proc - 1;
292
293 if (proc >= 0) _town_draw_tile_procs[proc](ti);
294 }
295}
296
299{
300 HouseID hid = GetHouseType(tile);
301
302 /* For NewGRF house tiles we might not be drawing a foundation. We need to
303 * account for this, as other structures should
304 * draw the wall of the foundation in this case.
305 */
306 if (hid >= NEW_HOUSE_OFFSET) {
307 const HouseSpec *hs = HouseSpec::Get(hid);
309 uint32_t callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
311 }
312 }
313 return FlatteningFoundation(tileh);
314}
315
323{
324 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
325 AnimateNewHouseTile(tile);
326 return;
327 }
328
329 if (TimerGameTick::counter & 3) return;
330
331 /* If the house is not one with a lift anymore, then stop this animating.
332 * Not exactly sure when this happens, but probably when a house changes.
333 * Before this was just a return...so it'd leak animated tiles..
334 * That bug seems to have been here since day 1?? */
335 if (!HouseSpec::Get(GetHouseType(tile))->building_flags.Test(BuildingFlag::IsAnimated)) {
336 DeleteAnimatedTile(tile);
337 return;
338 }
339
340 if (!LiftHasDestination(tile)) {
341 uint i;
342
343 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
344 * This is due to the fact that the first floor is, in the graphics,
345 * the height of 2 'normal' floors.
346 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
347 do {
348 i = RandomRange(7);
349 } while (i == 1 || i * 6 == GetLiftPosition(tile));
350
351 SetLiftDestination(tile, i);
352 }
353
354 int pos = GetLiftPosition(tile);
355 int dest = GetLiftDestination(tile) * 6;
356 pos += (pos < dest) ? 1 : -1;
357 SetLiftPosition(tile, pos);
358
359 if (pos == dest) {
360 HaltLift(tile);
361 DeleteAnimatedTile(tile);
362 }
363
365}
366
373static bool IsCloseToTown(TileIndex tile, uint dist)
374{
375 if (_town_kdtree.Count() == 0) return false;
376 Town *t = Town::Get(_town_kdtree.FindNearest(TileX(tile), TileY(tile)));
377 return DistanceManhattan(tile, t->xy) < dist;
378}
379
382{
383 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
384
385 if (this->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(this->index));
386
387 std::string town_string;
388 if (this->larger_town) {
389 town_string = GetString(_settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_CITY_POP : STR_VIEWPORT_TOWN_CITY, this->index, this->cache.population);
390 } else {
391 town_string = GetString(_settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_TOWN_NAME, this->index, this->cache.population);
392 }
393
394 this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_BASE,
395 town_string,
396 GetString(STR_TOWN_NAME, this->index, this->cache.population)
397);
398
399 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(this->index));
400
401 SetWindowDirty(WindowClass::TownView, this->index);
402}
403
406{
407 for (Town *t : Town::Iterate()) {
408 t->UpdateVirtCoord();
409 }
410}
411
414{
415 for (Town *t : Town::Iterate()) {
416 t->cached_name.clear();
417 }
418}
419
425static void ChangePopulation(Town *t, int mod)
426{
427 t->cache.population += mod;
428 if (_generating_town) [[unlikely]] return;
429
430 InvalidateWindowData(WindowClass::TownView, t->index); // Cargo requirements may appear/vanish for small populations
431 if (_settings_client.gui.population_in_label) t->UpdateVirtCoord();
432
433 InvalidateWindowData(WindowClass::TownDirectory, 0, TDIWD_POPULATION_CHANGE);
434}
435
441{
442 uint32_t pop = 0;
443 for (const Town *t : Town::Iterate()) pop += t->cache.population;
444 return pop;
445}
446
455{
456 for (StationList::iterator it = t->stations_near.begin(); it != t->stations_near.end(); /* incremented inside loop */) {
457 const Station *st = *it;
458
459 bool covers_area = st->TileIsInCatchment(tile);
460 if (flags.Any(BUILDING_2_TILES_Y)) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(0, 1));
461 if (flags.Any(BUILDING_2_TILES_X)) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 0));
462 if (flags.Any(BUILDING_HAS_4_TILES)) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 1));
463
464 if (covers_area && !st->CatchmentCoversTown(t->index)) {
465 it = t->stations_near.erase(it);
466 } else {
467 ++it;
468 }
469 }
470}
471
477{
478 assert(IsTileType(tile, TileType::House));
479
480 /* Progress in construction stages */
482 if (GetHouseConstructionTick(tile) != 0) return;
483
484 TriggerHouseAnimation_ConstructionStageChanged(tile, false);
485
486 if (IsHouseCompleted(tile)) {
487 /* Now that construction is complete, we can add the population of the
488 * building to the town. */
489 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
490 ResetHouseAge(tile);
491 }
493}
494
500{
502 if (flags.Any(BUILDING_HAS_1_TILE)) AdvanceSingleHouseConstruction(TileAddXY(tile, 0, 0));
503 if (flags.Any(BUILDING_2_TILES_Y)) AdvanceSingleHouseConstruction(TileAddXY(tile, 0, 1));
504 if (flags.Any(BUILDING_2_TILES_X)) AdvanceSingleHouseConstruction(TileAddXY(tile, 1, 0));
505 if (flags.Any(BUILDING_HAS_4_TILES)) AdvanceSingleHouseConstruction(TileAddXY(tile, 1, 1));
506}
507
516static void TownGenerateCargo(Town *t, CargoType cargo, uint amount, StationFinder &stations, bool affected_by_recession)
517{
518 if (amount == 0) return;
519
520 /* All production is halved during a recession (except for NewGRF-supplied town cargo). */
521 if (affected_by_recession && EconomyIsInRecession()) {
522 amount = (amount + 1) >> 1;
523 }
524
525 /* Scale by cargo scale setting. */
526 amount = ScaleByCargoScale(amount, true);
527 if (amount == 0) return;
528
529 /* Actually generate cargo and update town statistics. */
530 auto &supplied = t->GetOrCreateCargoSupplied(cargo);
531 supplied.history[THIS_MONTH].production += amount;
532 supplied.history[THIS_MONTH].transported += MoveGoodsToStation(cargo, amount, {t->index, SourceType::Town}, stations.GetStations());;
533}
534
542static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
543{
544 for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
545 uint32_t r = Random();
546 if (GB(r, 0, 8) < rate) {
547 CargoType cargo_type = cs->Index();
548 uint amt = (GB(r, 0, 8) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR) / 8 + 1;
549
550 TownGenerateCargo(t, cargo_type, amt, stations, true);
551 }
552 }
553}
554
562static void TownGenerateCargoBinomial(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
563{
564 for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
565 CargoType cargo_type = cs->Index();
566 uint32_t r = Random();
567
568 /* Make a bitmask with up to 32 bits set, one for each potential pax. */
569 int genmax = (rate + 7) / 8;
570 uint32_t genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
571
572 /* Mask random value by potential pax and count number of actual pax. */
573 uint amt = CountBits(r & genmask) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR;
574
575 TownGenerateCargo(t, cargo_type, amt, stations, true);
576 }
577}
578
580static void TileLoop_Town(TileIndex tile)
581{
582 HouseID house_id = GetHouseType(tile);
583
584 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
585 * doesn't exist any more, so don't continue here. */
586 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
587
588 if (!IsHouseCompleted(tile)) {
589 /* Construction is not completed, so we advance a construction stage. */
591 return;
592 }
593
594 const HouseSpec *hs = HouseSpec::Get(house_id);
595
596 /* If the lift has a destination, it is already an animated tile. */
598 house_id < NEW_HOUSE_OFFSET &&
599 !LiftHasDestination(tile) &&
600 Chance16(1, 2)) {
601 AddAnimatedTile(tile);
602 }
603
604 Town *t = Town::GetByTile(tile);
605 uint32_t r = Random();
606
607 StationFinder stations(TileArea(tile, 1, 1));
608
610 for (uint i = 0; i < 256; i++) {
611 uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
612
613 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
614
615 CargoType cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
616 if (!IsValidCargoType(cargo)) continue;
617
618 uint amt = GB(callback, 0, 8);
619 if (amt == 0) continue;
620
621 /* NewGRF-supplied town cargos are not affected by recessions. */
622 TownGenerateCargo(t, cargo, amt, stations, false);
623 }
624 } else {
625 switch (_settings_game.economy.town_cargogen_mode) {
627 /* Original (quadratic) cargo generation algorithm */
630 break;
631
633 /* Binomial distribution per tick, by a series of coin flips */
634 /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
635 * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
636 if (GB(TimerGameTick::counter, 8, 2) == GB(tile.base(), 0, 2)) {
639 }
640 break;
641
642 default:
643 NOT_REACHED();
644 }
645 }
646
648
649 if (hs->building_flags.Any(BUILDING_HAS_1_TILE) &&
651 CanDeleteHouse(tile) &&
652 GetHouseAge(tile) >= hs->minimum_life &&
653 --t->time_until_rebuild == 0) {
654 t->time_until_rebuild = GB(r, 16, 8) + 192;
655
656 ClearTownHouse(t, tile);
657
658 /* Rebuild with another house? */
659 if (GB(r, 24, 8) >= 12) {
660 /* If we are multi-tile houses, make sure to replace the house
661 * closest to city center. If we do not do this, houses tend to
662 * wander away from roads and other houses. */
663 if (hs->building_flags.Any(BUILDING_HAS_2_TILES)) {
664 /* House tiles are always the most north tile. Move the new
665 * house to the south if we are north of the city center. */
666 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
667 int x = Clamp(grid_pos.x, 0, 1);
668 int y = Clamp(grid_pos.y, 0, 1);
669
671 tile = TileAddXY(tile, x, y);
672 } else if (hs->building_flags.Test(BuildingFlag::Size1x2)) {
673 tile = TileAddXY(tile, 0, y);
674 } else if (hs->building_flags.Test(BuildingFlag::Size2x1)) {
675 tile = TileAddXY(tile, x, 0);
676 }
677 }
678
680 if (_settings_game.economy.allow_town_roads) modes.Set(TownExpandMode::Roads);
681
682 TryBuildTownHouse(t, tile, modes);
683 }
684 }
685}
686
689{
690 if (flags.Test(DoCommandFlag::Auto)) return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
691 if (!CanDeleteHouse(tile)) return CommandCost(STR_ERROR_BUILDING_IS_PROTECTED);
692
693 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
694
696 cost.AddCost(hs->GetRemovalCost());
697
698 int rating = hs->remove_rating_decrease;
699 Town *t = Town::GetByTile(tile);
700
702 if (!_cheats.magic_bulldozer.value && !flags.Test(DoCommandFlag::NoTestTownRating)) {
703 /* NewGRFs can add indestructible houses. */
704 if (rating > RATING_MAXIMUM) {
705 return CommandCost(STR_ERROR_BUILDING_IS_PROTECTED);
706 }
707 /* If town authority controls removal, check the company's rating. */
708 if (rating > t->ratings[_current_company] && _settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
709 return CommandCostWithParam(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS, t->index);
710 }
711 }
712 }
713
714 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
715 if (flags.Test(DoCommandFlag::Execute)) {
716 ClearTownHouse(t, tile);
717 }
718
719 return cost;
720}
721
723static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
724{
725 HouseID house_id = GetHouseType(tile);
726 const HouseSpec *hs = HouseSpec::Get(house_id);
727 Town *t = Town::GetByTile(tile);
728
730 for (uint i = 0; i < 256; i++) {
731 uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
732
733 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
734
735 CargoType cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
736
737 if (!IsValidCargoType(cargo)) continue;
738 produced[cargo]++;
739 }
740 } else {
741 if (hs->population > 0) {
743 produced[cs->Index()]++;
744 }
745 }
746 if (hs->mail_generation > 0) {
748 produced[cs->Index()]++;
749 }
750 }
751 }
752}
753
761static void AddAcceptedCargoSetMask(CargoType cargo, uint amount, CargoArray &acceptance, CargoTypes &always_accepted)
762{
763 if (!IsValidCargoType(cargo) || amount == 0) return;
764 acceptance[cargo] += amount;
765 always_accepted.Set(cargo);
766}
767
777void AddAcceptedCargoOfHouse(TileIndex tile, HouseID house, const HouseSpec *hs, Town *t, CargoArray &acceptance, CargoTypes &always_accepted)
778{
779 CargoType accepts[lengthof(hs->accepts_cargo)];
780
781 /* Set the initial accepted cargo types */
782 for (uint8_t i = 0; i < lengthof(accepts); i++) {
783 accepts[i] = hs->accepts_cargo[i];
784 }
785
786 /* Check for custom accepted cargo types */
788 uint16_t callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, house, t, tile, {}, tile == INVALID_TILE);
789 if (callback != CALLBACK_FAILED) {
790 /* Replace accepted cargo types with translated values from callback */
791 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
792 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
793 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
794 }
795 }
796
797 /* Check for custom cargo acceptance */
799 uint16_t callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, house, t, tile, {}, tile == INVALID_TILE);
800 if (callback != CALLBACK_FAILED) {
801 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
802 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
803 if (_settings_game.game_creation.landscape != LandscapeType::Temperate && HasBit(callback, 12)) {
804 /* The 'S' bit indicates food instead of goods */
805 AddAcceptedCargoSetMask(GetCargoTypeByLabel(CT_FOOD), GB(callback, 8, 4), acceptance, always_accepted);
806 } else {
807 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
808 }
809 return;
810 }
811 }
812
813 /* No custom acceptance, so fill in with the default values */
814 for (uint8_t i = 0; i < lengthof(accepts); i++) {
815 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
816 }
817}
818
820static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes &always_accepted)
821{
822 HouseID house = GetHouseType(tile);
823 AddAcceptedCargoOfHouse(tile, house, HouseSpec::Get(house), Town::GetByTile(tile), acceptance, always_accepted);
824}
825
832{
833 CargoTypes always_accepted{};
834 CargoArray acceptance{};
835 AddAcceptedCargoOfHouse(INVALID_TILE, hs->Index(), hs, nullptr, acceptance, always_accepted);
836 return acceptance;
837}
838
840static void GetTileDesc_Town(TileIndex tile, TileDesc &td)
841{
842 const HouseID house = GetHouseType(tile);
843 const HouseSpec *hs = HouseSpec::Get(house);
844 bool house_completed = IsHouseCompleted(tile);
845
846 td.str = hs->building_name;
847
848 /* Show if a player has protected the house, or if the house property is set for protection.
849 * Note that houses also have a callback which overrides their property (player choice is always respected),
850 * but it's impossible to know the possible results of the callback in runtime so it's not evaluated here. */
852
853 std::array<int32_t, 1> regs100;
854 uint16_t callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile, regs100);
855 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
856 StringID new_name = STR_NULL;
857 if (callback_res == 0x40F) {
858 new_name = GetGRFStringID(hs->grf_prop.grfid, static_cast<GRFStringID>(regs100[0]));
859 } else if (callback_res > 0x400) {
861 } else {
862 new_name = GetGRFStringID(hs->grf_prop.grfid, GRFSTR_MISC_GRF_TEXT + callback_res);
863 }
864 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
865 td.str = new_name;
866 }
867 }
868
869 if (!house_completed) {
870 td.dparam = td.str.base();
871 td.str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
872 }
873
874 if (hs->grf_prop.HasGrfFile()) {
875 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grfid);
876 td.grf = gc->GetName();
877 }
878
879 td.owner[0] = OWNER_TOWN;
880}
881
882static bool GrowTown(Town *t, TownExpandModes modes);
883
888static void TownTickHandler(Town *t)
889{
892 if (_settings_game.economy.allow_town_roads) modes.Set(TownExpandMode::Roads);
893 int i = (int)t->grow_counter - 1;
894 if (i < 0) {
895 if (GrowTown(t, modes)) {
896 i = t->growth_rate;
897 } else {
898 /* If growth failed wait a bit before retrying */
899 i = std::min<uint16_t>(t->growth_rate, Ticks::TOWN_GROWTH_TICKS - 1);
900 }
901 }
902 t->grow_counter = i;
903 }
904}
905
908{
909 if (_game_mode == GameMode::Editor) return;
910
911 for (Town *t : Town::Iterate()) {
913 }
914}
915
922{
923 if (IsRoadDepotTile(tile) || IsBayRoadStopTile(tile)) return {};
924
925 return GetAnyRoadBits(tile, RoadTramType::Road, true);
926}
927
934{
935 RoadType best_rt = ROADTYPE_ROAD;
936 const RoadTypeInfo *best = nullptr;
937 const uint16_t assume_max_speed = 50;
938
940 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
941
942 /* Can town build this road. */
943 if (!rti->flags.Test(RoadTypeFlag::TownBuild)) continue;
944
945 /* Not yet introduced at this date. */
947
948 if (best != nullptr) {
949 if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue;
950 }
951
952 best_rt = rt;
953 best = rti;
954 }
955
956 return best_rt;
957}
958
964{
965 const RoadTypeInfo *best = nullptr;
967 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
968
969 if (!rti->flags.Test(RoadTypeFlag::TownBuild)) continue; // Town can't build this road type.
970
971 if (best != nullptr && rti->introduction_date >= best->introduction_date) continue;
972 best = rti;
973 }
974
975 if (best == nullptr) return TimerGameCalendar::Date(INT32_MAX);
976 return best->introduction_date;
977}
978
984{
985 auto min_date = GetTownRoadTypeFirstIntroductionDate();
986 if (min_date <= TimerGameCalendar::date) return true;
987
988 if (min_date < INT32_MAX) {
990 GetEncodedString(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET),
991 GetEncodedString(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET_EXPLANATION, min_date),
993 } else {
995 GetEncodedString(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL),
996 GetEncodedString(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL_EXPLANATION), WarningLevel::Critical);
997 }
998 return false;
999}
1000
1011static bool IsNeighbourRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
1012{
1013 if (!IsValidTile(tile)) return false;
1014
1015 /* Lookup table for the used diff values */
1016 const TileIndexDiff tid_lt[3] = {
1020 };
1021
1022 dist_multi = (dist_multi + 1) * 4;
1023 for (uint pos = 4; pos < dist_multi; pos++) {
1024 /* Go (pos / 4) tiles to the left or the right */
1025 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
1026
1027 /* Use the current tile as origin, or go one tile backwards */
1028 if (pos & 2) cur += tid_lt[2];
1029
1030 /* Test for roadbit parallel to dir and facing towards the middle axis */
1031 if (IsValidTile(tile + cur) &&
1032 GetTownRoadBits(TileAdd(tile, cur)).Any(DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir)))) return true;
1033 }
1034 return false;
1035}
1036
1046{
1047 if (DistanceFromEdge(tile) == 0) return false;
1048
1049 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
1050 if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
1051
1052 /* Check if there already is a road at this point? */
1053 if (GetTownRoadBits(tile).None()) {
1054 /* No, try if we are able to build a road piece there.
1055 * If that fails clear the land, and if that fails exit.
1056 * This is to make sure that we can build a road here later. */
1058 if (Command<Commands::BuildRoad>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater}, tile, (dir == DiagDirection::NW || dir == DiagDirection::SE) ? ROAD_Y : ROAD_X, rt, {}, t->index).Failed() &&
1059 Command<Commands::LandscapeClear>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater}, tile).Failed()) {
1060 return false;
1061 }
1062 }
1063
1064 Slope cur_slope = _settings_game.construction.build_on_slopes ? std::get<Slope>(GetFoundationSlope(tile)) : GetTileSlope(tile);
1065 bool ret = !IsNeighbourRoadTile(tile, dir, t->layout == TownLayout::Original ? 1 : 2);
1066 if (cur_slope == SLOPE_FLAT) return ret;
1067
1068 /* If the tile is not a slope in the right direction, then
1069 * maybe terraform some. */
1070 Slope desired_slope = (dir == DiagDirection::NW || dir == DiagDirection::SE) ? SLOPE_NW : SLOPE_NE;
1071 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
1072 if (Chance16(1, 8)) {
1073 CommandCost res = CMD_ERROR;
1074 if (!_generating_world && Chance16(1, 10)) {
1075 res = ExtractCommandCost(Command<Commands::TerraformLand>::Do({DoCommandFlag::Execute, DoCommandFlag::Auto, DoCommandFlag::NoWater},
1076 tile, Chance16(1, 16) ? cur_slope : ComplementSlope(RemoveSteepSlope(RemoveHalftileSlope(cur_slope))), false));
1077 }
1078 if (res.Failed() && Chance16(1, 3)) {
1079 /* We can consider building on the slope, though. */
1080 return ret;
1081 }
1082 }
1083 return false;
1084 }
1085 return ret;
1086}
1087
1088static bool TerraformTownTile(TileIndex tile, Slope edges, bool dir)
1089{
1090 assert(tile < Map::Size());
1091
1092 CommandCost r = ExtractCommandCost(Command<Commands::TerraformLand>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater}, tile, edges, dir));
1093 if (r.Failed() || r.GetCost() >= (_price[Price::Terraform] + 2) * 8) return false;
1094 Command<Commands::TerraformLand>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater, DoCommandFlag::Execute}, tile, edges, dir);
1095 return true;
1096}
1097
1098static void LevelTownLand(TileIndex tile)
1099{
1100 assert(tile < Map::Size());
1101
1102 /* Don't terraform if land is plain or if there's a house there. */
1103 if (IsTileType(tile, TileType::House)) return;
1104 Slope tileh = GetTileSlope(tile);
1105 if (tileh == SLOPE_FLAT) return;
1106
1107 /* First try up, then down */
1108 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, true)) {
1109 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, false);
1110 }
1111}
1112
1122{
1123 /* align the grid to the downtown */
1124 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1125 RoadBits rcmd{};
1126
1127 switch (t->layout) {
1128 default: NOT_REACHED();
1129
1131 if ((grid_pos.x % 3) == 0) rcmd.Set(ROAD_Y);
1132 if ((grid_pos.y % 3) == 0) rcmd.Set(ROAD_X);
1133 break;
1134
1136 if ((grid_pos.x % 4) == 0) rcmd.Set(ROAD_Y);
1137 if ((grid_pos.y % 4) == 0) rcmd.Set(ROAD_X);
1138 break;
1139 }
1140
1141 /* Optimise only X-junctions */
1142 if (rcmd != ROAD_ALL) return rcmd;
1143
1144 RoadBits rb_template;
1145
1146 switch (GetTileSlope(tile)) {
1147 default: rb_template = ROAD_ALL; break;
1148 case SLOPE_W: rb_template = {RoadBit::NW, RoadBit::SW}; break;
1149 case SLOPE_SW: rb_template = ROAD_Y | RoadBit::SW; break;
1150 case SLOPE_S: rb_template = {RoadBit::SW, RoadBit::SE}; break;
1151 case SLOPE_SE: rb_template = ROAD_X | RoadBit::SE; break;
1152 case SLOPE_E: rb_template = {RoadBit::SE, RoadBit::NE}; break;
1153 case SLOPE_NE: rb_template = ROAD_Y | RoadBit::NE; break;
1154 case SLOPE_N: rb_template = {RoadBit::NE, RoadBit::NW}; break;
1155 case SLOPE_NW: rb_template = ROAD_X | RoadBit::NW; break;
1156 case SLOPE_STEEP_W:
1157 case SLOPE_STEEP_S:
1158 case SLOPE_STEEP_E:
1159 case SLOPE_STEEP_N:
1160 rb_template = {};
1161 break;
1162 }
1163
1164 /* Stop if the template is compatible to the growth dir */
1165 if (DiagDirToRoadBits(ReverseDiagDir(dir)).Any(rb_template)) return rb_template;
1166 /* If not generate a straight road in the direction of the growth */
1168}
1169
1182{
1183 /* We can't look further than that. */
1184 if (DistanceFromEdge(tile) == 0) return false;
1185
1186 uint counter = 0; // counts the house neighbour tiles
1187
1188 /* Check the tiles E,N,W and S of the current tile for houses */
1190 /* Count both void and house tiles for checking whether there
1191 * are enough houses in the area. This to make it likely that
1192 * houses get build up to the edge of the map. */
1193 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1194 case TileType::House:
1195 case TileType::Void:
1196 counter++;
1197 break;
1198
1199 default:
1200 break;
1201 }
1202
1203 /* If there are enough neighbours stop here */
1204 if (counter >= 3) {
1205 return TryBuildTownHouse(t, tile, modes);
1206 }
1207 }
1208 return false;
1209}
1210
1219static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1220{
1222 return Command<Commands::BuildRoad>::Do({DoCommandFlag::Execute, DoCommandFlag::Auto, DoCommandFlag::NoWater}, tile, rcmd, rt, {}, t->index).Succeeded();
1223}
1224
1234static bool CanRoadContinueIntoNextTile(const Town *t, const TileIndex tile, const DiagDirection road_dir)
1235{
1236 const TileIndexDiff delta = TileOffsByDiagDir(road_dir); // +1 tile in the direction of the road
1237 TileIndex next_tile = tile + delta; // The tile beyond which must be connectable to the target tile
1238 RoadBits rcmd = DiagDirToRoadBits(ReverseDiagDir(road_dir));
1240
1241 /* Before we try anything, make sure the tile is on the map and not the void. */
1242 if (!IsValidTile(next_tile)) return false;
1243
1244 /* If the next tile is a bridge or tunnel, allow if it's continuing in the same direction. */
1245 if (IsTileType(next_tile, TileType::TunnelBridge)) {
1246 return GetTunnelBridgeTransportType(next_tile) == TransportType::Road && GetTunnelBridgeDirection(next_tile) == road_dir;
1247 }
1248
1249 /* If the next tile is a station, allow if it's a road station facing the proper direction. Otherwise return false. */
1250 if (IsTileType(next_tile, TileType::Station)) {
1251 /* If the next tile is a road station, allow if it can be entered by the new tunnel/bridge, otherwise disallow. */
1252 if (IsDriveThroughStopTile(next_tile)) return GetDriveThroughStopAxis(next_tile) == DiagDirToAxis(road_dir);
1253 if (IsBayRoadStopTile(next_tile)) return GetBayRoadStopDir(next_tile) == ReverseDiagDir(road_dir);
1254 return false;
1255 }
1256
1257 /* If the next tile is a road depot, allow if it's facing the right way. */
1258 if (IsTileType(next_tile, TileType::Road)) {
1259 return IsRoadDepot(next_tile) && GetRoadDepotDirection(next_tile) == ReverseDiagDir(road_dir);
1260 }
1261
1262 /* If the next tile is a railroad track, check if towns are allowed to build level crossings.
1263 * If level crossing are not allowed, reject the construction. Else allow DoCommand to determine if the rail track is buildable. */
1264 if (IsTileType(next_tile, TileType::Railway) && !_settings_game.economy.allow_town_level_crossings) return false;
1265
1266 /* If a road tile can be built, the construction is allowed. */
1267 return Command<Commands::BuildRoad>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater}, next_tile, rcmd, rt, {}, t->index).Succeeded();
1268}
1269
1280static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1281{
1282 assert(bridge_dir < DiagDirection::End);
1283
1284 const Slope slope = GetTileSlope(tile);
1285
1286 /* Make sure the direction is compatible with the slope.
1287 * Well we check if the slope has an up bit set in the
1288 * reverse direction. */
1289 if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1290
1291 /* Assure that the bridge is connectable to the start side */
1292 if (!GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))).Any(DiagDirToRoadBits(bridge_dir))) return false;
1293
1294 /* We are in the right direction */
1295 uint bridge_length = 0; // This value stores the length of the possible bridge
1296 TileIndex bridge_tile = tile; // Used to store the other waterside
1297
1298 const TileIndexDiff delta = TileOffsByDiagDir(bridge_dir);
1299
1300 /* To prevent really small towns from building disproportionately
1301 * long bridges, make the max a function of its population. */
1302 const uint TOWN_BRIDGE_LENGTH_CAP = 11;
1303 uint base_bridge_length = 5;
1304 uint max_bridge_length = std::min(t->cache.population / 1000 + base_bridge_length, TOWN_BRIDGE_LENGTH_CAP);
1305
1306 if (slope == SLOPE_FLAT) {
1307 /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1308 do {
1309 if (bridge_length++ >= base_bridge_length) {
1310 /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1311 return false;
1312 }
1313 bridge_tile += delta;
1314 } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile).Any())));
1315 } else {
1316 do {
1317 if (bridge_length++ >= max_bridge_length) {
1318 /* Ensure the bridge is not longer than the max allowed length. */
1319 return false;
1320 }
1321 bridge_tile += delta;
1322 } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile).Any())));
1323 }
1324
1325 /* Don't allow a bridge where the start and end tiles are adjacent with no span between. */
1326 if (bridge_length == 1) return false;
1327
1328 /* Make sure the road can be continued past the bridge. At this point, bridge_tile holds the end tile of the bridge. */
1329 if (!CanRoadContinueIntoNextTile(t, bridge_tile, bridge_dir)) return false;
1330
1331 /* If another parallel bridge exists nearby, this one would be redundant and shouldn't be built. We don't care about flat bridges. */
1332 if (slope != SLOPE_FLAT) {
1333 for (auto search : SpiralTileSequence(tile, bridge_length, 0, 0)) {
1334 /* Only consider bridge head tiles. */
1335 if (!IsBridgeTile(search)) continue;
1336
1337 /* Only consider road bridges. */
1338 if (GetTunnelBridgeTransportType(search) != TransportType::Road) continue;
1339
1340 /* If the bridge is facing the same direction as the proposed bridge, we've found a redundant bridge. */
1341 if (GetTileSlope(search) & InclinedSlope(ReverseDiagDir(bridge_dir))) return false;
1342 }
1343 }
1344
1346 for (uint8_t times = 0; times <= 22; times++) {
1347 uint8_t bridge_type = RandomRange(MAX_BRIDGES - 1);
1348
1349 /* Can we actually build the bridge? */
1350 if (Command<Commands::BuildBridge>::Do(CommandFlagsToDCFlags(GetCommandFlags<Commands::BuildBridge>()), tile, bridge_tile, TransportType::Road, bridge_type, INVALID_RAILTYPE, rt).Succeeded()) {
1351 Command<Commands::BuildBridge>::Do(CommandFlagsToDCFlags(GetCommandFlags<Commands::BuildBridge>()).Set(DoCommandFlag::Execute), tile, bridge_tile, TransportType::Road, bridge_type, INVALID_RAILTYPE, rt);
1352 return true;
1353 }
1354 }
1355 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1356 return false;
1357}
1358
1369static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
1370{
1371 assert(tunnel_dir < DiagDirection::End);
1372
1373 Slope slope = GetTileSlope(tile);
1374
1375 /* Only consider building a tunnel if the starting tile is sloped properly. */
1376 if (slope != InclinedSlope(tunnel_dir)) return false;
1377
1378 /* Assure that the tunnel is connectable to the start side */
1379 if (!GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(tunnel_dir))).Any(DiagDirToRoadBits(tunnel_dir))) return false;
1380
1381 const TileIndexDiff delta = TileOffsByDiagDir(tunnel_dir);
1382 int max_tunnel_length = 0;
1383
1384 /* There are two conditions for building tunnels: Under a mountain and under an obstruction. */
1385 if (CanRoadContinueIntoNextTile(t, tile, tunnel_dir)) {
1386 /* Only tunnel under a mountain if the slope is continuous for at least 4 tiles. We want tunneling to be a last resort for large hills. */
1387 TileIndex slope_tile = tile;
1388 for (uint8_t tiles = 0; tiles < 4; tiles++) {
1389 if (!IsValidTile(slope_tile)) return false;
1390 slope = GetTileSlope(slope_tile);
1391 if (slope != InclinedSlope(tunnel_dir) && !IsSteepSlope(slope) && !IsSlopeWithOneCornerRaised(slope)) return false;
1392 slope_tile += delta;
1393 }
1394
1395 /* More population means longer tunnels, but make sure we can at least cover the smallest mountain which necessitates tunneling. */
1396 max_tunnel_length = (t->cache.population / 1000) + 7;
1397 } else {
1398 /* When tunneling under an obstruction, the length limit is 5, enough to tunnel under a four-track railway. */
1399 max_tunnel_length = 5;
1400 }
1401
1402 uint8_t tunnel_length = 0;
1403 TileIndex tunnel_tile = tile; // Iterator to store the other end tile of the tunnel.
1404
1405 /* Find the end tile of the tunnel for length and continuation checks. */
1406 do {
1407 if (tunnel_length++ >= max_tunnel_length) return false;
1408 tunnel_tile += delta;
1409 /* The tunnel ends when start and end tiles are the same height. */
1410 } while (IsValidTile(tunnel_tile) && GetTileZ(tile) != GetTileZ(tunnel_tile));
1411
1412 /* Don't allow a tunnel where the start and end tiles are adjacent. */
1413 if (tunnel_length == 1) return false;
1414
1415 /* Make sure the road can be continued past the tunnel. At this point, tunnel_tile holds the end tile of the tunnel. */
1416 if (!CanRoadContinueIntoNextTile(t, tunnel_tile, tunnel_dir)) return false;
1417
1418 /* Attempt to build the tunnel. Return false if it fails to let the town build a road instead. */
1420 if (Command<Commands::BuildTunnel>::Do(CommandFlagsToDCFlags(GetCommandFlags<Commands::BuildTunnel>()), tile, TransportType::Road, INVALID_RAILTYPE, rt).Succeeded()) {
1422 return true;
1423 }
1424
1425 return false;
1426}
1427
1435{
1436 static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1437 bool allow = false;
1438
1439 for (const auto &ptr : tiles) {
1440 TileIndex cur_tile = t + ToTileIndexDiff(ptr);
1441 if (!IsValidTile(cur_tile)) continue;
1442
1443 if (!(IsTileType(cur_tile, TileType::Road) || IsAnyRoadStopTile(cur_tile))) continue;
1444 allow = true;
1445
1446 RoadType road_rt = GetRoadTypeRoad(cur_tile);
1447 if (road_rt != INVALID_ROADTYPE && !GetRoadTypeInfo(road_rt)->flags.Test(RoadTypeFlag::NoHouses)) return true;
1448 }
1449
1450 /* If no road was found surrounding the tile we can allow building the house since there is
1451 * nothing which forbids it, if a road was found but the execution reached this point, then
1452 * all the found roads don't allow houses to be built */
1453 return !allow;
1454}
1455
1461{
1462 if (!IsTileType(tile, TileType::Road)) return true;
1463
1464 /* Allow extending on roadtypes which can be built by town, or if the road type matches the type the town will build. */
1465 RoadType rt = GetRoadTypeRoad(tile);
1467}
1468
1475{
1476 return modes.Test(TownExpandMode::Roads);
1477}
1478
1485
1505static TownGrowthResult GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1, TownExpandModes modes)
1506{
1507 RoadBits rcmd{}; // RoadBits for the road construction command
1508 TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1509
1510 assert(tile < Map::Size());
1511
1512 if (cur_rb.None()) {
1513 /* Tile has no road.
1514 * We will return TownGrowthResult::SearchStopped to say that this is the last iteration. */
1515
1517 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, TileType::Railway)) return TownGrowthResult::SearchStopped;
1518
1519 /* Remove hills etc */
1520 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1521
1522 /* Is a road allowed here? */
1523 switch (t1->layout) {
1524 default: NOT_REACHED();
1525
1528 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1529 if (rcmd.None()) return TownGrowthResult::SearchStopped;
1530 break;
1531
1534 if (!IsRoadAllowedHere(t1, tile, target_dir)) return TownGrowthResult::SearchStopped;
1535
1536 DiagDirection source_dir = ReverseDiagDir(target_dir);
1537
1538 if (Chance16(1, 4)) {
1539 /* Randomize a new target dir */
1540 do target_dir = RandomRange(DiagDirection::End); while (target_dir == source_dir);
1541 }
1542
1543 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1544 /* A road is not allowed to continue the randomized road,
1545 * return if the road we're trying to build is curved. */
1546 if (target_dir != ReverseDiagDir(source_dir)) return TownGrowthResult::SearchStopped;
1547
1548 /* Return if neither side of the new road is a house */
1552 }
1553
1554 /* That means that the road is only allowed if there is a house
1555 * at any side of the new road. */
1556 }
1557
1558 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1559 break;
1560 }
1561
1562 } else if (target_dir < DiagDirection::End && !cur_rb.Any(DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1564
1566
1567 /* Continue building on a partial road.
1568 * Should be always OK, so we only generate
1569 * the fitting RoadBits */
1570 switch (t1->layout) {
1571 default: NOT_REACHED();
1572
1575 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1576 break;
1577
1580 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1581 break;
1582 }
1583 } else {
1584 bool allow_house = true; // Value which decides if we want to construct a house
1585
1586 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1587 * it is the starting tile. Half the time, we stay on this side then.*/
1589 if (GetTunnelBridgeTransportType(tile) == TransportType::Road && (target_dir != DiagDirection::End || Chance16(1, 2))) {
1590 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1591 }
1593 }
1594
1595 /* Possibly extend the road in a direction.
1596 * Randomize a direction and if it has a road, bail out. */
1597 target_dir = RandomRange(DiagDirection::End);
1598 RoadBits target_rb = DiagDirToRoadBits(target_dir);
1599 TileIndex house_tile; // position of a possible house
1600
1601 if (cur_rb.Any(target_rb)) {
1602 /* If it's a road turn possibly build a house in a corner.
1603 * Use intersection with straight road as an indicator
1604 * that we randomised corner house position.
1605 * A turn (and we check for that later) always has only
1606 * one common bit with a straight road so it has the same
1607 * chance to be chosen as the house on the side of a road.
1608 */
1609 if ((cur_rb & ROAD_X) != target_rb) return TownGrowthResult::Continue;
1610
1611 /* Check whether it is a turn and if so determine
1612 * position of the corner tile */
1613 switch (cur_rb.base()) {
1614 case ROAD_N.base():
1615 house_tile = TileAddByDir(tile, Direction::S);
1616 break;
1617 case ROAD_S.base():
1618 house_tile = TileAddByDir(tile, Direction::N);
1619 break;
1620 case ROAD_E.base():
1621 house_tile = TileAddByDir(tile, Direction::W);
1622 break;
1623 case ROAD_W.base():
1624 house_tile = TileAddByDir(tile, Direction::E);
1625 break;
1626 default:
1627 return TownGrowthResult::Continue; // not a turn
1628 }
1629 target_dir = DiagDirection::End;
1630 } else {
1631 house_tile = TileAddByDiagDir(tile, target_dir);
1632 }
1633
1634 /* Don't walk into water. */
1635 if (HasTileWaterGround(house_tile)) return TownGrowthResult::Continue;
1636
1637 if (!IsValidTile(house_tile)) return TownGrowthResult::Continue;
1638
1640
1641 if (target_dir != DiagDirection::End && TownAllowedToBuildRoads(modes)) {
1642 switch (t1->layout) {
1643 default: NOT_REACHED();
1644
1645 case TownLayout::Grid3x3: // Use 2x2 grid afterwards!
1646 if (GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir), modes)) {
1648 }
1649 [[fallthrough]];
1650
1652 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1653 allow_house = !rcmd.Any(target_rb);
1654 break;
1655
1656 case TownLayout::BetterRoads: // Use original afterwards!
1657 if (GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir), modes)) {
1659 }
1660 [[fallthrough]];
1661
1663 /* Allow a house at the edge. 60% chance or
1664 * always ok if no road allowed. */
1665 rcmd = target_rb;
1666 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1667 break;
1668 }
1669 }
1670
1671 allow_house &= RoadTypesAllowHouseHere(house_tile);
1672
1673 if (allow_house) {
1674 /* Build a house, but not if there already is a house there. */
1675 if (!IsTileType(house_tile, TileType::House)) {
1676 /* Level the land if possible */
1677 if (Chance16(1, 6)) LevelTownLand(house_tile);
1678
1679 /* And build a house.
1680 * Set result to -1 if we managed to build it. */
1681 if (TryBuildTownHouse(t1, house_tile, modes)) {
1683 }
1684 }
1685 return result;
1686 }
1687
1688 if (!TownCanGrowRoad(tile)) return result;
1689 }
1690
1691 /* Return if a water tile */
1693
1694 /* Make the roads look nicer */
1695 rcmd = CleanUpRoadBits(tile, rcmd);
1696 if (rcmd.None()) return TownGrowthResult::SearchStopped;
1697
1698 /* Only use the target direction for bridges and tunnels to ensure they're connected.
1699 * The target_dir is as computed previously according to town layout, so
1700 * it will match it perfectly. */
1701 if (GrowTownWithBridge(t1, tile, target_dir)) {
1703 }
1704 if (GrowTownWithTunnel(t1, tile, target_dir)) {
1706 }
1707
1708 if (GrowTownWithRoad(t1, tile, rcmd)) {
1710 }
1712}
1713
1723{
1724 TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1725 if (!IsValidTile(target_tile)) return false;
1726 if (HasTileWaterGround(target_tile)) return false;
1727
1728 RoadBits target_rb = GetTownRoadBits(target_tile);
1729 if (TownAllowedToBuildRoads(modes)) {
1730 /* Check whether a road connection exists or can be build. */
1731 switch (GetTileType(target_tile)) {
1732 case TileType::Road:
1733 return target_rb.Any();
1734
1735 case TileType::Station:
1736 return IsDriveThroughStopTile(target_tile);
1737
1740
1741 case TileType::House:
1742 case TileType::Industry:
1743 case TileType::Object:
1744 return false;
1745
1746 default:
1747 /* Checked for void and water earlier */
1748 return true;
1749 }
1750 } else {
1751 /* Check whether a road connection already exists,
1752 * and it leads somewhere else. */
1754 return target_rb.Any(back_rb) && target_rb.Reset(back_rb).Any();
1755 }
1756}
1757
1765static bool GrowTownAtRoad(Town *t, TileIndex tile, TownExpandModes modes)
1766{
1767 /* Special case.
1768 * @see GrowTownInTile Check the else if
1769 */
1770 DiagDirection target_dir = DiagDirection::End; // The direction in which we want to extend the town
1771
1772 assert(tile < Map::Size());
1773
1774 /* Number of times to search.
1775 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1776 * them a little handicap. */
1777 int iterations;
1778 switch (t->layout) {
1780 iterations = 10 + t->cache.num_houses * 2 / 9;
1781 break;
1782
1785 iterations = 10 + t->cache.num_houses * 1 / 9;
1786 break;
1787
1788 default:
1789 iterations = 10 + t->cache.num_houses * 4 / 9;
1790 break;
1791 }
1792
1793 do {
1794 RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1795
1796 /* Try to grow the town from this point */
1797 switch (GrowTownInTile(&tile, cur_rb, target_dir, t, modes)) {
1799 return true;
1801 iterations = 0;
1802 break;
1803 default:
1804 break;
1805 };
1806
1807 /* Exclude the source position from the bitmask
1808 * and return if no more road blocks available */
1809 if (IsValidDiagDirection(target_dir)) cur_rb.Reset(DiagDirToRoadBits(ReverseDiagDir(target_dir)));
1810 if (cur_rb.None()) return false;
1811
1813 /* Only build in the direction away from the tunnel or bridge. */
1814 target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1815 } else {
1816 /* Select a random bit from the blockmask, walk a step
1817 * and continue the search from there. */
1818 do {
1819 if (cur_rb.None()) return false;
1820 RoadBits target_bits;
1821 do {
1822 target_dir = RandomRange(DiagDirection::End);
1823 target_bits = DiagDirToRoadBits(target_dir);
1824 } while (!cur_rb.Any(target_bits));
1825 cur_rb.Reset(target_bits);
1826 } while (!CanFollowRoad(tile, target_dir, modes));
1827 }
1828 tile = TileAddByDiagDir(tile, target_dir);
1829
1831 /* Don't allow building over roads of other cities */
1832 if (IsRoadOwner(tile, RoadTramType::Road, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1833 return false;
1834 } else if (IsRoadOwner(tile, RoadTramType::Road, OWNER_NONE) && _game_mode == GameMode::Editor) {
1835 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1836 * owner :) (happy happy happy road now) */
1838 SetTownIndex(tile, t->index);
1839 }
1840 }
1841
1842 /* Max number of times is checked. */
1843 } while (--iterations >= 0);
1844
1845 return false;
1846}
1847
1856{
1857 uint32_t r = Random();
1858 uint a = GB(r, 0, 2);
1859 uint b = GB(r, 8, 2);
1860 if (a == b) b ^= 2;
1861 return static_cast<RoadBits>((RoadBits{RoadBit::NW}.base() << a) + (RoadBits{RoadBit::NW}.base() << b));
1862}
1863
1870static bool GrowTown(Town *t, TownExpandModes modes)
1871{
1872 static const TileIndexDiffC _town_coord_mod[] = {
1873 {-1, 0},
1874 { 1, 1},
1875 { 1, -1},
1876 {-1, -1},
1877 {-1, 0},
1878 { 0, 2},
1879 { 2, 0},
1880 { 0, -2},
1881 {-1, -1},
1882 {-2, 2},
1883 { 2, 2},
1884 { 2, -2},
1885 { 0, 0}
1886 };
1887
1888 /* Current "company" is a town */
1890
1891 TileIndex tile = t->xy; // The tile we are working with ATM
1892
1893 /* Find a road that we can base the construction on. */
1894 for (const auto &ptr : _town_coord_mod) {
1895 if (GetTownRoadBits(tile).Any()) {
1896 bool success = GrowTownAtRoad(t, tile, modes);
1897 return success;
1898 }
1899 tile = TileAdd(tile, ToTileIndexDiff(ptr));
1900 }
1901
1902 /* No road available, try to build a random road block by
1903 * clearing some land and then building a road there. */
1904 if (TownAllowedToBuildRoads(modes)) {
1905 tile = t->xy;
1906 for (const auto &ptr : _town_coord_mod) {
1907 /* Only work with plain land that not already has a house */
1908 if (!IsTileType(tile, TileType::House) && IsTileFlat(tile)) {
1909 if (Command<Commands::LandscapeClear>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater}, tile).Succeeded()) {
1911 Command<Commands::BuildRoad>::Do({DoCommandFlag::Execute, DoCommandFlag::Auto}, tile, GenRandomRoadBits(), rt, {}, t->index);
1912 return true;
1913 }
1914 }
1915 tile = TileAdd(tile, ToTileIndexDiff(ptr));
1916 }
1917 }
1918
1919 return false;
1920}
1921
1927{
1928 static const std::array<std::array<uint32_t, NUM_HOUSE_ZONES>, 23> _town_squared_town_zone_radius_data = {{
1929 { 4, 0, 0, 0, 0}, // 0
1930 { 16, 0, 0, 0, 0},
1931 { 25, 0, 0, 0, 0},
1932 { 36, 0, 0, 0, 0},
1933 { 49, 0, 4, 0, 0},
1934 { 64, 0, 4, 0, 0}, // 20
1935 { 64, 0, 9, 0, 1},
1936 { 64, 0, 9, 0, 4},
1937 { 64, 0, 16, 0, 4},
1938 { 81, 0, 16, 0, 4},
1939 { 81, 0, 16, 0, 4}, // 40
1940 { 81, 0, 25, 0, 9},
1941 { 81, 36, 25, 0, 9},
1942 { 81, 36, 25, 16, 9},
1943 { 81, 49, 0, 25, 9},
1944 { 81, 64, 0, 25, 9}, // 60
1945 { 81, 64, 0, 36, 9},
1946 { 81, 64, 0, 36, 16},
1947 {100, 81, 0, 49, 16},
1948 {100, 81, 0, 49, 25},
1949 {121, 81, 0, 49, 25}, // 80
1950 {121, 81, 0, 49, 25},
1951 {121, 81, 0, 49, 36}, // 88
1952 }};
1953
1954 if (t->cache.num_houses < std::size(_town_squared_town_zone_radius_data) * 4) {
1955 t->cache.squared_town_zone_radius = _town_squared_town_zone_radius_data[t->cache.num_houses / 4];
1956 } else {
1957 int mass = t->cache.num_houses / 8;
1958 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1959 * The offsets are to make sure the radii do not decrease in size when going from the table
1960 * to the calculated value.*/
1966 }
1967}
1968
1974{
1976 uint32_t production = ScaleByCargoScale(t->cache.population >> 3, true);
1977 if (production == 0) continue;
1978
1979 auto &supplied = t->GetOrCreateCargoSupplied(cs->Index());
1980 supplied.history[LAST_MONTH].production = production;
1981 }
1982
1984 uint32_t production = ScaleByCargoScale(t->cache.population >> 4, true);
1985 if (production == 0) continue;
1986
1987 auto &supplied = t->GetOrCreateCargoSupplied(cs->Index());
1988 supplied.history[LAST_MONTH].production = production;
1989 }
1990}
1991
1992static void UpdateTownGrowthRate(Town *t);
1993static void UpdateTownGrowth(Town *t);
1994
2006static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
2007{
2008 AutoRestoreBackup backup(_generating_town, true);
2009
2010 t->xy = tile;
2011 t->cache.num_houses = 0;
2012 t->time_until_rebuild = 10;
2014 t->flags.Reset();
2015 t->cache.population = 0;
2017 /* Spread growth across ticks so even if there are many
2018 * similar towns they're unlikely to grow all in one tick */
2019 t->grow_counter = t->index % Ticks::TOWN_GROWTH_TICKS;
2020 t->growth_rate = TownTicksToGameTicks(250);
2021 t->show_zone = false;
2022
2023 _town_kdtree.Insert(t->index);
2024
2025 /* Set the default cargo requirement for town growth */
2026 switch (_settings_game.game_creation.landscape) {
2029 break;
2030
2034 break;
2035
2036 default:
2037 break;
2038 }
2039
2040 t->fund_buildings_months = 0;
2041
2042 t->ratings.fill(RATING_INITIAL);
2043
2044 t->have_ratings = {};
2045 t->exclusivity = CompanyID::Invalid();
2046 t->exclusive_counter = 0;
2047 t->statues = {};
2048
2049 {
2050 TownNameParams tnp(_settings_game.game_creation.town_name);
2051 t->townnamegrfid = tnp.grfid;
2052 t->townnametype = tnp.type;
2053 }
2054 t->townnameparts = townnameparts;
2055
2056 t->InitializeLayout(layout);
2057
2058 t->larger_town = city;
2059
2060 int x = to_underlying(size) * 16 + 3;
2061 if (size == TownSize::Random) x = (Random() & 0xF) + 8;
2062 /* Don't create huge cities when founding town in-game */
2063 if (city && (!manual || _game_mode == GameMode::Editor)) x *= _settings_game.economy.initial_city_size;
2064
2065 t->cache.num_houses += x;
2067
2068 int i = x * 4;
2069 do {
2071 } while (--i);
2072
2073 t->UpdateVirtCoord();
2074 InvalidateWindowData(WindowClass::TownDirectory, 0, TDIWD_FORCE_REBUILD);
2075
2076 t->cache.num_houses -= x;
2081}
2082
2089static CommandCost TownCanBePlacedHere(TileIndex tile, bool check_surrounding)
2090{
2091 /* Check if too close to the edge of map */
2092 if (DistanceFromEdge(tile) < 12) {
2093 return CommandCost(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP);
2094 }
2095
2096 /* Check distance to all other towns. */
2097 if (IsCloseToTown(tile, _settings_game.economy.town_min_distance)) {
2098 return CommandCost(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
2099 }
2100
2101 /* Can only build on clear flat areas, possibly with trees. */
2102 if ((!IsTileType(tile, TileType::Clear) && !IsTileType(tile, TileType::Trees)) || !IsTileFlat(tile)) {
2103 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2104 }
2105
2106 /* We might want to make sure the town has enough room. */
2107 if (check_surrounding) {
2108 constexpr uint SEARCH_DIAMETER = 5; // Center tile of town + 2 tile radius.
2109 /* Half of the tiles in the search must be valid for the town to build upon. */
2110 constexpr uint VALID_TILE_GOAL = (SEARCH_DIAMETER * SEARCH_DIAMETER) / 2;
2111 uint counter = 0;
2112 int town_height = GetTileZ(tile);
2113 for (TileIndex t : SpiralTileSequence(tile, SEARCH_DIAMETER)) {
2114 if (counter == VALID_TILE_GOAL) break;
2115
2116 switch (GetTileType(t)) {
2117 case TileType::Clear:
2118 /* Don't allow rough tiles, as they are likely wetlands. */
2119 if (GetClearGround(t) == ClearGround::Rough) continue;
2120 break;
2121
2122 case TileType::Trees:
2123 /* Don't allow rough trees, as they are likely wetlands. */
2124 if (GetTreeGround(t) == TreeGround::Rough) continue;
2125 break;
2126
2127 default:
2128 continue;
2129 }
2130
2131 bool elevation_similar = (GetTileMaxZ(t) <= town_height + 1) && (GetTileZ(t) >= town_height - 1);
2132 if (elevation_similar) counter++;
2133 }
2134
2135 if (counter < VALID_TILE_GOAL) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2136 }
2137
2139}
2140
2146static bool IsUniqueTownName(std::string_view name)
2147{
2148 for (const Town *t : Town::Iterate()) {
2149 if (!t->name.empty() && t->name == name) return false;
2150 }
2151
2152 return true;
2153}
2154
2167std::tuple<CommandCost, Money, TownID> CmdFoundTown(DoCommandFlags flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
2168{
2169 TownNameParams par(_settings_game.game_creation.town_name);
2170
2171 if (size >= TownSize::End) return { CMD_ERROR, 0, TownID::Invalid() };
2172 if (layout >= TownLayout::End) return { CMD_ERROR, 0, TownID::Invalid() };
2173
2174 /* Some things are allowed only in the scenario editor and for game scripts. */
2175 if (_game_mode != GameMode::Editor && _current_company != OWNER_DEITY) {
2176 if (_settings_game.economy.found_town == TownFounding::Forbidden) return { CMD_ERROR, 0, TownID::Invalid() };
2177 if (size == TownSize::Large) return { CMD_ERROR, 0, TownID::Invalid() };
2178 if (random_location) return { CMD_ERROR, 0, TownID::Invalid() };
2179 if (_settings_game.economy.found_town != TownFounding::CustomLayout && layout != _settings_game.economy.town_layout) {
2180 return { CMD_ERROR, 0, TownID::Invalid() };
2181 }
2182 } else if (_current_company == OWNER_DEITY && random_location) {
2183 /* Random parameter is not allowed for Game Scripts. */
2184 return { CMD_ERROR, 0, TownID::Invalid() };
2185 }
2186
2187 if (text.empty()) {
2188 /* If supplied name is empty, townnameparts has to generate unique automatic name */
2189 if (!VerifyTownName(townnameparts, &par)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE), 0, TownID::Invalid() };
2190 } else {
2191 /* If name is not empty, it has to be unique custom name */
2192 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return { CMD_ERROR, 0, TownID::Invalid() };
2193 if (!IsUniqueTownName(text)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE), 0, TownID::Invalid() };
2194 }
2195
2196 /* Allocate town struct */
2197 if (!Town::CanAllocateItem()) return { CommandCost(STR_ERROR_TOO_MANY_TOWNS), 0, TownID::Invalid() };
2198
2199 if (!random_location) {
2200 CommandCost ret = TownCanBePlacedHere(tile, false);
2201 if (ret.Failed()) return { ret, 0, TownID::Invalid() };
2202 }
2203
2204 static const EnumIndexArray<uint8_t, TownSize, TownSize::End> town_price_mult = {15, 25, 40, 25};
2205 static const EnumIndexArray<uint8_t, TownSize, TownSize::End> city_price_mult = {20, 35, 55, 35};
2206
2208 uint8_t mult = city ? city_price_mult[size] : town_price_mult[size];
2209
2210 cost.MultiplyCost(mult);
2211
2212 /* Create the town */
2213 TownID new_town = TownID::Invalid();
2214 if (flags.Test(DoCommandFlag::Execute)) {
2215 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
2216 return { CommandCost(ExpensesType::Other), cost.GetCost(), TownID::Invalid() };
2217 }
2218
2219 Backup<bool> old_generating_world(_generating_world, true);
2220 bool road_pending = UpdateNearestTownForRoadTiles(true);
2221 Town *t;
2222 if (random_location) {
2223 t = CreateRandomTown(20, townnameparts, size, city, layout);
2224 } else {
2225 t = Town::Create(tile);
2226 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
2227 }
2228
2229 if (road_pending) UpdateNearestTownForRoadTiles(false);
2230 old_generating_world.Restore();
2231
2232 if (t == nullptr) return { CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN), 0, TownID::Invalid() };
2233
2234 new_town = t->index;
2235
2236 if (!text.empty()) {
2237 t->name = text;
2238 t->UpdateVirtCoord();
2239 }
2240
2241 if (_game_mode != GameMode::Editor) {
2242 /* 't' can't be nullptr since 'random' is false outside scenedit */
2243 assert(!random_location);
2244
2246 AddTileNewsItem(GetEncodedString(STR_NEWS_NEW_TOWN_UNSPONSORED, t->index), NewsType::IndustryOpen, tile);
2247 } else {
2248 std::string company_name = GetString(STR_COMPANY_NAME, _current_company);
2249 AddTileNewsItem(GetEncodedString(STR_NEWS_NEW_TOWN, company_name, t->index), NewsType::IndustryOpen, tile);
2250 }
2251 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
2252 Game::NewEvent(new ScriptEventTownFounded(t->index));
2253 }
2254 }
2255 return { cost, 0, new_town };
2256}
2257
2268{
2269 switch (layout) {
2270 case TownLayout::Grid2x2: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
2271 case TownLayout::Grid3x3: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
2272 default: return tile;
2273 }
2274}
2275
2286{
2287 switch (layout) {
2288 case TownLayout::Grid2x2: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
2289 case TownLayout::Grid3x3: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
2290 default: return true;
2291 }
2292}
2293
2307{
2308 for (auto coast : SpiralTileSequence(tile, 40)) {
2309 /* Find nearest land tile */
2310 if (!IsTileType(coast, TileType::Clear)) continue;
2311
2312 TileIndex furthest = INVALID_TILE;
2313 uint max_dist = 0;
2314 for (auto test : SpiralTileSequence(coast, 10)) {
2315 if (!IsTileType(test, TileType::Clear) || !IsTileFlat(test) || !IsTileAlignedToGrid(test, layout)) continue;
2316 if (TownCanBePlacedHere(test, true).Failed()) continue;
2317
2318 uint dist = GetClosestWaterDistance(test, true);
2319 if (dist > max_dist) {
2320 furthest = test;
2321 max_dist = dist;
2322 }
2323 }
2324 return furthest;
2325 }
2326
2327 /* if we get here just give up */
2328 return INVALID_TILE;
2329}
2330
2345
2355static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
2356{
2357 assert(_game_mode == GameMode::Editor || _generating_world); // These are the preconditions for Commands::DeleteTown
2358
2359 if (!Town::CanAllocateItem()) return nullptr;
2360
2361 do {
2362 /* Generate a tile index not too close from the edge */
2363 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
2364
2365 /* If we tried to place the town on water, find a suitable land tile nearby.
2366 * Otherwise, evaluate the land tile. */
2367 if (IsTileType(tile, TileType::Water)) {
2368 tile = FindNearestGoodCoastalTownSpot(tile, layout);
2369 if (tile == INVALID_TILE) continue;
2370 } else if (TownCanBePlacedHere(tile, true).Failed()) continue;
2371
2372 /* Allocate a town struct */
2373 Town *t = Town::Create(tile);
2374
2375 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2376
2377 /* if the population is still 0 at the point, then the
2378 * placement is so bad it couldn't grow at all */
2379 if (t->cache.population > 0) return t;
2380
2382 [[maybe_unused]] CommandCost rc = Command<Commands::DeleteTown>::Do(DoCommandFlag::Execute, t->index);
2383 assert(rc.Succeeded());
2384
2385 /* We already know that we can allocate a single town when
2386 * entering this function. However, we create and delete
2387 * a town which "resets" the allocation checks. As such we
2388 * need to check again when assertions are enabled. */
2389 assert(Town::CanAllocateItem());
2390 } while (--attempts != 0);
2391
2392 return nullptr;
2393}
2394
2401{
2402 static const uint8_t num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2403 if (_settings_game.difficulty.number_towns == static_cast<uint>(CUSTOM_TOWN_NUMBER_DIFFICULTY)) {
2404 return _settings_newgame.game_creation.custom_town_number;
2405 }
2406 return Map::ScaleBySize(num_initial_towns[_settings_game.difficulty.number_towns]);
2407}
2408
2416bool GenerateTowns(TownLayout layout, std::optional<uint> number)
2417{
2418 uint current_number = 0;
2419 uint total;
2420 if (number.has_value()) {
2421 total = number.value();
2422 } else if (_settings_game.difficulty.number_towns == static_cast<uint>(CUSTOM_TOWN_NUMBER_DIFFICULTY)) {
2423 total = GetDefaultTownsForMapSize();
2424 } else {
2425 total = Map::ScaleByLandProportion(GetDefaultTownsForMapSize() + (Random() & 7));
2426 }
2427
2428 total = Clamp<uint>(total, 1, TownPool::MAX_SIZE);
2429 uint32_t townnameparts;
2430 TownNames town_names;
2431
2433
2434 /* Pre-populate the town names list with the names of any towns already on the map */
2435 for (const Town *town : Town::Iterate()) {
2436 town_names.insert(town->GetCachedName());
2437 }
2438
2439 /* Randomised offset for city status. This means with e.g. 1-in-4 towns being cities, a map with 10 towns
2440 * may have 2 or 3 cities, instead of always 3. */
2441 uint city_random_offset = _settings_game.economy.larger_towns == 0 ? 0 : (Random() % _settings_game.economy.larger_towns);
2442
2443 /* First attempt will be made at creating the suggested number of towns.
2444 * Note that this is really a suggested value, not a required one.
2445 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2446 do {
2447 bool city = (_settings_game.economy.larger_towns != 0 && ((city_random_offset + current_number) % _settings_game.economy.larger_towns) == 0);
2449 /* Get a unique name for the town. */
2450 if (!GenerateTownName(_random, &townnameparts, &town_names)) continue;
2451 /* try 20 times to create a random-sized town for the first loop. */
2452 if (CreateRandomTown(20, townnameparts, TownSize::Random, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
2453 } while (--total);
2454
2455 town_names.clear();
2456
2457 /* Build the town k-d tree again to make sure it's well balanced */
2458 RebuildTownKdtree();
2459
2460 if (current_number != 0) return true;
2461
2462 /* If current_number is still zero at this point, it means that not a single town has been created.
2463 * So give it a last try, but now more aggressive */
2464 if (GenerateTownName(_random, &townnameparts) &&
2465 CreateRandomTown(10000, townnameparts, TownSize::Random, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
2466 return true;
2467 }
2468
2469 /* If there are no towns at all and we are generating new game, bail out */
2470 if (Town::GetNumItems() == 0 && _game_mode != GameMode::Editor) {
2471 ShowErrorMessage(GetEncodedString(STR_ERROR_COULD_NOT_CREATE_TOWN), {}, WarningLevel::Critical);
2472 }
2473
2474 return false; // we are still without a town? we failed, simply
2475}
2476
2486Town *TryGenerateNamedTownAroundTile(TileIndex target_tile, TownSize size, bool city, TownLayout layout, std::string_view name)
2487{
2488 if (!Town::CanAllocateItem() || name.empty() || Utf8StringLength(name) >= MAX_LENGTH_TOWN_NAME_CHARS || !IsUniqueTownName(name)) {
2489 return nullptr;
2490 }
2491
2492 /* Try founding on the target tile, and if that doesn't work, find the nearest suitable tile up to 16 tiles away.
2493 * The target might be on water, blocked somehow, or on a steep slope that can't be terraformed by the founding command. */
2494 for (TileIndex tile : SpiralTileSequence(target_tile, 16, 0, 0)) {
2495 CommandCost ret = TownCanBePlacedHere(tile, false);
2496 if (ret.Failed()) continue;
2497
2498 Town *t = Town::Create(tile);
2499 t->name = name;
2500 DoCreateTown(t, tile, 0, size, city, layout, true);
2501
2502 return t;
2503 }
2504
2505 return nullptr;
2506}
2507
2515{
2516 uint dist = DistanceSquare(tile, t->xy);
2517
2518 if (t->fund_buildings_months != 0 && dist <= 25) return HouseZone::TownCentre;
2519
2520 HouseZone smallest = HouseZone::TownEdge;
2521 for (HouseZone i : HZ_ZONE_ALL) {
2522 if (dist < t->cache.squared_town_zone_radius[to_underlying(i)]) smallest = i;
2523 }
2524
2525 return smallest;
2526}
2527
2539static inline void ClearMakeHouseTile(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool is_protected)
2540{
2541 [[maybe_unused]] CommandCost cc = Command<Commands::LandscapeClear>::Do({DoCommandFlag::Execute, DoCommandFlag::Auto, DoCommandFlag::NoWater}, tile);
2542 assert(cc.Succeeded());
2543
2544 IncreaseBuildingCount(t, type);
2545 MakeHouseTile(tile, t->index, counter, stage, type, random_bits, is_protected);
2546 if (HouseSpec::Get(type)->building_flags.Test(BuildingFlag::IsAnimated)) AddAnimatedTile(tile, false);
2547
2548 MarkTileDirtyByTile(tile);
2549}
2550
2551
2563static void MakeTownHouse(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool is_protected)
2564{
2566
2567 ClearMakeHouseTile(tile, t, counter, stage, type, random_bits, is_protected);
2568 if (size.Any(BUILDING_2_TILES_Y)) ClearMakeHouseTile(tile + TileDiffXY(0, 1), t, counter, stage, ++type, random_bits, is_protected);
2569 if (size.Any(BUILDING_2_TILES_X)) ClearMakeHouseTile(tile + TileDiffXY(1, 0), t, counter, stage, ++type, random_bits, is_protected);
2570 if (size.Any(BUILDING_HAS_4_TILES)) ClearMakeHouseTile(tile + TileDiffXY(1, 1), t, counter, stage, ++type, random_bits, is_protected);
2571
2572 ForAllStationsAroundTiles(TileArea(tile, size.Any(BUILDING_2_TILES_X) ? 2 : 1, size.Any(BUILDING_2_TILES_Y) ? 2 : 1), [t](Station *st, TileIndex) {
2573 t->stations_near.insert(st);
2574 return true;
2575 });
2576}
2577
2578
2585static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2586{
2587 /* cannot build on these slopes... */
2588 Slope slope = GetTileSlope(tile);
2589 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2590
2591 /* at least one RoadTypes allow building the house here? */
2592 if (!RoadTypesAllowHouseHere(tile)) return false;
2593
2594 /* building under a bridge? */
2595 if (IsBridgeAbove(tile)) return false;
2596
2597 /* can we clear the land? */
2598 return Command<Commands::LandscapeClear>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater}, tile).Succeeded();
2599}
2600
2601
2610static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2611{
2612 if (!CanBuildHouseHere(tile, noslope)) return false;
2613
2614 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2615 if (GetTileMaxZ(tile) != z) return false;
2616
2617 return true;
2618}
2619
2620
2629static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2630{
2631 /* we need to check this tile too because we can be at different tile now */
2632 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2633
2635 tile += TileOffsByDiagDir(d);
2636 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2637 }
2638
2639 return true;
2640}
2641
2642
2651static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile, TownExpandModes modes)
2652{
2653 if (!modes.Test(TownExpandMode::Buildings)) return false;
2654
2655 /* Allow towns everywhere when we don't build roads */
2656 if (!TownAllowedToBuildRoads(modes)) return true;
2657
2658 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2659
2660 switch (t->layout) {
2662 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2663 break;
2664
2666 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2667 break;
2668
2669 default:
2670 break;
2671 }
2672
2673 return true;
2674}
2675
2676
2686{
2687 if (!modes.Test(TownExpandMode::Buildings)) return false;
2688
2689 /* Allow towns everywhere when we don't build roads */
2690 if (!TownAllowedToBuildRoads(modes)) return true;
2691
2692 /* Compute relative position of tile. (Positive offsets are towards north) */
2693 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2694
2695 switch (t->layout) {
2697 grid_pos.x %= 3;
2698 grid_pos.y %= 3;
2699 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2700 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2701 break;
2702
2704 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2705 break;
2706
2707 default:
2708 break;
2709 }
2710
2711 return true;
2712}
2713
2714
2726static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second, TownExpandModes modes)
2727{
2728 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2729
2730 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2731 if (TownLayoutAllowsHouseHere(t, tile2, modes) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2732
2733 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2734 if (TownLayoutAllowsHouseHere(t, tile2, modes) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2735 *tile = tile2;
2736 return true;
2737 }
2738
2739 return false;
2740}
2741
2742
2753static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope, TownExpandModes modes)
2754{
2755 TileIndex tile2 = *tile;
2756
2757 for (DiagDirection d = DiagDirection::SE;; d++) { // 'd' goes through DiagDirection::SE, DiagDirection::SW, DiagDirection::NW, DiagDirection::End
2758 if (TownLayoutAllows2x2HouseHere(t, tile2, modes) && CheckFree2x2Area(tile2, maxz, noslope)) {
2759 *tile = tile2;
2760 return true;
2761 }
2762 if (d == DiagDirection::End) break;
2763 tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2764 }
2765
2766 return false;
2767}
2768
2779static void BuildTownHouse(Town *t, TileIndex tile, const HouseSpec *hs, HouseID house, uint8_t random_bits, bool house_completed, bool is_protected)
2780{
2781 /* build the house */
2782 t->cache.num_houses++;
2783
2784 uint8_t construction_counter = 0;
2785 uint8_t construction_stage = 0;
2786
2787 if (_generating_world || _game_mode == GameMode::Editor || house_completed) {
2788 uint32_t construction_random = Random();
2789
2790 construction_stage = TOWN_HOUSE_COMPLETED;
2791 if (_generating_world && !hs->extra_flags.Test(HouseExtraFlag::BuildingIsHistorical) && Chance16(1, 7)) construction_stage = GB(construction_random, 0, 2);
2792
2793 if (construction_stage == TOWN_HOUSE_COMPLETED) {
2795 } else {
2796 construction_counter = GB(construction_random, 2, 2);
2797 }
2798 }
2799
2800 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits, is_protected);
2803
2804 BuildingFlags size = hs->building_flags;
2805
2806 TriggerHouseAnimation_ConstructionStageChanged(tile, true);
2807 if (size.Any(BUILDING_2_TILES_Y)) TriggerHouseAnimation_ConstructionStageChanged(tile + TileDiffXY(0, 1), true);
2808 if (size.Any(BUILDING_2_TILES_X)) TriggerHouseAnimation_ConstructionStageChanged(tile + TileDiffXY(1, 0), true);
2809 if (size.Any(BUILDING_HAS_4_TILES)) TriggerHouseAnimation_ConstructionStageChanged(tile + TileDiffXY(1, 1), true);
2810}
2811
2820{
2821 /* forbidden building here by town layout */
2822 if (!TownLayoutAllowsHouseHere(t, tile, modes)) return false;
2823
2824 /* no house allowed at all, bail out */
2825 if (!CanBuildHouseHere(tile, false)) return false;
2826
2827 Slope slope = GetTileSlope(tile);
2828 int maxz = GetTileMaxZ(tile);
2829
2830 /* Get the town zone type of the current tile, as well as the climate.
2831 * This will allow to easily compare with the specs of the new house to build */
2832 HouseZones zones = GetTownRadiusGroup(t, tile);
2833
2834 switch (_settings_game.game_creation.landscape) {
2839 }
2840
2841 /* bits 0-4 are used
2842 * bits 11-15 are used
2843 * bits 5-10 are not used. */
2844 static std::vector<std::pair<HouseID, uint>> probs;
2845 probs.clear();
2846
2847 uint probability_max = 0;
2848
2849 /* Generate a list of all possible houses that can be built. */
2850 for (const auto &hs : HouseSpec::Specs()) {
2851 /* Verify that the candidate house spec matches the current tile status */
2852 if (!hs.building_availability.All(zones) || !hs.enabled || hs.grf_prop.override_id != INVALID_HOUSE_ID) continue;
2853
2854 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2855 if (hs.class_id != HOUSE_NO_CLASS) {
2856 /* id_count is always <= class_count, so it doesn't need to be checked */
2857 if (t->cache.building_counts.class_count[hs.class_id] == UINT16_MAX) continue;
2858 } else {
2859 /* If the house has no class, check id_count instead */
2860 if (t->cache.building_counts.id_count[hs.Index()] == UINT16_MAX) continue;
2861 }
2862
2863 uint cur_prob = hs.probability;
2864 probability_max += cur_prob;
2865 probs.emplace_back(hs.Index(), cur_prob);
2866 }
2867
2868 TileIndex base_tile = tile;
2869
2870 while (probability_max > 0) {
2871 /* Building a multitile building can change the location of tile.
2872 * The building would still be built partially on that tile, but
2873 * its northern tile would be elsewhere. However, if the callback
2874 * fails we would be basing further work from the changed tile.
2875 * So a next 1x1 tile building could be built on the wrong tile. */
2876 tile = base_tile;
2877
2878 uint r = RandomRange(probability_max);
2879 uint i;
2880 for (i = 0; i < probs.size(); i++) {
2881 if (probs[i].second > r) break;
2882 r -= probs[i].second;
2883 }
2884
2885 HouseID house = probs[i].first;
2886 probability_max -= probs[i].second;
2887
2888 /* remove tested house from the set */
2889 probs[i] = probs.back();
2890 probs.pop_back();
2891
2892 const HouseSpec *hs = HouseSpec::Get(house);
2893
2895 continue;
2896 }
2897
2899
2900 /* Special houses that there can be only one of. */
2901 TownFlags oneof{};
2902
2904 oneof.Set(TownFlag::HasChurch);
2907 }
2908
2909 if (t->flags.Any(oneof)) continue;
2910
2911 /* Make sure there is no slope? */
2912 bool noslope = hs->building_flags.Test(BuildingFlag::NotSloped);
2913 if (noslope && slope != SLOPE_FLAT) continue;
2914
2916 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope, modes)) continue;
2917 } else if (hs->building_flags.Test(BuildingFlag::Size2x1)) {
2918 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DiagDirection::SW, modes)) continue;
2919 } else if (hs->building_flags.Test(BuildingFlag::Size1x2)) {
2920 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DiagDirection::SE, modes)) continue;
2921 } else {
2922 /* 1x1 house checks are already done */
2923 }
2924
2925 uint8_t random_bits = Random();
2926
2928 uint16_t callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, {}, true, random_bits);
2929 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2930 }
2931
2932 /* Special houses that there can be only one of. */
2933 t->flags.Set(oneof);
2934
2935 BuildTownHouse(t, tile, hs, house, random_bits, false, false);
2936
2937 return true;
2938 }
2939
2940 return false;
2941}
2942
2952CommandCost CmdPlaceHouse(DoCommandFlags flags, TileIndex tile, HouseID house, bool is_protected, bool replace)
2953{
2954 if (_game_mode != GameMode::Editor && _settings_game.economy.place_houses == PlaceHouses::Forbidden) return CMD_ERROR;
2955
2956 if (Town::GetNumItems() == 0) return CommandCost(STR_ERROR_MUST_FOUND_TOWN_FIRST);
2957
2958 if (static_cast<size_t>(house) >= HouseSpec::Specs().size()) return CMD_ERROR;
2959 const HouseSpec *hs = HouseSpec::Get(house);
2960 if (!hs->enabled) return CMD_ERROR;
2961
2962 int maxz = GetTileMaxZ(tile);
2963
2964 /* Check each tile of a multi-tile house. */
2965 TileArea ta(tile, 1, 1);
2966 if (hs->building_flags.Test(BuildingFlag::Size2x2)) ta.Add(TileAddXY(tile, 1, 1));
2969
2970 for (const TileIndex subtile : ta) {
2971 /* Houses cannot be built on steep slopes. */
2972 Slope slope = GetTileSlope(subtile);
2973 if (IsSteepSlope(slope)) return CommandCost(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
2974
2975 /* Houses cannot be built under bridges. */
2976 if (IsBridgeAbove(subtile)) return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2977
2978 /* Make sure there is no slope? */
2979 bool noslope = hs->building_flags.Test(BuildingFlag::NotSloped);
2980 if (noslope && slope != SLOPE_FLAT) return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
2981
2982 /* All tiles of a multi-tile house must have the same z-level. */
2983 if (GetTileMaxZ(subtile) != maxz) return CommandCost(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
2984
2985 /* We might be replacing an existing house, otherwise check if we can clear land. */
2986 if (!(replace && GetTileType(subtile) == TileType::House)) {
2987 CommandCost cost = Command<Commands::LandscapeClear>::Do({DoCommandFlag::Auto, DoCommandFlag::NoWater}, subtile);
2988 if (!cost.Succeeded()) return cost;
2989 }
2990 }
2991
2992 if (flags.Test(DoCommandFlag::Execute)) {
2993 /* If replacing, clear any existing houses first. */
2994 if (replace) {
2995 for (const TileIndex &subtile : ta) {
2996 if (GetTileType(subtile) == TileType::House) ClearTownHouse(Town::GetByTile(subtile), subtile);
2997 }
2998 }
2999
3000 Town *t = ClosestTownFromTile(tile, UINT_MAX);
3001 bool house_completed = _settings_game.economy.place_houses == PlaceHouses::AllowedConstructed;
3002 BuildTownHouse(t, tile, hs, house, Random(), house_completed, is_protected);
3003 }
3004
3005 return CommandCost();
3006}
3007
3019CommandCost CmdPlaceHouseArea(DoCommandFlags flags, TileIndex tile, TileIndex start_tile, HouseID house, bool is_protected, bool replace, bool diagonal)
3020{
3021 if (start_tile >= Map::Size()) return CMD_ERROR;
3022
3023 if (_game_mode != GameMode::Editor && _settings_game.economy.place_houses == PlaceHouses::Forbidden) return CMD_ERROR;
3024
3025 if (Town::GetNumItems() == 0) return CommandCost(STR_ERROR_MUST_FOUND_TOWN_FIRST);
3026
3027 if (static_cast<size_t>(house) >= HouseSpec::Specs().size()) return CMD_ERROR;
3028 const HouseSpec *hs = HouseSpec::Get(house);
3029 if (!hs->enabled) return CMD_ERROR;
3030
3031 /* Only allow placing an area of 1x1 houses. */
3033
3034 /* Use the built object limit to rate limit house placement. */
3036 int limit = (c == nullptr ? INT32_MAX : GB(c->build_object_limit, 16, 16));
3037
3038 CommandCost last_error = CMD_ERROR;
3039 bool had_success = false;
3040
3041 for (TileIndex t : CreateOrthoDiagonalArea(tile, start_tile, diagonal)) {
3042 CommandCost ret = Command<Commands::PlaceHouse>::Do(DoCommandFlags{flags}.Reset(DoCommandFlag::Execute), t, house, is_protected, replace);
3043
3044 /* If we've reached the limit, stop building (or testing). */
3045 if (c != nullptr && limit-- <= 0) break;
3046
3047 if (ret.Failed()) {
3048 last_error = std::move(ret);
3049 continue;
3050 }
3051
3052 if (flags.Test(DoCommandFlag::Execute)) Command<Commands::PlaceHouse>::Do(flags, t, house, is_protected, replace);
3053 had_success = true;
3054 }
3055
3056 return had_success ? CommandCost{} : last_error;
3057}
3058
3065static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
3066{
3067 assert(IsTileType(tile, TileType::House));
3068 DecreaseBuildingCount(t, house);
3069 DoClearSquare(tile);
3070
3072}
3073
3082{
3083 if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
3084 if (HouseSpec::Get(house - 1)->building_flags.Test(BuildingFlag::Size2x1)) {
3085 house--;
3086 return TileDiffXY(-1, 0);
3087 } else if (HouseSpec::Get(house - 1)->building_flags.Any(BUILDING_2_TILES_Y)) {
3088 house--;
3089 return TileDiffXY(0, -1);
3090 } else if (HouseSpec::Get(house - 2)->building_flags.Any(BUILDING_HAS_4_TILES)) {
3091 house -= 2;
3092 return TileDiffXY(-1, 0);
3093 } else if (HouseSpec::Get(house - 3)->building_flags.Any(BUILDING_HAS_4_TILES)) {
3094 house -= 3;
3095 return TileDiffXY(-1, -1);
3096 }
3097 }
3098 return TileDiffXY(0, 0);
3099}
3100
3107{
3108 assert(IsTileType(tile, TileType::House));
3109
3110 HouseID house = GetHouseType(tile);
3111
3112 /* The northernmost tile of the house is the main house. */
3113 tile += GetHouseNorthPart(house);
3114
3115 const HouseSpec *hs = HouseSpec::Get(house);
3116
3117 /* Remove population from the town if the house is finished. */
3118 if (IsHouseCompleted(tile)) {
3120 }
3121
3122 t->cache.num_houses--;
3123
3124 /* Clear flags for houses that only may exist once/town. */
3129 }
3130
3131 /* Do the actual clearing of tiles */
3132 DoClearTownHouseHelper(tile, t, house);
3133 if (hs->building_flags.Any(BUILDING_2_TILES_Y)) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
3134 if (hs->building_flags.Any(BUILDING_2_TILES_X)) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
3135 if (hs->building_flags.Any(BUILDING_HAS_4_TILES)) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
3136
3138
3140}
3141
3149CommandCost CmdRenameTown(DoCommandFlags flags, TownID town_id, const std::string &text)
3150{
3151 Town *t = Town::GetIfValid(town_id);
3152 if (t == nullptr) return CMD_ERROR;
3153
3154 bool reset = text.empty();
3155
3156 if (!reset) {
3158 if (!IsUniqueTownName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
3159 }
3160
3161 if (flags.Test(DoCommandFlag::Execute)) {
3162 t->cached_name.clear();
3163 if (reset) {
3164 t->name.clear();
3165 } else {
3166 t->name = text;
3167 }
3168
3169 t->UpdateVirtCoord();
3170 InvalidateWindowData(WindowClass::TownDirectory, 0, TDIWD_FORCE_RESORT);
3171 ClearAllStationCachedNames();
3172 ClearAllIndustryCachedNames();
3174 }
3175 return CommandCost();
3176}
3177
3184{
3185 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3186 if (cs->town_acceptance_effect == effect) return cs;
3187 }
3188 return nullptr;
3189}
3190
3199CommandCost CmdTownCargoGoal(DoCommandFlags flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
3200{
3201 if (_current_company != OWNER_DEITY) return CMD_ERROR;
3202
3203 if (tae < TownAcceptanceEffect::Begin || tae >= TownAcceptanceEffect::End) return CMD_ERROR;
3204
3205 Town *t = Town::GetIfValid(town_id);
3206 if (t == nullptr) return CMD_ERROR;
3207
3208 /* Validate if there is a cargo which is the requested TownEffect */
3210 if (cargo == nullptr) return CMD_ERROR;
3211
3212 if (flags.Test(DoCommandFlag::Execute)) {
3213 t->goal[tae] = goal;
3215 InvalidateWindowData(WindowClass::TownView, town_id);
3216 }
3217
3218 return CommandCost();
3219}
3220
3228CommandCost CmdTownSetText(DoCommandFlags flags, TownID town_id, const EncodedString &text)
3229{
3230 if (_current_company != OWNER_DEITY) return CMD_ERROR;
3231 Town *t = Town::GetIfValid(town_id);
3232 if (t == nullptr) return CMD_ERROR;
3233
3234 if (flags.Test(DoCommandFlag::Execute)) {
3235 t->text.clear();
3236 if (!text.empty()) t->text = text;
3237 InvalidateWindowData(WindowClass::TownView, town_id);
3238 }
3239
3240 return CommandCost();
3241}
3242
3250CommandCost CmdTownGrowthRate(DoCommandFlags flags, TownID town_id, uint16_t growth_rate)
3251{
3252 if (_current_company != OWNER_DEITY) return CMD_ERROR;
3253
3254 Town *t = Town::GetIfValid(town_id);
3255 if (t == nullptr) return CMD_ERROR;
3256
3257 if (flags.Test(DoCommandFlag::Execute)) {
3258 if (growth_rate == 0) {
3259 /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
3261 } else {
3262 uint old_rate = t->growth_rate;
3263 if (t->grow_counter >= old_rate) {
3264 /* This also catches old_rate == 0 */
3265 t->grow_counter = growth_rate;
3266 } else {
3267 /* Scale grow_counter, so half finished houses stay half finished */
3268 t->grow_counter = t->grow_counter * growth_rate / old_rate;
3269 }
3270 t->growth_rate = growth_rate;
3272 }
3274 InvalidateWindowData(WindowClass::TownView, town_id);
3275 }
3276
3277 return CommandCost();
3278}
3279
3288CommandCost CmdTownRating(DoCommandFlags flags, TownID town_id, CompanyID company_id, int16_t rating)
3289{
3290 if (_current_company != OWNER_DEITY) return CMD_ERROR;
3291
3292 Town *t = Town::GetIfValid(town_id);
3293 if (t == nullptr) return CMD_ERROR;
3294
3295 if (!Company::IsValidID(company_id)) return CMD_ERROR;
3296
3297 int16_t new_rating = Clamp(rating, RATING_MINIMUM, RATING_MAXIMUM);
3298 if (flags.Test(DoCommandFlag::Execute)) {
3299 t->ratings[company_id] = new_rating;
3300 InvalidateWindowData(WindowClass::TownAuthority, town_id);
3301 }
3302
3303 return CommandCost();
3304}
3305
3314CommandCost CmdExpandTown(DoCommandFlags flags, TownID town_id, uint32_t grow_amount, TownExpandModes modes)
3315{
3316 if (_game_mode != GameMode::Editor && _current_company != OWNER_DEITY) return CMD_ERROR;
3317 if (modes.None()) return CMD_ERROR;
3318 Town *t = Town::GetIfValid(town_id);
3319 if (t == nullptr) return CMD_ERROR;
3320
3321 if (flags.Test(DoCommandFlag::Execute)) {
3322 /* The more houses, the faster we grow */
3323 if (grow_amount == 0) {
3324 uint amount = RandomRange(ClampTo<uint16_t>(t->cache.num_houses / 10)) + 3;
3325 t->cache.num_houses += amount;
3327
3328 uint n = amount * 10;
3329 do GrowTown(t, modes); while (--n);
3330
3331 t->cache.num_houses -= amount;
3332 } else {
3333 for (; grow_amount > 0; grow_amount--) {
3334 /* Try several times to grow, as we are really suppose to grow */
3335 for (uint i = 0; i < 25; i++) if (GrowTown(t, modes)) break;
3336 }
3337 }
3339
3341 }
3342
3343 return CommandCost();
3344}
3345
3353{
3354 if (_game_mode != GameMode::Editor && !_generating_world) return CMD_ERROR;
3355 Town *t = Town::GetIfValid(town_id);
3356 if (t == nullptr) return CMD_ERROR;
3357
3358 /* Stations refer to towns. */
3359 for (const Station *st : Station::Iterate()) {
3360 if (st->town == t) {
3361 /* Non-oil rig stations are always a problem. */
3362 if (!st->facilities.Test(StationFacility::Airport) || st->airport.type != AT_OILRIG) return CMD_ERROR;
3363 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
3364 CommandCost ret = Command<Commands::LandscapeClear>::Do(flags, st->airport.tile);
3365 if (ret.Failed()) return ret;
3366 }
3367 }
3368
3369 /* Waypoints refer to towns. */
3370 for (const Waypoint *wp : Waypoint::Iterate()) {
3371 if (wp->town == t) return CMD_ERROR;
3372 }
3373
3374 /* Depots refer to towns. */
3375 for (const Depot *d : Depot::Iterate()) {
3376 if (d->town == t) return CMD_ERROR;
3377 }
3378
3379 /* Check all tiles for town ownership. First check for bridge tiles, as
3380 * these do not directly have an owner so we need to check adjacent
3381 * tiles. This won't work correctly in the same loop if the adjacent
3382 * tile was already deleted earlier in the loop. */
3383 for (const auto current_tile : Map::Iterate()) {
3384 if (IsTileType(current_tile, TileType::TunnelBridge) && TestTownOwnsBridge(current_tile, t)) {
3385 CommandCost ret = Command<Commands::LandscapeClear>::Do(flags, current_tile);
3386 if (ret.Failed()) return ret;
3387 }
3388 }
3389
3390 /* Check all remaining tiles for town ownership. */
3391 for (const auto current_tile : Map::Iterate()) {
3392 bool try_clear = false;
3393 switch (GetTileType(current_tile)) {
3394 case TileType::Road:
3395 try_clear = HasTownOwnedRoad(current_tile) && GetTownIndex(current_tile) == t->index;
3396 break;
3397
3398 case TileType::House:
3399 try_clear = GetTownIndex(current_tile) == t->index;
3400 break;
3401
3402 case TileType::Industry:
3403 try_clear = Industry::GetByTile(current_tile)->town == t;
3404 break;
3405
3406 case TileType::Object:
3407 if (Town::GetNumItems() == 1) {
3408 /* No towns will be left, remove it! */
3409 try_clear = true;
3410 } else {
3411 Object *o = Object::GetByTile(current_tile);
3412 if (o->town == t) {
3413 if (o->type == OBJECT_STATUE) {
3414 /* Statue... always remove. */
3415 try_clear = true;
3416 } else {
3417 /* Tell to find a new town. */
3418 if (flags.Test(DoCommandFlag::Execute)) o->town = nullptr;
3419 }
3420 }
3421 }
3422 break;
3423
3424 default:
3425 break;
3426 }
3427 if (try_clear) {
3428 CommandCost ret = Command<Commands::LandscapeClear>::Do(flags, current_tile);
3429 if (ret.Failed()) return ret;
3430 }
3431 }
3432
3433 /* The town destructor will delete the other things related to the town. */
3434 if (flags.Test(DoCommandFlag::Execute)) {
3435 _town_kdtree.Remove(t->index);
3436 if (t->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(t->index));
3437 delete t;
3438 }
3439
3440 return CommandCost();
3441}
3442
3449{
3454 static const uint8_t town_action_costs[] = {
3455 2, 4, 9, 35, 48, 53, 117, 175
3456 };
3457 static_assert(std::size(town_action_costs) == to_underlying(TownAction::End));
3458
3459 assert(to_underlying(action) < std::size(town_action_costs));
3460 return town_action_costs[to_underlying(action)];
3461}
3462
3470{
3471 if (flags.Test(DoCommandFlag::Execute)) {
3473 }
3474 return CommandCost();
3475}
3476
3484{
3485 if (flags.Test(DoCommandFlag::Execute)) {
3487 }
3488 return CommandCost();
3489}
3490
3498{
3499 if (flags.Test(DoCommandFlag::Execute)) {
3501 }
3502 return CommandCost();
3503}
3504
3512{
3513 /* Check if the company is allowed to fund new roads. */
3514 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
3515
3516 if (flags.Test(DoCommandFlag::Execute)) {
3517 t->road_build_months = 6;
3518
3519 std::string company_name = GetString(STR_COMPANY_NAME, _current_company);
3520
3522 GetEncodedString(TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_ROAD_REBUILDING_MINUTES : STR_NEWS_ROAD_REBUILDING_MONTHS, t->index, company_name),
3523 NewsType::General, NewsStyle::Normal, {}, t->index);
3524 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction(_current_company, t->index));
3525 Game::NewEvent(new ScriptEventRoadReconstruction(_current_company, t->index));
3526 }
3527 return CommandCost();
3528}
3529
3535static bool CheckClearTile(TileIndex tile)
3536{
3538 return Command<Commands::LandscapeClear>::Do({}, tile).Succeeded();
3539}
3540
3549{
3550 if (!Object::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_OBJECTS);
3551
3552 static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
3553
3554 TileIndex best_position = INVALID_TILE;
3555 uint tile_count = 0;
3556 for (auto tile : SpiralTileSequence(t->xy, 9)) {
3557 tile_count++;
3558
3559 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3560 if (IsSteepSlope(GetTileSlope(tile))) continue;
3561 /* Don't build statues under bridges. */
3562 if (IsBridgeAbove(tile)) continue;
3563
3564 /* A clear-able open space is always preferred. */
3565 if ((IsTileType(tile, TileType::Clear) || IsTileType(tile, TileType::Trees)) && CheckClearTile(tile)) {
3566 best_position = tile;
3567 break;
3568 }
3569
3570 bool house = IsTileType(tile, TileType::House);
3571
3572 /* Searching inside the inner circle. */
3573 if (tile_count <= STATUE_NUMBER_INNER_TILES) {
3574 /* Save first house in inner circle. */
3575 if (house && best_position == INVALID_TILE && CheckClearTile(tile)) {
3576 best_position = tile;
3577 }
3578
3579 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3580 if (tile_count == STATUE_NUMBER_INNER_TILES && best_position != INVALID_TILE) break;
3581 }
3582
3583 /* Searching outside the circle, just pick the first possible spot. */
3584 if (!house || !CheckClearTile(tile)) continue;
3585 best_position = tile;
3586 break;
3587 }
3588 if (best_position == INVALID_TILE) return CommandCost(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
3589
3590 if (flags.Test(DoCommandFlag::Execute)) {
3592 Command<Commands::LandscapeClear>::Do(DoCommandFlag::Execute, best_position);
3593 cur_company.Restore();
3594 BuildObject(OBJECT_STATUE, best_position, _current_company, t);
3595 t->statues.Set(_current_company); // Once found and built, "inform" the Town.
3596 MarkTileDirtyByTile(best_position);
3597 }
3598 return CommandCost();
3599}
3600
3608{
3609 /* Check if it's allowed to buy the rights */
3610 if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
3611
3612 if (flags.Test(DoCommandFlag::Execute)) {
3613 /* And grow for 3 months */
3614 t->fund_buildings_months = 3;
3615
3616 /* Enable growth (also checking GameScript's opinion) */
3618
3619 /* Build a new house, but add a small delay to make sure
3620 * that spamming funding doesn't let town grow any faster
3621 * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3622 * Also emulate original behaviour when town was only growing in
3623 * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3624 * tick-perfect and gives player some time window where they can
3625 * spam funding with the exact same efficiency.
3626 */
3628
3629 SetWindowDirty(WindowClass::TownView, t->index);
3630 }
3631 return CommandCost();
3632}
3633
3641{
3642 /* Check if it's allowed to buy the rights */
3643 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
3644 if (t->exclusivity != CompanyID::Invalid()) return CMD_ERROR;
3645
3646 if (flags.Test(DoCommandFlag::Execute)) {
3647 t->exclusive_counter = 12;
3649
3651
3652 SetWindowClassesDirty(WindowClass::StationView);
3653
3654 /* Spawn news message */
3655 auto cni = std::make_unique<CompanyNewsInformation>(STR_NEWS_EXCLUSIVE_RIGHTS_TITLE, Company::Get(_current_company));
3656 EncodedString message = GetEncodedString(TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MINUTES : STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MONTHS, t->index, cni->company_name);
3657 AddNewsItem(std::move(message),
3658 NewsType::General, NewsStyle::Company, {}, t->index, {}, std::move(cni));
3659 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights(_current_company, t->index));
3660 Game::NewEvent(new ScriptEventExclusiveTransportRights(_current_company, t->index));
3661 }
3662 return CommandCost();
3663}
3664
3672{
3673 if (flags.Test(DoCommandFlag::Execute)) {
3674 if (Chance16(1, 14)) {
3675 /* set as unwanted for 6 months */
3676 t->unwanted[_current_company] = 6;
3677
3678 /* set all close by station ratings to 0 */
3679 for (Station *st : Station::Iterate()) {
3680 if (st->town == t && st->owner == _current_company) {
3681 for (GoodsEntry &ge : st->goods) ge.rating = 0;
3682 }
3683 }
3684
3685 /* only show error message to the executing player. All errors are handled command.c
3686 * but this is special, because it can only 'fail' on a DoCommandFlag::Execute */
3687 if (IsLocalCompany()) ShowErrorMessage(GetEncodedString(STR_ERROR_BRIBE_FAILED), {}, WarningLevel::Info);
3688
3689 /* decrease by a lot!
3690 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3691 * be independent of any cheat settings
3692 */
3693 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3694 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3695 SetWindowDirty(WindowClass::TownAuthority, t->index);
3696 }
3697 } else {
3698 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DoCommandFlag::Execute);
3699 if (t->exclusivity != _current_company && t->exclusivity != CompanyID::Invalid()) {
3700 t->exclusivity = CompanyID::Invalid();
3701 t->exclusive_counter = 0;
3702 }
3703 }
3704 }
3705 return CommandCost();
3706}
3707
3708typedef CommandCost TownActionProc(Town *t, DoCommandFlags flags);
3709static TownActionProc * const _town_action_proc[] = {
3718};
3719static_assert(std::size(_town_action_proc) == to_underlying(TownAction::End));
3720
3727TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
3728{
3729 TownActions buttons{};
3730
3731 /* Spectators and unwanted have no options */
3732 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3733
3734 /* Actions worth more than this are not able to be performed */
3735 Money avail = GetAvailableMoney(cid);
3736
3737 /* Check the action bits for validity and
3738 * if they are valid add them */
3739 for (TownAction cur : EnumRange(TownAction::End)) {
3740
3741 /* Is the company prohibited from bribing ? */
3742 if (cur == TownAction::Bribe) {
3743 /* Company can't bribe if setting is disabled */
3744 if (!_settings_game.economy.bribe) continue;
3745 /* Company can bribe if another company has exclusive transport rights,
3746 * or its standing with the town is less than outstanding. */
3747 if (t->ratings[cid] >= RATING_BRIBE_MAXIMUM) {
3748 if (t->exclusivity == _current_company) continue;
3749 if (t->exclusive_counter == 0) continue;
3750 }
3751 }
3752
3753 /* Is the company not able to buy exclusive rights ? */
3754 if (cur == TownAction::BuyRights && (!_settings_game.economy.exclusive_rights || t->exclusive_counter != 0)) continue;
3755
3756 /* Is the company not able to fund buildings ? */
3757 if (cur == TownAction::FundBuildings && !_settings_game.economy.fund_buildings) continue;
3758
3759 /* Is the company not able to fund local road reconstruction? */
3760 if (cur == TownAction::RoadRebuild && !_settings_game.economy.fund_roads) continue;
3761
3762 /* Is the company not able to build a statue ? */
3763 if (cur == TownAction::BuildStatue && t->statues.Test(cid)) continue;
3764
3765 if (avail >= GetTownActionCost(cur) * _price[Price::TownAction] >> 8) {
3766 buttons.Set(cur);
3767 }
3768 }
3769 }
3770
3771 return buttons;
3772}
3773
3784{
3785 Town *t = Town::GetIfValid(town_id);
3786 if (t == nullptr || to_underlying(action) >= std::size(_town_action_proc)) return CMD_ERROR;
3787
3788 if (!GetMaskOfTownActions(_current_company, t).Test(action)) return CMD_ERROR;
3789
3791
3792 CommandCost ret = _town_action_proc[to_underlying(action)](t, flags);
3793 if (ret.Failed()) return ret;
3794
3795 if (flags.Test(DoCommandFlag::Execute)) {
3796 SetWindowDirty(WindowClass::TownAuthority, town_id);
3797 }
3798
3799 return cost;
3800}
3801
3802template <typename Func>
3803static void ForAllStationsNearTown(Town *t, Func func)
3804{
3805 /* Ideally the search radius should be close to the actual town zone 0 radius.
3806 * The true radius is not stored or calculated anywhere, only the squared radius. */
3807 /* The efficiency of this search might be improved for large towns and many stations on the map,
3808 * by using an integer square root approximation giving a value not less than the true square root. */
3810 ForAllStationsRadius(t->xy, search_radius, [&](const Station * st) {
3811 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[to_underlying(HouseZone::TownEdge)]) {
3812 func(st);
3813 }
3814 });
3815}
3816
3821static void UpdateTownRating(Town *t)
3822{
3823 /* Increase company ratings if they're low */
3824 for (const Company *c : Company::Iterate()) {
3825 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3826 t->ratings[c->index] = std::min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3827 }
3828 }
3829
3830 ForAllStationsNearTown(t, [&](const Station *st) {
3831 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3832 if (Company::IsValidID(st->owner)) {
3833 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3834 t->ratings[st->owner] = std::min<int>(new_rating, INT16_MAX); // do not let it overflow
3835 }
3836 } else {
3837 if (Company::IsValidID(st->owner)) {
3838 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3839 t->ratings[st->owner] = std::max(new_rating, INT16_MIN);
3840 }
3841 }
3842 });
3843
3844 /* clamp all ratings to valid values */
3845 for (auto it = t->ratings.begin(); it != t->ratings.end(); ++it) {
3846 *it = Clamp(*it, RATING_MINIMUM, RATING_MAXIMUM);
3847 }
3848
3849 SetWindowDirty(WindowClass::TownAuthority, t->index);
3850}
3851
3852
3859static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
3860{
3861 if (t->growth_rate == TOWN_GROWTH_RATE_NONE) return;
3862 if (prev_growth_rate == TOWN_GROWTH_RATE_NONE) {
3863 t->grow_counter = std::min<uint16_t>(t->growth_rate, t->grow_counter);
3864 return;
3865 }
3866 t->grow_counter = RoundDivSU((uint32_t)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1);
3867}
3868
3875{
3876 int n = 0;
3877 ForAllStationsNearTown(t, [&](const Station * st) {
3878 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3879 n++;
3880 }
3881 });
3882 return n;
3883}
3884
3892{
3898 static const uint16_t _grow_count_values[2][6] = {
3899 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3900 { 320, 420, 300, 220, 160, 100 } // Normal values
3901 };
3902
3903 int n = CountActiveStations(t);
3904 uint16_t m = _grow_count_values[t->fund_buildings_months != 0 ? 0 : 1][std::min(n, 5)];
3905
3906 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3907
3908 m >>= growth_multiplier;
3909 if (t->larger_town) m /= 2;
3910
3911 return TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3912}
3913
3919{
3920 if (t->flags.Test(TownFlag::CustomGrowth)) return;
3921 uint old_rate = t->growth_rate;
3923 UpdateTownGrowCounter(t, old_rate);
3924 SetWindowDirty(WindowClass::TownView, t->index);
3925}
3926
3931static void UpdateTownGrowth(Town *t)
3932{
3934
3936 SetWindowDirty(WindowClass::TownView, t->index);
3937
3938 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3939
3940 if (t->fund_buildings_months == 0) {
3941 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3943 switch (t->goal[i]) {
3944 case TOWN_GROWTH_WINTER:
3945 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3946 break;
3947 case TOWN_GROWTH_DESERT:
3948 if (GetTropicZone(t->xy) == TropicZone::Desert && t->received[i].old_act == 0 && t->cache.population > 60) return;
3949 break;
3950 default:
3951 if (t->goal[i] > t->received[i].old_act) return;
3952 break;
3953 }
3954 }
3955 }
3956
3959 SetWindowDirty(WindowClass::TownView, t->index);
3960 return;
3961 }
3962
3963 if (t->fund_buildings_months == 0 && CountActiveStations(t) == 0 && !Chance16(1, 12)) return;
3964
3966 SetWindowDirty(WindowClass::TownView, t->index);
3967}
3968
3976{
3977 /* The required rating is hardcoded to RATING_VERYPOOR (see below), not the authority attitude setting, so we can bail out like this. */
3978 if (_settings_game.difficulty.town_council_tolerance == TOWN_COUNCIL_PERMISSIVE) return CommandCost();
3979
3981
3982 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
3983 if (t == nullptr) return CommandCost();
3984
3985 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3986
3987 return CommandCostWithParam(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS, t->index);
3988}
3989
3999{
4000 if (Town::GetNumItems() == 0) return nullptr;
4001
4002 TownID tid = _town_kdtree.FindNearest(TileX(tile), TileY(tile));
4003 Town *town = Town::Get(tid);
4004 if (DistanceManhattan(tile, town->xy) < threshold) return town;
4005 return nullptr;
4006}
4007
4016Town *ClosestTownFromTile(TileIndex tile, uint threshold)
4017{
4018 switch (GetTileType(tile)) {
4019 case TileType::Road:
4020 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
4021
4022 if (!HasTownOwnedRoad(tile)) {
4023 TownID tid = GetTownIndex(tile);
4024
4025 if (tid == TownID::Invalid()) {
4026 /* in the case we are generating "many random towns", this value may be TownID::Invalid() */
4027 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
4028 assert(Town::GetNumItems() == 0);
4029 return nullptr;
4030 }
4031
4032 assert(Town::IsValidID(tid));
4033 Town *town = Town::Get(tid);
4034
4035 if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
4036
4037 return town;
4038 }
4039 [[fallthrough]];
4040
4041 case TileType::House:
4042 return Town::GetByTile(tile);
4043
4044 default:
4045 return CalcClosestTownFromTile(tile, threshold);
4046 }
4047}
4048
4049static bool _town_rating_test = false;
4050static std::map<const Town *, int> _town_test_ratings;
4051
4058{
4059 static int ref_count = 0; // Number of times test-mode is switched on.
4060 if (mode) {
4061 if (ref_count == 0) {
4062 _town_test_ratings.clear();
4063 }
4064 ref_count++;
4065 } else {
4066 assert(ref_count > 0);
4067 ref_count--;
4068 }
4069 _town_rating_test = !(ref_count == 0);
4070}
4071
4077static int GetRating(const Town *t)
4078{
4079 if (_town_rating_test) {
4080 auto it = _town_test_ratings.find(t);
4081 if (it != _town_test_ratings.end()) {
4082 return it->second;
4083 }
4084 }
4085 return t->ratings[_current_company];
4086}
4087
4095void ChangeTownRating(Town *t, int add, int max, DoCommandFlags flags)
4096{
4097 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
4098 if (t == nullptr || flags.Test(DoCommandFlag::NoModifyTownRating) ||
4100 (_cheats.magic_bulldozer.value && add < 0)) {
4101 return;
4102 }
4103
4104 int rating = GetRating(t);
4105 if (add < 0) {
4106 if (rating > max) {
4107 rating += add;
4108 if (rating < max) rating = max;
4109 }
4110 } else {
4111 if (rating < max) {
4112 rating += add;
4113 if (rating > max) rating = max;
4114 }
4115 }
4116 if (_town_rating_test) {
4117 _town_test_ratings[t] = rating;
4118 } else {
4120 t->ratings[_current_company] = rating;
4121 SetWindowDirty(WindowClass::TownAuthority, t->index);
4122 }
4123}
4124
4133{
4134 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
4135 if (t == nullptr || !Company::IsValidID(_current_company) ||
4136 _cheats.magic_bulldozer.value || flags.Test(DoCommandFlag::NoTestTownRating)) {
4137 return CommandCost();
4138 }
4139
4140 /* minimum rating needed to be allowed to remove stuff */
4141 static const int needed_rating[][to_underlying(TownRatingCheckType::End)] = {
4142 /* RoadRemove, TunnelBridgeRemove */
4147 };
4148
4149 /* check if you're allowed to remove the road/bridge/tunnel
4150 * owned by a town no removal if rating is lower than ... depends now on
4151 * difficulty setting. Minimum town rating selected by difficulty level
4152 */
4153 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][to_underlying(type)];
4154
4155 if (GetRating(t) < needed) {
4156 return CommandCostWithParam(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS, t->index);
4157 }
4158
4159 return CommandCost();
4160}
4161
4167template <>
4168Town::SuppliedHistory SumHistory(std::span<const Town::SuppliedHistory> history)
4169{
4170 uint64_t production = std::accumulate(std::begin(history), std::end(history), 0, [](uint64_t r, const auto &s) { return r + s.production; });
4171 uint64_t transported = std::accumulate(std::begin(history), std::end(history), 0, [](uint64_t r, const auto &s) { return r + s.transported; });
4172 auto count = std::size(history);
4173 return {.production = ClampTo<uint32_t>(production / count), .transported = ClampTo<uint32_t>(transported / count)};
4174}
4175
4181template <>
4182Town::AcceptedHistory SumHistory(std::span<const Town::AcceptedHistory> history)
4183{
4184 uint64_t accepted = std::accumulate(std::begin(history), std::end(history), 0, [](uint64_t r, const auto &s) { return r + s.accepted; });
4185 auto count = std::size(history);
4186 return {.accepted = ClampTo<uint32_t>(accepted / count)};
4187}
4188
4190static const IntervalTimer<TimerGameEconomy> _economy_towns_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Town}, [](auto)
4191{
4192 for (Town *t : Town::Iterate()) {
4193 /* Check for active town actions and decrement their counters. */
4194 if (t->road_build_months != 0) t->road_build_months--;
4195 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
4196
4197 if (t->exclusive_counter != 0) {
4198 if (--t->exclusive_counter == 0) t->exclusivity = CompanyID::Invalid();
4199 }
4200
4201 /* Check for active failed bribe cooloff periods and decrement them. */
4202 for (const Company *c : Company::Iterate()) {
4203 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
4204 }
4205
4206 UpdateValidHistory(t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);
4207
4208 /* Update cargo statistics. */
4209 for (auto &s : t->supplied) RotateHistory(s.history, t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);
4210 for (auto &a : t->accepted) RotateHistory(a.history, t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);
4211 for (auto &received : t->received) received.NewMonth();
4212
4215
4216 SetWindowDirty(WindowClass::TownView, t->index);
4217 }
4218});
4219
4220static const IntervalTimer<TimerGameEconomy> _economy_towns_yearly({TimerGameEconomy::Trigger::Year, TimerGameEconomy::Priority::Town}, [](auto)
4221{
4222 /* Increment house ages */
4223 for (const auto t : Map::Iterate()) {
4224 if (!IsTileType(t, TileType::House)) continue;
4226 }
4227});
4228
4230static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
4231{
4232 if (AutoslopeEnabled()) {
4233 HouseID house = GetHouseType(tile);
4234 GetHouseNorthPart(house); // modifies house to the ID of the north tile
4235 const HouseSpec *hs = HouseSpec::Get(house);
4236
4237 /* Here we differ from TTDP by checking BuildingFlag::NotSloped */
4238 if (!hs->building_flags.Test(BuildingFlag::NotSloped) && !IsSteepSlope(tileh_new) &&
4239 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
4240 bool allow_terraform = true;
4241
4242 /* Call the autosloping callback per tile, not for the whole building at once. */
4243 house = GetHouseType(tile);
4244 hs = HouseSpec::Get(house);
4246 /* If the callback fails, allow autoslope. */
4247 uint16_t res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
4248 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
4249 }
4250
4252 }
4253 }
4254
4255 return Command<Commands::LandscapeClear>::Do(flags, tile);
4256}
4257
4259extern const TileTypeProcs _tile_type_town_procs = {
4260 .draw_tile_proc = DrawTile_Town,
4261 .get_slope_pixel_z_proc = [](TileIndex tile, uint, uint, bool) { return GetTileMaxPixelZ(tile); },
4262 .clear_tile_proc = ClearTile_Town,
4263 .add_accepted_cargo_proc = AddAcceptedCargo_Town,
4264 .get_tile_desc_proc = GetTileDesc_Town,
4265 .animate_tile_proc = AnimateTile_Town,
4266 .tile_loop_proc = TileLoop_Town,
4267 .add_produced_cargo_proc = AddProducedCargo_Town,
4268 .get_foundation_proc = GetFoundation_Town,
4269 .terraform_tile_proc = TerraformTile_Town,
4270};
4271
4272std::span<const DrawBuildingsTileStruct> GetTownDrawTileData()
4273{
4274 return _town_draw_tile_data;
4275}
Base functions for all AIs.
@ AT_OILRIG
Oilrig airport.
Definition airport.h:38
void AddAnimatedTile(TileIndex tile, bool mark_dirty)
Add the given tile to the animated tile table (if it does not exist yet).
void DeleteAnimatedTile(TileIndex tile, bool immediate)
Stops animation on the given tile.
Tile animation!
@ None
Tile is not animated.
Functions related to autoslope.
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition autoslope.h:65
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Header file for bridges.
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition bridge.h:18
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition bridge_map.h:35
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition bridge_map.h:45
Axis GetBridgeAxis(Tile t)
Get the axis of the bridge that goes over the tile.
Definition bridge_map.h:68
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoLabel CT_FOOD
Cargo label for food.
Definition cargo_type.h:48
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
CargoType GetCargoTypeByLabel(CargoLabel label)
Get cargo assigned to a label.
Definition cargotype.h:268
static const uint TOWN_PRODUCTION_DIVISOR
By what factor divide town production.
Definition cargotype.h:73
TownProductionEffect
Town effect when producing cargo.
Definition cargotype.h:35
@ Mail
Cargo behaves mail-like for production.
Definition cargotype.h:38
@ Passengers
Cargo behaves passenger-like for production.
Definition cargotype.h:37
TownAcceptanceEffect
Town growth effect when delivering cargo.
Definition cargotype.h:21
@ Food
Cargo behaves food/fizzy-drinks-like.
Definition cargotype.h:28
@ Water
Cargo behaves water-like.
Definition cargotype.h:27
@ End
End of town effects.
Definition cargotype.h:29
Cheats _cheats
All the cheats.
Definition cheat.cpp:16
Types related to cheating.
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=CompanyID::Invalid())
Broadcast a new event to all active AIs.
Definition ai_core.cpp:250
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Container for an encoded string, created by GetEncodedString.
Iterate a range of enum values.
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
TimerGameCalendar::Date introduction_date
Introduction date.
Definition road.h:142
RoadTypeFlags flags
Bit mask of road type flags.
Definition road.h:103
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition road.h:118
Generate TileIndices around a center tile or tile area, with increasing distance.
Structure contains cached list of stations nearby.
const StationList & GetStations()
Run a tile loop to find stations around a tile, on demand.
static constexpr TimerGameTick::Ticks TOWN_GROWTH_TICKS
Cycle duration for towns trying to grow (this originates from the size of the town array in TTD).
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr TimerGame< struct Calendar >::Date MAX_DATE
static Month month
Current month (0..11).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
StrongType::Typedef< int32_t, DateTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Date
Map accessors for 'clear' tiles.
@ Rough
Rough mounds (3).
Definition clear_map.h:23
ClearGround GetClearGround(Tile t)
Get the type of clear tile.
Definition clear_map.h:52
CommandFlags GetCommandFlags(Commands cmd)
Get the command flags associated with the given command.
Definition command.cpp:112
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Definition command.cpp:415
Functions related to commands.
CommandCost & ExtractCommandCost(Tret &ret)
Extract the CommandCost from a command proc result.
static constexpr DoCommandFlags CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Auto
don't allow building on structures
@ NoModifyTownRating
do not change town rating
@ NoWater
don't allow building on water
@ Execute
execute the given command
@ NoTestTownRating
town rating does not disallow you from building
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
static constexpr Owner OWNER_DEITY
The object is owned by a superuser / goal script.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
static constexpr Owner OWNER_NONE
The tile has no ownership.
Base for all depots (except hangars).
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
@ Left90
90 degrees left
@ Right90
90 degrees right
DiagDirection
Enumeration for diagonal directions.
@ SW
Southwest.
@ NW
Northwest.
@ End
Used for iterations.
@ SE
Southeast.
Prices _price
Prices and also the fractional part.
Definition economy.cpp:109
bool EconomyIsInRecession()
Is the economy in recession?
uint ScaleByCargoScale(uint num, bool town)
Scale a number by the cargo scale setting.
@ Construction
Construction costs.
@ Other
Other expenses.
@ Terraform
Price for terraforming land, e.g. rising, lowering and flattening.
@ BuildFoundation
Price for building foundation under other constructions e.g. roads, rails, depots,...
@ TownAction
Price for interaction with local authorities.
@ ClearHouse
Price for destroying houses and other town buildings.
@ BuildTown
Price for funding new towns and cities.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
Definition error.h:25
@ Info
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:22
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Base functions for all Games.
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:70
Functions related to world/map generation.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
@ Towns
Generate towns.
Definition genworld.h:62
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
uint8_t HighestSnowLine()
Get the highest possible snow line height, either variable or static.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static const SpriteID SPR_LIFT
Definition sprites.h:1152
void UpdateValidHistory(ValidHistoryMask &valid_history, const HistoryRange &hr, uint cur_month)
Update mask of valid records for a historical data.
Definition history.cpp:25
Functions for storing historical data.
void RotateHistory(HistoryData< T > &history, ValidHistoryMask valid_history, const HistoryRange &hr, uint cur_month)
Rotate historical data.
Types for storing historical data.
@ BuildingIsHistorical
this house will only appear during town generation in random games, thus the historical
Definition house.h:97
@ BuildingIsProtected
towns and AI will not remove this house, while human players will be able to
Definition house.h:98
@ Size1x1
The building is a single tile.
Definition house.h:39
@ Size2x2
The building is 2x2 tiles.
Definition house.h:43
@ IsAnimated
The building uses animation.
Definition house.h:44
@ NotSloped
The building can only be built on flat land; when not set foundations are placed.
Definition house.h:40
@ Size2x1
The building is 2x1 tiles, i.e. wider on the X-axis.
Definition house.h:41
@ IsChurch
The building functions as a church, i.e. only one can be built in a town.
Definition house.h:45
@ IsStadium
The building functions as a stadium, i.e. only one can be built in a town.
Definition house.h:46
@ Size1x2
The building is 1x2 tiles, i.e. wider on the Y-axis.
Definition house.h:42
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition house.h:28
EnumBitSet< BuildingFlag, uint8_t > BuildingFlags
Bitset of BuildingFlag elements.
Definition house.h:50
EnumBitSet< HouseZone, uint16_t > HouseZones
Bitset of HouseZone elements.
Definition house.h:75
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition house.h:25
HouseZone
Concentric rings of zoning around the centre of a town.
Definition house.h:59
@ TownOuterSuburb
Outer suburbs; roads with pavement.
Definition house.h:62
@ ClimateSubarcticAboveSnow
Building can appear in sub-arctic climate above the snow line.
Definition house.h:67
@ ClimateSubarcticBelowSnow
Building can appear in sub-arctic climate below the snow line.
Definition house.h:69
@ TownInnerSuburb
Inner suburbs; roads with pavement and trees.
Definition house.h:63
@ TownOutskirt
Outskirts of a town; roads without pavement.
Definition house.h:61
@ TownEdge
Edge of the town; roads without pavement.
Definition house.h:60
@ TownCentre
Centre of town; roads with pavement and streetlights.
Definition house.h:64
@ ClimateTemperate
Building can appear in temperate climate.
Definition house.h:68
@ ClimateToyland
Building can appear in toyland climate.
Definition house.h:71
@ ClimateSubtropic
Building can appear in subtropical climate.
Definition house.h:70
uint16_t HouseID
OpenTTD ID of house types.
Definition house_type.h:15
Base of all industries.
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
std::tuple< Slope, int > GetFoundationSlope(TileIndex tile)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
const TileTypeProcs _tile_type_town_procs
TileTypeProcs definitions for TileType::Town tiles.
Definition landscape.cpp:57
Functions related to OTTD's landscape.
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:97
Command definitions related to landscape (slopes etc.).
@ Arctic
Landscape with snow levels.
@ Toyland
Landscape with funky industries and vehicles.
@ Tropic
Landscape with distinct rainforests and deserts,.
@ Temperate
Base landscape.
#define Point
Macro that prevents name conflicts between included headers.
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
Definition map.cpp:185
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition map.cpp:228
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:168
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition map.cpp:262
Functions related to maps.
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition map_func.h:474
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition map_func.h:603
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition map_func.h:444
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition map_func.h:615
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:392
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset)
Adds a given offset to a tile.
Definition map_func.h:461
#define RandomTile()
Get a valid random tile.
Definition map_func.h:656
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:574
TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition map_func.h:535
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
@ FakeTowns
Fake town GrfSpecFeature for NewGRF debugging (parent scope).
Definition newgrf.h:107
@ Houses
Houses feature.
Definition newgrf.h:89
@ CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house tile.
@ CBID_HOUSE_CARGO_ACCEPTANCE
Called to decide how much cargo a town building can accept.
@ CBID_HOUSE_AUTOSLOPE
Called to determine if one can alter the ground below a house tile.
@ CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
@ CBID_HOUSE_ALLOW_CONSTRUCTION
Determine whether the house can be built on the specified tile.
@ CBID_HOUSE_ACCEPT_CARGO
Called to determine which cargoes a town building should accept.
@ CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
@ AllowConstruction
decide whether the house can be built on a given tile
@ AcceptCargo
decides accepted types
@ CargoAcceptance
decides amount of cargo acceptance
@ DrawFoundations
decides if default foundations need to be drawn
@ ProduceCargo
custom cargo production
@ Autoslope
decides allowance of autosloping
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
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.
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
GRFConfig * GetGRFConfig(GrfID grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
@ Any
Use first found.
Functions/types related to NewGRF debugging.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town.
uint16_t GetHouseCallback(CallbackID callback, uint32_t param1, uint32_t param2, HouseID house_id, Town *town, TileIndex tile, std::span< int32_t > regs100, bool not_yet_constructed, uint8_t initial_random_bits, CargoTypes watched_cargo_triggers, int view)
Get the result of a house callback.
void InitializeBuildingCounts()
Initialise global building counts and all town building counts.
Functions related to NewGRF houses.
StringID GetGRFStringID(GrfID grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
Definition news_gui.cpp:919
@ General
General news (from towns).
Definition news_type.h:48
@ IndustryOpen
Opening of industries.
Definition news_type.h:36
@ Company
Company news item. (Newspaper with face).
Definition news_type.h:85
@ Normal
Normal news item. (Newspaper with text only).
Definition news_type.h:83
Functions related to objects.
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=nullptr, uint8_t view=0)
Actually build the object.
Base for all objects.
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition object_type.h:20
@ Editor
In the scenario editor.
Definition openttd.h:21
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition rail_type.h:33
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
Definition road.cpp:58
Road specific functions.
@ NoHouses
Bit number for setting this roadtype as not house friendly.
Definition road.h:27
@ TownBuild
Bit number for allowing towns to build this roadtype.
Definition road.h:29
RoadTypes GetMaskForRoadTramType(RoadTramType rtt)
Get the mask for road types of the given RoadTramType.
Definition road.h:185
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:217
bool UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Road related functions.
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition road_func.h:78
Functions used internally by the roads.
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition road_map.cpp:54
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition road_map.h:261
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
Definition road_map.h:290
RoadType GetRoadTypeRoad(Tile t)
Get the road type for RoadTramType being RoadTramType::Road.
Definition road_map.h:152
static bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
Definition road_map.h:100
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition road_map.h:311
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition road_map.h:221
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
Definition road_map.h:576
static bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition road_map.h:90
static bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition road_map.h:58
bool IsRoadOwner(Tile t, RoadTramType rtt, Owner o)
Check if a specific road type is owned by an owner.
Definition road_map.h:278
static constexpr RoadBits ROAD_W
Road at the two western edges.
Definition road_type.h:73
static constexpr RoadBits ROAD_X
Full road along the x-axis (south-west + north-east).
Definition road_type.h:67
EnumBitSet< RoadBit, uint8_t > RoadBits
Bitset of RoadBit elements.
Definition road_type.h:65
static constexpr RoadBits ROAD_E
Road at the two eastern edges.
Definition road_type.h:71
@ SW
South-west part.
Definition road_type.h:59
@ NW
North-west part.
Definition road_type.h:58
@ NE
North-east part.
Definition road_type.h:61
@ SE
South-east part.
Definition road_type.h:60
static constexpr RoadBits ROAD_ALL
Full 4-way crossing.
Definition road_type.h:75
static constexpr RoadBits ROAD_Y
Full road along the y-axis (north-west + south-east).
Definition road_type.h:68
static constexpr RoadBits ROAD_N
Road at the two northern edges.
Definition road_type.h:70
RoadType
The different roadtypes we support.
Definition road_type.h:24
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:29
@ ROADTYPE_ROAD
Basic road type.
Definition road_type.h:26
static constexpr RoadBits ROAD_S
Road at the two southern edges.
Definition road_type.h:72
@ Road
Road type.
Definition road_type.h:39
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:61
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition settings.cpp:62
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height).
Definition slope_func.h:170
static constexpr Slope RemoveHalftileSlope(Slope s)
Removes a halftile slope from a slope.
Definition slope_func.h:70
bool IsSlopeWithOneCornerRaised(Slope s)
Tests if a specific slope has exactly one corner raised.
Definition slope_func.h:98
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition slope_func.h:36
static constexpr Slope RemoveSteepSlope(Slope s)
Removes a steep flag from a slope.
Definition slope_func.h:46
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition slope_func.h:377
Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition slope_func.h:266
Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition slope_func.h:86
Slope
Enumeration for the slope-type.
Definition slope_type.h:53
@ SLOPE_W
the west corner of the tile is raised
Definition slope_type.h:55
@ SLOPE_ELEVATED
bit mask containing all 'simple' slopes
Definition slope_type.h:66
@ SLOPE_E
the east corner of the tile is raised
Definition slope_type.h:57
@ SLOPE_S
the south corner of the tile is raised
Definition slope_type.h:56
@ SLOPE_N
the north corner of the tile is raised
Definition slope_type.h:58
@ SLOPE_SW
south and west corner are raised
Definition slope_type.h:61
@ SLOPE_FLAT
a flat tile
Definition slope_type.h:54
@ SLOPE_STEEP_W
a steep slope falling to east (from west)
Definition slope_type.h:71
@ SLOPE_NE
north and east corner are raised
Definition slope_type.h:63
@ SLOPE_STEEP_E
a steep slope falling to west (from east)
Definition slope_type.h:73
@ SLOPE_SE
south and east corner are raised
Definition slope_type.h:62
@ SLOPE_NW
north and west corner are raised
Definition slope_type.h:60
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
Definition slope_type.h:74
@ SLOPE_STEEP_S
a steep slope falling to north (from south)
Definition slope_type.h:72
Foundation
Enumeration for Foundations.
Definition slope_type.h:119
@ Leveled
The tile is leveled up to a flat slope.
Definition slope_type.h:121
@ None
The tile has no foundation, the slope remains unchanged.
Definition slope_type.h:120
@ Town
Source/destination is a town.
Definition source_type.h:22
Base classes/functions for stations.
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
Functions related to stations.
Declarations for accessing the k-d tree of stations.
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
Axis GetDriveThroughStopAxis(Tile t)
Gets the axis of the drive through stop.
DiagDirection GetBayRoadStopDir(Tile t)
Gets the direction the bay road stop entrance points towards.
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
@ Airport
Station with an airport.
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:261
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:350
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
Owner owner
The owner of this station.
Class for storing amounts of cargo.
Definition cargo_type.h:120
static void InvalidateAllFrom(Source src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Specification of a cargo type.
Definition cargotype.h:76
static EnumIndexArray< std::vector< const CargoSpec * >, TownProductionEffect, TownProductionEffect::End > town_production_cargoes
List of cargo specs for each Town Product Effect.
Definition cargotype.h:242
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition cargotype.h:239
uint32_t build_object_limit
Amount of tiles we can (still) build objects on (times 65536). Also applies to buying land and placin...
T y
Y coordinate.
T x
X coordinate.
T x
X coordinate.
T y
Y coordinate.
This structure is the same for both Industries and Houses.
Definition sprite.h:90
uint8_t draw_proc
This allows to specify a special drawing procedure.
Definition sprite.h:93
Information about GRF, used in the game and (part of it) in savegames.
std::string GetName() const
Get the name of this grf.
GrfID grfid
grfid that introduced this entity.
const struct GRFFile * grffile
grf file that introduced this entity
bool HasGrfFile() const
Test if this entity was introduced by NewGRF.
Stores station stats for a single cargo.
uint8_t rating
Station rating for this cargo.
CargoType accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition house.h:116
SubstituteGRFFileProps grf_prop
Properties related the the grf file.
Definition house.h:122
uint8_t removal_cost
cost multiplier for removing it
Definition house.h:111
uint8_t mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition house.h:114
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition house.h:119
Money GetRemovalCost() const
Get the cost for removing this house.
Definition town_cmd.cpp:237
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:117
TimerGameCalendar::Year max_year
last year it can be built
Definition house.h:109
HouseCallbackMasks callback_mask
Bitmask of house callbacks that have to be called.
Definition house.h:123
uint16_t remove_rating_decrease
rating decrease if removed
Definition house.h:113
uint8_t population
population (Zero on other tiles in multi tile house.)
Definition house.h:110
HouseExtraFlags extra_flags
some more flags
Definition house.h:126
uint8_t cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition house.h:115
HouseID Index() const
Gets the index of this spec.
StringID building_name
building name
Definition house.h:112
uint8_t minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition house.h:130
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
Defines the internal data of a functional industry.
Definition industry.h:64
Town * town
Nearest town.
Definition industry.h:109
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition industry.h:253
static uint ScaleBySize(uint n)
Scales the given value by the map size, where the given value is for a 256 by 256 map.
Definition map_func.h:331
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:366
static uint ScaleByLandProportion(uint n)
Scales the given value by the number of water tiles.
Definition map_func.h:308
static uint Size()
Get the size of the map.
Definition map_func.h:280
An object, such as transmitter, on the map.
Definition object_base.h:23
ObjectType type
Type of the object.
Definition object_base.h:24
Town * town
Town the object is built in.
Definition object_base.h:25
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
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< Town > Iterate(size_t from=0)
static T * Create(Targs &&... args)
static Town * Get(auto index)
static bool CanAllocateItem(size_t n=1)
static bool IsValidID(auto index)
static Company * GetIfValid(auto index)
static constexpr size_t MAX_SIZE
A location from where cargo can come from (or go to).
Definition source_type.h:32
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Station data structure.
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
Definition station.cpp:434
uint16_t subst_id
The id of the entity to replace.
Tile description for the 'land area information' tool.
Definition tile_cmd.h:40
std::optional< std::string > grf
newGRF used for the tile contents
Definition tile_cmd.h:51
StringID str
Description of the tile.
Definition tile_cmd.h:41
std::array< Owner, 4 > owner
Name of the owner(s).
Definition tile_cmd.h:43
uint64_t dparam
Parameter of the str string.
Definition tile_cmd.h:42
std::optional< bool > town_can_upgrade
Whether the town can upgrade this house during town growth.
Definition tile_cmd.h:58
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:34
Slope tileh
Slope of the tile.
Definition tile_cmd.h:35
TileIndex tile
Tile index.
Definition tile_cmd.h:36
Set of callback functions for performing tile operations of a given tile type.
Definition tile_cmd.h:214
uint32_t population
Current population of people.
Definition town.h:54
uint32_t num_houses
Amount of houses.
Definition town.h:53
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition town.h:55
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
Definition town.h:58
std::array< uint32_t, NUM_HOUSE_ZONES > squared_town_zone_radius
UpdateTownRadius updates this given the house count.
Definition town.h:57
Struct holding parameters used to generate town name.
GrfID grfid
newgrf ID (0 if not used)
uint16_t type
town name style
Individual data point for accepted cargo history.
Definition town.h:111
Town data structure.
Definition town.h:64
EncodedString text
General text with additional information.
Definition town.h:137
bool larger_town
if this is a larger town and should grow more quickly
Definition town.h:199
CompanyMask statues
which companies have a statue?
Definition town.h:82
uint16_t time_until_rebuild
time until we rebuild a house
Definition town.h:191
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition town.h:75
TileIndex xy
town center tile
Definition town.h:65
uint8_t fund_buildings_months
fund buildings program in action?
Definition town.h:196
TownLayout layout
town specific road layout
Definition town.h:200
static Town * GetRandom()
Return a random valid town.
Definition town_cmd.cpp:208
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition town.h:74
Town(TownID index, TileIndex tile=INVALID_TILE)
Creates a new town.
Definition town.h:211
GrfID townnamegrfid
NewGRF id that contains the name. O is not used.
Definition town.h:71
uint16_t grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition town.h:193
uint32_t townnameparts
Random number that give unique town name when passed to generator.
Definition town.h:73
TownFlags flags
See TownFlags.
Definition town.h:78
TownCache cache
Container for all cacheable data.
Definition town.h:67
TypedIndexContainer< std::array< uint8_t, MAX_COMPANIES >, CompanyID > unwanted
how many months companies aren't wanted by towns (bribe)
Definition town.h:86
CompanyID exclusivity
which company has exclusivity
Definition town.h:87
void InitializeLayout(TownLayout layout)
Assign the town layout.
Definition town_cmd.cpp:194
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition town.h:202
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:88
void UpdateVirtCoord()
Resize the sign (label) of the town after it changes population.
Definition town_cmd.cpp:381
EnumIndexArray< TransportedCargoStat< uint16_t >, TownAcceptanceEffect, TownAcceptanceEffect::End > received
Cargo statistics about received cargotypes.
Definition town.h:133
CompanyMask have_ratings
which companies have a rating
Definition town.h:85
~Town()
Destroy the town.
Definition town_cmd.cpp:119
TypedIndexContainer< std::array< int16_t, MAX_COMPANIES >, CompanyID > ratings
ratings of each company for this town
Definition town.h:89
uint16_t growth_rate
town growth rate
Definition town.h:194
StationList stations_near
NOSAVE: List of nearby stations.
Definition town.h:189
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool.
Definition town_cmd.cpp:179
uint8_t road_build_months
fund road reconstruction in action?
Definition town.h:197
EnumIndexArray< uint32_t, TownAcceptanceEffect, TownAcceptanceEffect::End > goal
Amount of cargo required for the town to grow.
Definition town.h:134
uint16_t townnametype
The style of the name.
Definition town.h:72
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Representation of a waypoint.
void DeleteSubsidyWith(Source source)
Delete the subsidies associated with a given cargo source type and id.
Definition subsidy.cpp:119
Functions related to subsidies.
Command definitions related to terraforming.
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition tile_map.cpp:94
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition tile_map.cpp:135
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.cpp:115
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition tile_map.h:324
static uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
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
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition tile_map.h:238
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.h:279
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
@ Desert
Tile is desert.
Definition tile_type.h:83
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
@ TunnelBridge
Tunnel entry/exit and bridge heads.
Definition tile_type.h:58
@ Water
Water tile.
Definition tile_type.h:55
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Object
Contains objects such as transmitters and owned land.
Definition tile_type.h:59
@ Industry
Part of an industry.
Definition tile_type.h:57
@ Railway
A tile with railway.
Definition tile_type.h:50
@ Void
Invisible tiles at the SW and SE border.
Definition tile_type.h:56
@ Trees
Tile with one or more trees.
Definition tile_type.h:53
@ House
A house by a town.
Definition tile_type.h:52
@ Road
A tile with road and/or tram tracks.
Definition tile_type.h:51
@ Clear
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition tile_type.h:49
OrthoDiagonalTileArea CreateOrthoDiagonalArea(TileIndex corner1, TileIndex corner2, bool diagonal)
Create an Orthogonal/Diagonal tile area wrapper.
Definition tilearea.cpp:23
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Type for iterating a sprial tile area.
Type for storing the 'area' of something uses on the map.
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Base of the town class.
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount).
Definition town.h:32
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition town.h:274
@ End
End marker.
Definition town.h:277
EnumBitSet< TownFlag, uint8_t > TownFlags
Bitset of TownFlag elements.
Definition town.h:49
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount).
Definition town.h:33
EnumBitSet< TownAction, uint8_t > TownActions
Bitset of TownAction elements.
Definition town.h:310
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition town.h:29
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
TownAction
Town actions of a company.
Definition town.h:297
@ RoadRebuild
Rebuild the roads.
Definition town.h:301
@ Bribe
Try to bribe the council.
Definition town.h:305
@ End
End marker.
Definition town.h:306
@ BuildStatue
Build a statue.
Definition town.h:302
@ BuyRights
Buy exclusive transport rights.
Definition town.h:304
@ FundBuildings
Fund new buildings.
Definition town.h:303
@ HasChurch
There can be only one church by town.
Definition town.h:43
@ CustomGrowth
Growth rate is controlled by GS.
Definition town.h:45
@ HasStadium
There can be only one stadium by town.
Definition town.h:44
@ IsGrowing
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition town.h:42
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition town.h:34
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding road allows to build a house here.
static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
Checks if a house of size 2x2 can be built at this tile.
std::tuple< CommandCost, Money, TownID > CmdFoundTown(DoCommandFlags flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
Create a new town.
void ChangeTownRating(Town *t, int add, int max, DoCommandFlags flags)
Changes town rating of the current company.
HouseZones GetClimateMaskForLandscape()
Get the HouseZones climate mask for the current landscape type.
static bool GrowTownAtRoad(Town *t, TileIndex tile, TownExpandModes modes)
Try to grow a town at a given road tile.
static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes &always_accepted)
Tile callback function signature for obtaining cargo acceptance of a tile.
Definition town_cmd.cpp:820
static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlags flags)
Perform the "small advertising campaign" town action.
static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
Tile callback function signature of the terraforming callback.
static CommandCost TownActionFundBuildings(Town *t, DoCommandFlags flags)
Perform the "fund new buildings" town action.
static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
static CommandCost TownActionBuildStatue(Town *t, DoCommandFlags flags)
Perform a 9x9 tiles circular search from the center of the town in order to find a free tile to place...
static CommandCost TownActionBribe(Town *t, DoCommandFlags flags)
Perform the "bribe" town action.
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
uint GetDefaultTownsForMapSize()
Calculate the number of towns which should be on the map according to the current "town density" newg...
void ClearTownHouse(Town *t, TileIndex tile)
Clear a town house.
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
Get a list of available town authority actions.
static CommandCost TownActionBuyRights(Town *t, DoCommandFlags flags)
Perform the "buy exclusive transport rights" town action.
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
Given a spot on the map (presumed to be a water tile), find a good coastal spot to build a city.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
TownGrowthResult
The possible states of town growth.
@ Continue
The town hasn't grown yet, but try again.
@ Succeed
The town has grown.
@ SearchStopped
There is a reason not to try growing the town now.
static bool CanRoadContinueIntoNextTile(const Town *t, const TileIndex tile, const DiagDirection road_dir)
Checks if a town road can be continued into the next tile.
static bool TryBuildTownHouse(Town *t, TileIndex tile, TownExpandModes modes)
Tries to build a house at this tile.
static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
Updates town grow counter after growth rate change.
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
static bool IsNeighbourRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
static bool _generating_town
Set if a town is being generated.
Definition town_cmd.cpp:92
static void MakeTownHouse(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool is_protected)
Write house information into the map.
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope, TownExpandModes modes)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
static void TileLoop_Town(TileIndex tile)
Tile callback function signature for running periodic tile updates.
Definition town_cmd.cpp:580
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Check if a house can be built here, based on slope, whether there's a bridge above,...
static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
Tile callback function signature for obtaining the produced cargo of a tile.
Definition town_cmd.cpp:723
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile, TownExpandModes modes)
Checks if the current town layout allows building here.
bool GenerateTowns(TownLayout layout, std::optional< uint > number)
Generate a number of towns with a given layout.
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
CommandCost CmdDoTownAction(DoCommandFlags flags, TownID town_id, TownAction action)
Do a town action.
static void TownGenerateCargoBinomial(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the binomial algorithm.
Definition town_cmd.cpp:562
static void UpdateTownRating(Town *t)
Monthly callback to update town and station ratings.
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile, TownExpandModes modes)
Checks if the current town layout allows a 2x2 building here.
static void AdvanceHouseConstruction(TileIndex tile)
Increase the construction stage of a house.
Definition town_cmd.cpp:499
static bool TownCanGrowRoad(TileIndex tile)
Test if town can grow road onto a specific tile.
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
Definition town_cmd.cpp:440
static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
Grows the town with a tunnel.
static std::map< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlags flags)
Tile callback function signature for clearing a tile.
Definition town_cmd.cpp:688
static bool CheckClearTile(TileIndex tile)
Check whether the land can be cleared.
static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlags flags)
Perform the "medium advertising campaign" town action.
static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the original algorithm.
Definition town_cmd.cpp:542
static void ClearMakeHouseTile(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool is_protected)
Clears tile and builds a house or house part.
void UpdateTownMaxPass(Town *t)
Update the maximum amount of monthly passengers and mail for a town, based on its population.
static void ChangePopulation(Town *t, int mod)
Change the town's population as recorded in the town cache, town label, and town directory.
Definition town_cmd.cpp:425
Town::SuppliedHistory SumHistory(std::span< const Town::SuppliedHistory > history)
Sum history for town supplied cargo.
CargoArray GetAcceptedCargoOfHouse(const HouseSpec *hs)
Get accepted cargo of a house prototype.
Definition town_cmd.cpp:831
Town * TryGenerateNamedTownAroundTile(TileIndex target_tile, TownSize size, bool city, TownLayout layout, std::string_view name)
Try to generate a named town around a tile.
static void AddAcceptedCargoSetMask(CargoType cargo, uint amount, CargoArray &acceptance, CargoTypes &always_accepted)
Fill cargo acceptance array and always_accepted mask, if cargo type is valid.
Definition town_cmd.cpp:761
static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
static Town * CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
Create a random town somewhere in the world.
static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
Remove stations from nearby station list if a town is no longer in the catchment area of each.
Definition town_cmd.cpp:454
static bool IsUniqueTownName(std::string_view name)
Verifies this custom name is unique.
uint8_t GetTownActionCost(TownAction action)
Get cost factors for a TownAction.
static const IntervalTimer< TimerGameEconomy > _economy_towns_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Town}, [](auto) { for(Town *t :Town::Iterate()) { if(t->road_build_months !=0) t->road_build_months--;if(t->fund_buildings_months !=0) t->fund_buildings_months--;if(t->exclusive_counter !=0) { if(--t->exclusive_counter==0) t->exclusivity=CompanyID::Invalid();} for(const Company *c :Company::Iterate()) { if(t->unwanted[c->index] > 0) t->unwanted[c->index]--;} UpdateValidHistory(t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);for(auto &s :t->supplied) RotateHistory(s.history, t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);for(auto &a :t->accepted) RotateHistory(a.history, t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);for(auto &received :t->received) received.NewMonth();UpdateTownGrowth(t);UpdateTownRating(t);SetWindowDirty(WindowClass::TownView, t->index);} })
Economy monthly timer for towns.
CommandCost CmdTownSetText(DoCommandFlags flags, TownID town_id, const EncodedString &text)
Set a custom text in the Town window.
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
CommandCost CmdTownGrowthRate(DoCommandFlags flags, TownID town_id, uint16_t growth_rate)
Change the growth rate of the town.
static TownGrowthResult GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1, TownExpandModes modes)
Grows the given town.
static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlags flags)
Perform the "local road reconstruction" town action.
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition town_cmd.cpp:413
CommandCost CmdDeleteTown(DoCommandFlags flags, TownID town_id)
Delete a town (scenario editor or worldgen only).
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Tile callback function signature for getting the foundation of a tile.
Definition town_cmd.cpp:298
static TimerGameCalendar::Date GetTownRoadTypeFirstIntroductionDate()
Get the calendar date of the earliest town-buildable road type.
Definition town_cmd.cpp:963
static void AnimateTile_Town(TileIndex tile)
Tile callback function signature for animating a tile.
Definition town_cmd.cpp:322
CommandCost CmdPlaceHouse(DoCommandFlags flags, TileIndex tile, HouseID house, bool is_protected, bool replace)
Place an individual house.
RoadType GetTownRoadType()
Get the road type that towns should build at this current moment.
Definition town_cmd.cpp:933
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile, ignoring depot and bay road stops.
Definition town_cmd.cpp:921
CommandCost CmdRenameTown(DoCommandFlags flags, TownID town_id, const std::string &text)
Rename a town (server-only).
CommandCost CmdTownCargoGoal(DoCommandFlags flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
Change the cargo goal of a town.
static void GetTileDesc_Town(TileIndex tile, TileDesc &td)
Tile callback function signature for obtaining a tile description.
Definition town_cmd.cpp:840
static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Actually create a town.
CommandCost CheckforTownRating(DoCommandFlags flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
HouseZone GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second, TownExpandModes modes)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
static CommandCost TownCanBePlacedHere(TileIndex tile, bool check_surrounding)
Check if it's possible to place a town on a given tile.
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
Check if a town 'owns' a bridge.
Definition town_cmd.cpp:103
void OnTick_Town()
Iterate through all towns and call their tick handler.
Definition town_cmd.cpp:907
static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlags flags)
Perform the "large advertising campaign" town action.
bool CheckTownRoadTypes()
Check if towns are able to build road.
Definition town_cmd.cpp:983
static bool GrowTown(Town *t, TownExpandModes modes)
Grow the town.
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
static void AdvanceSingleHouseConstruction(TileIndex tile)
Helper function for house construction stage progression.
Definition town_cmd.cpp:476
static void TownTickHandler(Town *t)
Handle the town tick for a single town, by growing the town if desired.
Definition town_cmd.cpp:888
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
static bool _town_rating_test
If true, town rating is in test-mode.
CommandCost CmdTownRating(DoCommandFlags flags, TownID town_id, CompanyID company_id, int16_t rating)
Change the rating of a company in a town.
void UpdateTownRadius(Town *t)
Update the cached town zone radii of a town, based on the number of houses.
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile, TownExpandModes modes)
Grows the town with an extra house.
void AddAcceptedCargoOfHouse(TileIndex tile, HouseID house, const HouseSpec *hs, Town *t, CargoArray &acceptance, CargoTypes &always_accepted)
Determine accepted cargo for a house.
Definition town_cmd.cpp:777
static bool TownAllowedToBuildRoads(TownExpandModes modes)
Check if the town is allowed to build roads.
CommandCost CmdExpandTown(DoCommandFlags flags, TownID town_id, uint32_t grow_amount, TownExpandModes modes)
Expand a town (scenario editor only).
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition town_cmd.cpp:373
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
static RoadBits GenRandomRoadBits()
Generate a random road block.
static bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
Check if a tile where we want to build a multi-tile house has an appropriate max Z.
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlags flags)
Checks whether the local authority allows construction of a new station (rail, road,...
static bool CanFollowRoad(TileIndex tile, DiagDirection dir, TownExpandModes modes)
Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
static void BuildTownHouse(Town *t, TileIndex tile, const HouseSpec *hs, HouseID house, uint8_t random_bits, bool house_completed, bool is_protected)
Build a house at this tile.
static void TownGenerateCargo(Town *t, CargoType cargo, uint amount, StationFinder &stations, bool affected_by_recession)
Generate cargo for a house, scaled by the current economy scale.
Definition town_cmd.cpp:516
static void DrawTile_Town(TileInfo *ti)
Tile callback function signature for drawing a tile and its contents to the screen.
Definition town_cmd.cpp:256
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition town_cmd.cpp:405
CommandCost CmdPlaceHouseArea(DoCommandFlags flags, TileIndex tile, TileIndex start_tile, HouseID house, bool is_protected, bool replace, bool diagonal)
Construct multiple houses in an area.
Command definitions related to towns.
Declarations for accessing the k-d tree of towns.
Sprites to use and how to display them for town tiles.
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition town_land.h:27
void IncrementHouseAge(Tile t)
Increments the age of the house.
Definition town_map.h:259
void HaltLift(Tile t)
Stop the lift of this animated house from moving.
Definition town_map.h:137
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 ResetHouseAge(Tile t)
Sets the age of the house to zero.
Definition town_map.h:248
void MakeHouseTile(Tile t, TownID tid, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool house_protected)
Make the tile a house.
Definition town_map.h:375
void IncHouseConstructionTick(Tile t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits,...
Definition town_map.h:230
uint8_t GetLiftPosition(Tile t)
Get the position of the lift on this animated house.
Definition town_map.h:147
bool IsHousePlayerProtected(Tile t)
Check if a house is protected by a player from removal by towns.
Definition town_map.h:82
void SetLiftDestination(Tile t, uint8_t dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit.
Definition town_map.h:115
TimerGameCalendar::Year GetHouseAge(Tile t)
Get the age of the house.
Definition town_map.h:271
void SetLiftPosition(Tile t, uint8_t pos)
Set the position of the lift on this animated house.
Definition town_map.h:157
uint8_t GetLiftDestination(Tile t)
Get the current destination for this lift.
Definition town_map.h:126
uint8_t GetHouseBuildingStage(Tile t)
House Construction Scheme.
Definition town_map.h:205
TownID GetTownIndex(Tile t)
Get the index of which town this house/street is attached to.
Definition town_map.h:23
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
Definition town_map.h:35
bool LiftHasDestination(Tile t)
Check if the lift of this animated house has a destination.
Definition town_map.h:104
bool IsHouseCompleted(Tile t)
Get the completion of this house.
Definition town_map.h:167
uint8_t GetHouseConstructionTick(Tile t)
Gets the construction stage of a house.
Definition town_map.h:217
static constexpr int RATING_GROWTH_UP_STEP
when a town grows, all companies have rating increased a bit ...
Definition town_type.h:52
static constexpr int RATING_INITIAL
initial rating
Definition town_type.h:44
static constexpr int RATING_ROAD_NEEDED_HOSTILE
"Hostile"
Definition town_type.h:70
@ Original
Original algorithm (quadratic cargo by population).
Definition town_type.h:112
@ Bitcount
Bit-counted algorithm (normal distribution from individual house population).
Definition town_type.h:113
static constexpr int RATING_ROAD_NEEDED_NEUTRAL
"Neutral"
Definition town_type.h:69
TownLayout
Town Layouts.
Definition town_type.h:83
@ Original
Original algorithm (min. 1 distance between roads).
Definition town_type.h:84
@ Random
Random town layout.
Definition town_type.h:89
@ BetterRoads
Extended original algorithm (min. 2 distance between roads).
Definition town_type.h:85
@ End
Number of town layouts.
Definition town_type.h:91
@ Grid2x2
Geometric 2x2 grid algorithm.
Definition town_type.h:86
@ Grid3x3
Geometric 3x3 grid algorithm.
Definition town_type.h:87
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
Definition town_type.h:60
@ CustomLayout
Allowed, with custom town layout.
Definition town_type.h:107
@ Forbidden
Forbidden.
Definition town_type.h:105
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
"Hostile"
Definition town_type.h:62
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
Definition town_type.h:63
static constexpr int RATING_STATION_DOWN_STEP
... but loses for badly serviced stations
Definition town_type.h:55
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
"Neutral"
Definition town_type.h:61
static constexpr int RATING_ROAD_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
Definition town_type.h:68
static constexpr int RATING_STATION_UP_STEP
when a town grows, company gains reputation for all well serviced stations ...
Definition town_type.h:54
TownSize
Supported initial town sizes.
Definition town_type.h:21
@ Large
Large town.
Definition town_type.h:24
@ Random
Random size, bigger than small, smaller than large.
Definition town_type.h:25
@ End
Number of available town sizes.
Definition town_type.h:27
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including '\0'.
Definition town_type.h:116
@ Roads
Allow town to place roads.
Definition town_type.h:97
@ Buildings
Allow town to place buildings.
Definition town_type.h:96
EnumBitSet< TownExpandMode, uint8_t > TownExpandModes
Bitset of TownExpandMode elements.
Definition town_type.h:101
static constexpr int RATING_ROAD_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
Definition town_type.h:71
static constexpr int RATING_GROWTH_MAXIMUM
... up to RATING_MEDIOCRE
Definition town_type.h:53
bool VerifyTownName(uint32_t r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition townname.cpp:101
bool GenerateTownName(Randomizer &randomizer, uint32_t *townnameparts, TownNames *town_names)
Generates valid town name.
Definition townname.cpp:134
Town name generator stuff.
bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
@ Houses
town buildings
@ Road
Transport by road vehicle.
Map accessors for tree tiles.
TreeGround GetTreeGround(Tile t)
Returns the groundtype for tree tiles.
Definition tree_map.h:102
@ Rough
Rough land.
Definition tree_map.h:54
Command definitions related to tunnels and bridges.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int z, const SpriteBounds &bounds, bool transparent, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition viewport.cpp:665
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
Add a child sprite to a parent sprite.
Definition viewport.cpp:827
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:580
Functions related to (drawing on) viewports.
Declarations for accessing the k-d tree of viewports.
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition water_map.h:356
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition water_map.h:194
bool IsSea(Tile t)
Is it a sea water tile?
Definition water_map.h:162
Base of waypoints.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
Window functions not directly related to making/drawing windows.