2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file town_cmd.cpp Handling of town tiles. */
12 #include "road_internal.h" /* Cleaning up road bits */
14 #include "landscape.h"
15 #include "viewport_func.h"
16 #include "viewport_kdtree.h"
17 #include "command_func.h"
19 #include "station_base.h"
20 #include "station_kdtree.h"
21 #include "company_base.h"
22 #include "news_func.h"
26 #include "newgrf_debug.h"
27 #include "newgrf_house.h"
28 #include "newgrf_text.h"
29 #include "autoslope.h"
30 #include "tunnelbridge_map.h"
31 #include "strings_func.h"
32 #include "window_func.h"
33 #include "string_func.h"
34 #include "newgrf_cargo.h"
35 #include "cheat_type.h"
36 #include "animated_tile_func.h"
37 #include "date_func.h"
38 #include "subsidy_func.h"
39 #include "core/pool_func.hpp"
41 #include "town_kdtree.h"
42 #include "townname_func.h"
43 #include "core/random_func.hpp"
44 #include "core/backup_type.hpp"
45 #include "depot_base.h"
46 #include "object_map.h"
47 #include "object_base.h"
49 #include "game/game.hpp"
51 #include "landscape_cmd.h"
53 #include "terraform_cmd.h"
54 #include "tunnelbridge_cmd.h"
56 #include "table/strings.h"
57 #include "table/town_land.h"
59 #include "safeguards.h"
61 /* Initialize the town-pool */
62 TownPool
_town_pool("Town");
63 INSTANTIATE_POOL_METHODS(Town
)
66 TownKdtree
_town_kdtree(&Kdtree_TownXYFunc
);
68 void RebuildTownKdtree()
70 std::vector
<TownID
> townids
;
71 for (const Town
*town
: Town::Iterate()) {
72 townids
.push_back(town
->index
);
74 _town_kdtree
.Build(townids
.begin(), townids
.end());
79 * Check if a town 'owns' a bridge.
80 * Bridges to not directly have an owner, so we check the tiles adjacent to the bridge ends.
81 * If either adjacent tile belongs to the town then it will be assumed that the town built
83 * @param tile Bridge tile to test
84 * @param t Town we are interested in
85 * @return true if town 'owns' a bridge.
87 static bool TestTownOwnsBridge(TileIndex tile
, const Town
*t
)
89 if (!IsTileOwner(tile
, OWNER_TOWN
)) return false;
91 TileIndex adjacent
= tile
+ TileOffsByDiagDir(ReverseDiagDir(GetTunnelBridgeDirection(tile
)));
92 bool town_owned
= IsTileType(adjacent
, MP_ROAD
) && IsTileOwner(adjacent
, OWNER_TOWN
) && GetTownIndex(adjacent
) == t
->index
;
95 /* Or other adjacent road */
96 TileIndex adjacent
= tile
+ TileOffsByDiagDir(ReverseDiagDir(GetTunnelBridgeDirection(GetOtherTunnelBridgeEnd(tile
))));
97 town_owned
= IsTileType(adjacent
, MP_ROAD
) && IsTileOwner(adjacent
, OWNER_TOWN
) && GetTownIndex(adjacent
) == t
->index
;
105 if (CleaningPool()) return;
107 /* Delete town authority window
108 * and remove from list of sorted towns */
109 CloseWindowById(WC_TOWN_VIEW
, this->index
);
112 /* Check no industry is related to us. */
113 for (const Industry
*i
: Industry::Iterate()) {
114 assert(i
->town
!= this);
117 /* ... and no object is related to us. */
118 for (const Object
*o
: Object::Iterate()) {
119 assert(o
->town
!= this);
121 #endif /* WITH_ASSERT */
123 /* Check no tile is related to us. */
124 for (TileIndex tile
= 0; tile
< MapSize(); ++tile
) {
125 switch (GetTileType(tile
)) {
127 assert(GetTownIndex(tile
) != this->index
);
131 assert(!HasTownOwnedRoad(tile
) || GetTownIndex(tile
) != this->index
);
134 case MP_TUNNELBRIDGE
:
135 assert(!TestTownOwnsBridge(tile
, this));
143 /* Clear the persistent storage list. */
144 this->psa_list
.clear();
146 DeleteSubsidyWith(ST_TOWN
, this->index
);
147 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS
, this->index
);
148 CargoPacket::InvalidateAllFrom(ST_TOWN
, this->index
);
149 MarkWholeScreenDirty();
154 * Invalidating of the "nearest town cache" has to be done
155 * after removing item from the pool.
156 * @param index index of deleted item
158 void Town::PostDestructor(size_t index
)
160 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_FORCE_REBUILD
);
161 UpdateNearestTownForRoadTiles(false);
163 /* Give objects a new home! */
164 for (Object
*o
: Object::Iterate()) {
165 if (o
->town
== nullptr) o
->town
= CalcClosestTownFromTile(o
->location
.tile
, UINT_MAX
);
170 * Assigns town layout. If Random, generates one based on TileHash.
172 void Town::InitializeLayout(TownLayout layout
)
174 if (layout
!= TL_RANDOM
) {
175 this->layout
= layout
;
179 this->layout
= static_cast<TownLayout
>(TileHash(TileX(this->xy
), TileY(this->xy
)) % (NUM_TLS
- 1));
183 * Return a random valid town.
184 * @return random town, nullptr if there are no towns
186 /* static */ Town
*Town::GetRandom()
188 if (Town::GetNumItems() == 0) return nullptr;
189 int num
= RandomRange((uint16
)Town::GetNumItems());
190 size_t index
= MAX_UVALUE(size_t);
196 /* Make sure we have a valid town */
197 while (!Town::IsValidID(index
)) {
199 assert(index
< Town::GetPoolSize());
203 return Town::Get(index
);
206 void Town::FillCachedName() const
208 char buf
[MAX_LENGTH_TOWN_NAME_CHARS
* MAX_CHAR_LENGTH
];
209 char *end
= GetTownName(buf
, this, lastof(buf
));
210 this->cached_name
.assign(buf
, end
);
214 * Get the cost for removing this house
215 * @return the cost (inflation corrected etc)
217 Money
HouseSpec::GetRemovalCost() const
219 return (_price
[PR_CLEAR_HOUSE
] * this->removal_cost
) >> 8;
223 static int _grow_town_result
;
225 /* Describe the possible states */
226 enum TownGrowthResult
{
228 GROWTH_SEARCH_STOPPED
= 0
229 // GROWTH_SEARCH_RUNNING >= 1
232 static bool BuildTownHouse(Town
*t
, TileIndex tile
);
233 static Town
*CreateRandomTown(uint attempts
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
);
235 static void TownDrawHouseLift(const TileInfo
*ti
)
237 AddChildSpriteScreen(SPR_LIFT
, PAL_NONE
, 14, 60 - GetLiftPosition(ti
->tile
));
240 typedef void TownDrawTileProc(const TileInfo
*ti
);
241 static TownDrawTileProc
* const _town_draw_tile_procs
[1] = {
246 * Return a random direction
248 * @return a random direction
250 static inline DiagDirection
RandomDiagDir()
252 return (DiagDirection
)(3 & Random());
256 * House Tile drawing handler.
257 * Part of the tile loop process
258 * @param ti TileInfo of the tile to draw
260 static void DrawTile_Town(TileInfo
*ti
)
262 HouseID house_id
= GetHouseType(ti
->tile
);
264 if (house_id
>= NEW_HOUSE_OFFSET
) {
265 /* Houses don't necessarily need new graphics. If they don't have a
266 * spritegroup associated with them, then the sprite for the substitute
267 * house id is drawn instead. */
268 if (HouseSpec::Get(house_id
)->grf_prop
.spritegroup
[0] != nullptr) {
269 DrawNewHouseTile(ti
, house_id
);
272 house_id
= HouseSpec::Get(house_id
)->grf_prop
.subst_id
;
276 /* Retrieve pointer to the draw town tile struct */
277 const DrawBuildingsTileStruct
*dcts
= &_town_draw_tile_data
[house_id
<< 4 | TileHash2Bit(ti
->x
, ti
->y
) << 2 | GetHouseBuildingStage(ti
->tile
)];
279 if (ti
->tileh
!= SLOPE_FLAT
) DrawFoundation(ti
, FOUNDATION_LEVELED
);
281 DrawGroundSprite(dcts
->ground
.sprite
, dcts
->ground
.pal
);
283 /* If houses are invisible, do not draw the upper part */
284 if (IsInvisibilitySet(TO_HOUSES
)) return;
286 /* Add a house on top of the ground? */
287 SpriteID image
= dcts
->building
.sprite
;
289 AddSortableSpriteToDraw(image
, dcts
->building
.pal
,
290 ti
->x
+ dcts
->subtile_x
,
291 ti
->y
+ dcts
->subtile_y
,
296 IsTransparencySet(TO_HOUSES
)
299 if (IsTransparencySet(TO_HOUSES
)) return;
303 int proc
= dcts
->draw_proc
- 1;
305 if (proc
>= 0) _town_draw_tile_procs
[proc
](ti
);
309 static int GetSlopePixelZ_Town(TileIndex tile
, uint x
, uint y
)
311 return GetTileMaxPixelZ(tile
);
314 /** Tile callback routine */
315 static Foundation
GetFoundation_Town(TileIndex tile
, Slope tileh
)
317 HouseID hid
= GetHouseType(tile
);
319 /* For NewGRF house tiles we might not be drawing a foundation. We need to
320 * account for this, as other structures should
321 * draw the wall of the foundation in this case.
323 if (hid
>= NEW_HOUSE_OFFSET
) {
324 const HouseSpec
*hs
= HouseSpec::Get(hid
);
325 if (hs
->grf_prop
.spritegroup
[0] != nullptr && HasBit(hs
->callback_mask
, CBM_HOUSE_DRAW_FOUNDATIONS
)) {
326 uint32 callback_res
= GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS
, 0, 0, hid
, Town::GetByTile(tile
), tile
);
327 if (callback_res
!= CALLBACK_FAILED
&& !ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_DRAW_FOUNDATIONS
, callback_res
)) return FOUNDATION_NONE
;
330 return FlatteningFoundation(tileh
);
334 * Animate a tile for a town
335 * Only certain houses can be animated
336 * The newhouses animation supersedes regular ones
337 * @param tile TileIndex of the house to animate
339 static void AnimateTile_Town(TileIndex tile
)
341 if (GetHouseType(tile
) >= NEW_HOUSE_OFFSET
) {
342 AnimateNewHouseTile(tile
);
346 if (_tick_counter
& 3) return;
348 /* If the house is not one with a lift anymore, then stop this animating.
349 * Not exactly sure when this happens, but probably when a house changes.
350 * Before this was just a return...so it'd leak animated tiles..
351 * That bug seems to have been here since day 1?? */
352 if (!(HouseSpec::Get(GetHouseType(tile
))->building_flags
& BUILDING_IS_ANIMATED
)) {
353 DeleteAnimatedTile(tile
);
357 if (!LiftHasDestination(tile
)) {
360 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
361 * This is due to the fact that the first floor is, in the graphics,
362 * the height of 2 'normal' floors.
363 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
366 } while (i
== 1 || i
* 6 == GetLiftPosition(tile
));
368 SetLiftDestination(tile
, i
);
371 int pos
= GetLiftPosition(tile
);
372 int dest
= GetLiftDestination(tile
) * 6;
373 pos
+= (pos
< dest
) ? 1 : -1;
374 SetLiftPosition(tile
, pos
);
378 DeleteAnimatedTile(tile
);
381 MarkTileDirtyByTile(tile
);
385 * Determines if a town is close to a tile
386 * @param tile TileIndex of the tile to query
387 * @param dist maximum distance to be accepted
388 * @returns true if the tile correspond to the distance criteria
390 static bool IsCloseToTown(TileIndex tile
, uint dist
)
392 if (_town_kdtree
.Count() == 0) return false;
393 Town
*t
= Town::Get(_town_kdtree
.FindNearest(TileX(tile
), TileY(tile
)));
394 return DistanceManhattan(tile
, t
->xy
) < dist
;
398 * Resize the sign(label) of the town after changes in
399 * population (creation or growth or else)
401 void Town::UpdateVirtCoord()
403 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
405 if (this->cache
.sign
.kdtree_valid
) _viewport_sign_kdtree
.Remove(ViewportSignKdtreeItem::MakeTown(this->index
));
407 SetDParam(0, this->index
);
408 SetDParam(1, this->cache
.population
);
409 this->cache
.sign
.UpdatePosition(pt
.x
, pt
.y
- 24 * ZOOM_LVL_BASE
,
410 _settings_client
.gui
.population_in_label
? STR_VIEWPORT_TOWN_POP
: STR_VIEWPORT_TOWN
,
413 _viewport_sign_kdtree
.Insert(ViewportSignKdtreeItem::MakeTown(this->index
));
415 SetWindowDirty(WC_TOWN_VIEW
, this->index
);
418 /** Update the virtual coords needed to draw the town sign for all towns. */
419 void UpdateAllTownVirtCoords()
421 for (Town
*t
: Town::Iterate()) {
422 t
->UpdateVirtCoord();
426 void ClearAllTownCachedNames()
428 for (Town
*t
: Town::Iterate()) {
429 t
->cached_name
.clear();
434 * Change the towns population
435 * @param t Town which population has changed
436 * @param mod population change (can be positive or negative)
438 static void ChangePopulation(Town
*t
, int mod
)
440 t
->cache
.population
+= mod
;
441 InvalidateWindowData(WC_TOWN_VIEW
, t
->index
); // Cargo requirements may appear/vanish for small populations
442 if (_settings_client
.gui
.population_in_label
) t
->UpdateVirtCoord();
444 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_POPULATION_CHANGE
);
448 * Determines the world population
449 * Basically, count population of all towns, one by one
450 * @return uint32 the calculated population of the world
452 uint32
GetWorldPopulation()
455 for (const Town
*t
: Town::Iterate()) pop
+= t
->cache
.population
;
460 * Remove stations from nearby station list if a town is no longer in the catchment area of each.
461 * To improve performance only checks stations that cover the provided house area (doesn't need to contain an actual house).
462 * @param t Town to work on
463 * @param tile Location of house area (north part)
464 * @param flags BuildingFlags containing the size of house area
466 static void RemoveNearbyStations(Town
*t
, TileIndex tile
, BuildingFlags flags
)
468 for (StationList::iterator it
= t
->stations_near
.begin(); it
!= t
->stations_near
.end(); /* incremented inside loop */) {
469 const Station
*st
= *it
;
471 bool covers_area
= st
->TileIsInCatchment(tile
);
472 if (flags
& BUILDING_2_TILES_Y
) covers_area
|= st
->TileIsInCatchment(tile
+ TileDiffXY(0, 1));
473 if (flags
& BUILDING_2_TILES_X
) covers_area
|= st
->TileIsInCatchment(tile
+ TileDiffXY(1, 0));
474 if (flags
& BUILDING_HAS_4_TILES
) covers_area
|= st
->TileIsInCatchment(tile
+ TileDiffXY(1, 1));
476 if (covers_area
&& !st
->CatchmentCoversTown(t
->index
)) {
477 it
= t
->stations_near
.erase(it
);
485 * Helper function for house completion stages progression
486 * @param tile TileIndex of the house (or parts of it) to "grow"
488 static void MakeSingleHouseBigger(TileIndex tile
)
490 assert(IsTileType(tile
, MP_HOUSE
));
492 /* progress in construction stages */
493 IncHouseConstructionTick(tile
);
494 if (GetHouseConstructionTick(tile
) != 0) return;
496 AnimateNewHouseConstruction(tile
);
498 if (IsHouseCompleted(tile
)) {
499 /* Now that construction is complete, we can add the population of the
500 * building to the town. */
501 ChangePopulation(Town::GetByTile(tile
), HouseSpec::Get(GetHouseType(tile
))->population
);
504 MarkTileDirtyByTile(tile
);
508 * Make the house advance in its construction stages until completion
509 * @param tile TileIndex of house
511 static void MakeTownHouseBigger(TileIndex tile
)
513 uint flags
= HouseSpec::Get(GetHouseType(tile
))->building_flags
;
514 if (flags
& BUILDING_HAS_1_TILE
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 0, 0));
515 if (flags
& BUILDING_2_TILES_Y
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 0, 1));
516 if (flags
& BUILDING_2_TILES_X
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 1, 0));
517 if (flags
& BUILDING_HAS_4_TILES
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 1, 1));
521 * Tile callback function.
523 * Periodic tic handler for houses and town
524 * @param tile been asked to do its stuff
526 static void TileLoop_Town(TileIndex tile
)
528 HouseID house_id
= GetHouseType(tile
);
530 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
531 * doesn't exist any more, so don't continue here. */
532 if (house_id
>= NEW_HOUSE_OFFSET
&& !NewHouseTileLoop(tile
)) return;
534 if (!IsHouseCompleted(tile
)) {
535 /* Construction is not completed. See if we can go further in construction*/
536 MakeTownHouseBigger(tile
);
540 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
542 /* If the lift has a destination, it is already an animated tile. */
543 if ((hs
->building_flags
& BUILDING_IS_ANIMATED
) &&
544 house_id
< NEW_HOUSE_OFFSET
&&
545 !LiftHasDestination(tile
) &&
547 AddAnimatedTile(tile
);
550 Town
*t
= Town::GetByTile(tile
);
553 StationFinder
stations(TileArea(tile
, 1, 1));
555 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
556 for (uint i
= 0; i
< 256; i
++) {
557 uint16 callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, r
, house_id
, t
, tile
);
559 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
561 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
562 if (cargo
== CT_INVALID
) continue;
564 uint amt
= GB(callback
, 0, 8);
565 if (amt
== 0) continue;
567 uint moved
= MoveGoodsToStation(cargo
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
569 const CargoSpec
*cs
= CargoSpec::Get(cargo
);
570 t
->supplied
[cs
->Index()].new_max
+= amt
;
571 t
->supplied
[cs
->Index()].new_act
+= moved
;
574 switch (_settings_game
.economy
.town_cargogen_mode
) {
576 /* Original (quadratic) cargo generation algorithm */
577 if (GB(r
, 0, 8) < hs
->population
) {
578 uint amt
= GB(r
, 0, 8) / 8 + 1;
580 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
581 t
->supplied
[CT_PASSENGERS
].new_max
+= amt
;
582 t
->supplied
[CT_PASSENGERS
].new_act
+= MoveGoodsToStation(CT_PASSENGERS
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
585 if (GB(r
, 8, 8) < hs
->mail_generation
) {
586 uint amt
= GB(r
, 8, 8) / 8 + 1;
588 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
589 t
->supplied
[CT_MAIL
].new_max
+= amt
;
590 t
->supplied
[CT_MAIL
].new_act
+= MoveGoodsToStation(CT_MAIL
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
595 /* Binomial distribution per tick, by a series of coin flips */
596 /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
597 * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
598 if (GB(_tick_counter
, 8, 2) == GB(tile
, 0, 2)) {
599 /* Make a bitmask with up to 32 bits set, one for each potential pax */
600 int genmax
= (hs
->population
+ 7) / 8;
601 uint32 genmask
= (genmax
>= 32) ? 0xFFFFFFFF : ((1 << genmax
) - 1);
602 /* Mask random value by potential pax and count number of actual pax */
603 uint amt
= CountBits(r
& genmask
);
604 /* Adjust and apply */
605 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
606 t
->supplied
[CT_PASSENGERS
].new_max
+= amt
;
607 t
->supplied
[CT_PASSENGERS
].new_act
+= MoveGoodsToStation(CT_PASSENGERS
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
609 /* Do the same for mail, with a fresh random */
611 genmax
= (hs
->mail_generation
+ 7) / 8;
612 genmask
= (genmax
>= 32) ? 0xFFFFFFFF : ((1 << genmax
) - 1);
613 amt
= CountBits(r
& genmask
);
614 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
615 t
->supplied
[CT_MAIL
].new_max
+= amt
;
616 t
->supplied
[CT_MAIL
].new_act
+= MoveGoodsToStation(CT_MAIL
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
625 Backup
<CompanyID
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
627 if ((hs
->building_flags
& BUILDING_HAS_1_TILE
) &&
628 HasBit(t
->flags
, TOWN_IS_GROWING
) &&
629 CanDeleteHouse(tile
) &&
630 GetHouseAge(tile
) >= hs
->minimum_life
&&
631 --t
->time_until_rebuild
== 0) {
632 t
->time_until_rebuild
= GB(r
, 16, 8) + 192;
634 ClearTownHouse(t
, tile
);
636 /* Rebuild with another house? */
637 if (GB(r
, 24, 8) >= 12) {
638 /* If we are multi-tile houses, make sure to replace the house
639 * closest to city center. If we do not do this, houses tend to
640 * wander away from roads and other houses. */
641 if (hs
->building_flags
& BUILDING_HAS_2_TILES
) {
642 /* House tiles are always the most north tile. Move the new
643 * house to the south if we are north of the city center. */
644 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
645 int x
= Clamp(grid_pos
.x
, 0, 1);
646 int y
= Clamp(grid_pos
.y
, 0, 1);
648 if (hs
->building_flags
& TILE_SIZE_2x2
) {
649 tile
= TILE_ADDXY(tile
, x
, y
);
650 } else if (hs
->building_flags
& TILE_SIZE_1x2
) {
651 tile
= TILE_ADDXY(tile
, 0, y
);
652 } else if (hs
->building_flags
& TILE_SIZE_2x1
) {
653 tile
= TILE_ADDXY(tile
, x
, 0);
657 BuildTownHouse(t
, tile
);
661 cur_company
.Restore();
664 static CommandCost
ClearTile_Town(TileIndex tile
, DoCommandFlag flags
)
666 if (flags
& DC_AUTO
) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
667 if (!CanDeleteHouse(tile
)) return CMD_ERROR
;
669 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
671 CommandCost
cost(EXPENSES_CONSTRUCTION
);
672 cost
.AddCost(hs
->GetRemovalCost());
674 int rating
= hs
->remove_rating_decrease
;
675 Town
*t
= Town::GetByTile(tile
);
677 if (Company::IsValidID(_current_company
)) {
678 if (rating
> t
->ratings
[_current_company
] && !(flags
& DC_NO_TEST_TOWN_RATING
) &&
679 !_cheats
.magic_bulldozer
.value
&& _settings_game
.difficulty
.town_council_tolerance
!= TOWN_COUNCIL_PERMISSIVE
) {
680 SetDParam(0, t
->index
);
681 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
685 ChangeTownRating(t
, -rating
, RATING_HOUSE_MINIMUM
, flags
);
686 if (flags
& DC_EXEC
) {
687 ClearTownHouse(t
, tile
);
693 static void AddProducedCargo_Town(TileIndex tile
, CargoArray
&produced
)
695 HouseID house_id
= GetHouseType(tile
);
696 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
697 Town
*t
= Town::GetByTile(tile
);
699 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
700 for (uint i
= 0; i
< 256; i
++) {
701 uint16 callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, 0, house_id
, t
, tile
);
703 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
705 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
707 if (cargo
== CT_INVALID
) continue;
711 if (hs
->population
> 0) {
712 produced
[CT_PASSENGERS
]++;
714 if (hs
->mail_generation
> 0) {
720 static inline void AddAcceptedCargoSetMask(CargoID cargo
, uint amount
, CargoArray
&acceptance
, CargoTypes
*always_accepted
)
722 if (cargo
== CT_INVALID
|| amount
== 0) return;
723 acceptance
[cargo
] += amount
;
724 SetBit(*always_accepted
, cargo
);
727 static void AddAcceptedCargo_Town(TileIndex tile
, CargoArray
&acceptance
, CargoTypes
*always_accepted
)
729 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
730 CargoID accepts
[lengthof(hs
->accepts_cargo
)];
732 /* Set the initial accepted cargo types */
733 for (uint8 i
= 0; i
< lengthof(accepts
); i
++) {
734 accepts
[i
] = hs
->accepts_cargo
[i
];
737 /* Check for custom accepted cargo types */
738 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ACCEPT_CARGO
)) {
739 uint16 callback
= GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
740 if (callback
!= CALLBACK_FAILED
) {
741 /* Replace accepted cargo types with translated values from callback */
742 accepts
[0] = GetCargoTranslation(GB(callback
, 0, 5), hs
->grf_prop
.grffile
);
743 accepts
[1] = GetCargoTranslation(GB(callback
, 5, 5), hs
->grf_prop
.grffile
);
744 accepts
[2] = GetCargoTranslation(GB(callback
, 10, 5), hs
->grf_prop
.grffile
);
748 /* Check for custom cargo acceptance */
749 if (HasBit(hs
->callback_mask
, CBM_HOUSE_CARGO_ACCEPTANCE
)) {
750 uint16 callback
= GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
751 if (callback
!= CALLBACK_FAILED
) {
752 AddAcceptedCargoSetMask(accepts
[0], GB(callback
, 0, 4), acceptance
, always_accepted
);
753 AddAcceptedCargoSetMask(accepts
[1], GB(callback
, 4, 4), acceptance
, always_accepted
);
754 if (_settings_game
.game_creation
.landscape
!= LT_TEMPERATE
&& HasBit(callback
, 12)) {
755 /* The 'S' bit indicates food instead of goods */
756 AddAcceptedCargoSetMask(CT_FOOD
, GB(callback
, 8, 4), acceptance
, always_accepted
);
758 AddAcceptedCargoSetMask(accepts
[2], GB(callback
, 8, 4), acceptance
, always_accepted
);
764 /* No custom acceptance, so fill in with the default values */
765 for (uint8 i
= 0; i
< lengthof(accepts
); i
++) {
766 AddAcceptedCargoSetMask(accepts
[i
], hs
->cargo_acceptance
[i
], acceptance
, always_accepted
);
770 static void GetTileDesc_Town(TileIndex tile
, TileDesc
*td
)
772 const HouseID house
= GetHouseType(tile
);
773 const HouseSpec
*hs
= HouseSpec::Get(house
);
774 bool house_completed
= IsHouseCompleted(tile
);
776 td
->str
= hs
->building_name
;
778 uint16 callback_res
= GetHouseCallback(CBID_HOUSE_CUSTOM_NAME
, house_completed
? 1 : 0, 0, house
, Town::GetByTile(tile
), tile
);
779 if (callback_res
!= CALLBACK_FAILED
&& callback_res
!= 0x400) {
780 if (callback_res
> 0x400) {
781 ErrorUnknownCallbackResult(hs
->grf_prop
.grffile
->grfid
, CBID_HOUSE_CUSTOM_NAME
, callback_res
);
783 StringID new_name
= GetGRFStringID(hs
->grf_prop
.grffile
->grfid
, 0xD000 + callback_res
);
784 if (new_name
!= STR_NULL
&& new_name
!= STR_UNDEFINED
) {
790 if (!house_completed
) {
791 SetDParamX(td
->dparam
, 0, td
->str
);
792 td
->str
= STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION
;
795 if (hs
->grf_prop
.grffile
!= nullptr) {
796 const GRFConfig
*gc
= GetGRFConfig(hs
->grf_prop
.grffile
->grfid
);
797 td
->grf
= gc
->GetName();
800 td
->owner
[0] = OWNER_TOWN
;
803 static TrackStatus
GetTileTrackStatus_Town(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
809 static void ChangeTileOwner_Town(TileIndex tile
, Owner old_owner
, Owner new_owner
)
814 static bool GrowTown(Town
*t
);
816 static void TownTickHandler(Town
*t
)
818 if (HasBit(t
->flags
, TOWN_IS_GROWING
)) {
819 int i
= (int)t
->grow_counter
- 1;
824 /* If growth failed wait a bit before retrying */
825 i
= std::min
<uint16
>(t
->growth_rate
, TOWN_GROWTH_TICKS
- 1);
834 if (_game_mode
== GM_EDITOR
) return;
836 for (Town
*t
: Town::Iterate()) {
842 * Return the RoadBits of a tile
844 * @note There are many other functions doing things like that.
845 * @note Needs to be checked for needlessness.
846 * @param tile The tile we want to analyse
847 * @return The roadbits of the given tile
849 static RoadBits
GetTownRoadBits(TileIndex tile
)
851 if (IsRoadDepotTile(tile
) || IsStandardRoadStopTile(tile
)) return ROAD_NONE
;
853 return GetAnyRoadBits(tile
, RTT_ROAD
, true);
856 RoadType
GetTownRoadType(const Town
*t
)
858 RoadType best_rt
= ROADTYPE_ROAD
;
859 const RoadTypeInfo
*best
= nullptr;
860 const uint16 assume_max_speed
= 50;
862 for (RoadType rt
= ROADTYPE_BEGIN
; rt
!= ROADTYPE_END
; rt
++) {
863 if (RoadTypeIsTram(rt
)) continue;
865 const RoadTypeInfo
*rti
= GetRoadTypeInfo(rt
);
867 /* Unused road type. */
868 if (rti
->label
== 0) continue;
870 /* Can town build this road. */
871 if (!HasBit(rti
->flags
, ROTF_TOWN_BUILD
)) continue;
873 /* Not yet introduced at this date. */
874 if (IsInsideMM(rti
->introduction_date
, 0, MAX_DAY
) && rti
->introduction_date
> _date
) continue;
876 if (best
!= nullptr) {
877 if ((rti
->max_speed
== 0 ? assume_max_speed
: rti
->max_speed
) < (best
->max_speed
== 0 ? assume_max_speed
: best
->max_speed
)) continue;
888 * Check for parallel road inside a given distance.
889 * Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
890 * is there a parallel road left or right of it within distance dist_multi?
892 * @param tile current tile
893 * @param dir target direction
894 * @param dist_multi distance multiplayer
895 * @return true if there is a parallel road
897 static bool IsNeighborRoadTile(TileIndex tile
, const DiagDirection dir
, uint dist_multi
)
899 if (!IsValidTile(tile
)) return false;
901 /* Lookup table for the used diff values */
902 const TileIndexDiff tid_lt
[3] = {
903 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90RIGHT
)),
904 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90LEFT
)),
905 TileOffsByDiagDir(ReverseDiagDir(dir
)),
908 dist_multi
= (dist_multi
+ 1) * 4;
909 for (uint pos
= 4; pos
< dist_multi
; pos
++) {
910 /* Go (pos / 4) tiles to the left or the right */
911 TileIndexDiff cur
= tid_lt
[(pos
& 1) ? 0 : 1] * (pos
/ 4);
913 /* Use the current tile as origin, or go one tile backwards */
914 if (pos
& 2) cur
+= tid_lt
[2];
916 /* Test for roadbit parallel to dir and facing towards the middle axis */
917 if (IsValidTile(tile
+ cur
) &&
918 GetTownRoadBits(TILE_ADD(tile
, cur
)) & DiagDirToRoadBits((pos
& 2) ? dir
: ReverseDiagDir(dir
))) return true;
924 * Check if a Road is allowed on a given tile
926 * @param t The current town
927 * @param tile The target tile
928 * @param dir The direction in which we want to extend the town
929 * @return true if it is allowed else false
931 static bool IsRoadAllowedHere(Town
*t
, TileIndex tile
, DiagDirection dir
)
933 if (DistanceFromEdge(tile
) == 0) return false;
935 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
936 if (IsBridgeAbove(tile
) && GetBridgeAxis(tile
) == DiagDirToAxis(dir
)) return false;
938 /* Check if there already is a road at this point? */
939 if (GetTownRoadBits(tile
) == ROAD_NONE
) {
940 /* No, try if we are able to build a road piece there.
941 * If that fails clear the land, and if that fails exit.
942 * This is to make sure that we can build a road here later. */
943 RoadType rt
= GetTownRoadType(t
);
944 if (Command
<CMD_BUILD_ROAD
>::Do(DC_AUTO
| DC_NO_WATER
, tile
, (dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? ROAD_Y
: ROAD_X
, rt
, DRD_NONE
, 0).Failed() &&
945 Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, tile
).Failed()) {
950 Slope cur_slope
= _settings_game
.construction
.build_on_slopes
? GetFoundationSlope(tile
) : GetTileSlope(tile
);
951 bool ret
= !IsNeighborRoadTile(tile
, dir
, t
->layout
== TL_ORIGINAL
? 1 : 2);
952 if (cur_slope
== SLOPE_FLAT
) return ret
;
954 /* If the tile is not a slope in the right direction, then
955 * maybe terraform some. */
956 Slope desired_slope
= (dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? SLOPE_NW
: SLOPE_NE
;
957 if (desired_slope
!= cur_slope
&& ComplementSlope(desired_slope
) != cur_slope
) {
958 if (Chance16(1, 8)) {
959 CommandCost res
= CMD_ERROR
;
960 if (!_generating_world
&& Chance16(1, 10)) {
961 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
962 res
= std::get
<0>(Command
<CMD_TERRAFORM_LAND
>::Do(DC_EXEC
| DC_AUTO
| DC_NO_WATER
,
963 tile
, Chance16(1, 16) ? cur_slope
: cur_slope
^ SLOPE_ELEVATED
, false));
965 if (res
.Failed() && Chance16(1, 3)) {
966 /* We can consider building on the slope, though. */
975 static bool TerraformTownTile(TileIndex tile
, Slope edges
, bool dir
)
977 assert(tile
< MapSize());
979 CommandCost r
= std::get
<0>(Command
<CMD_TERRAFORM_LAND
>::Do(DC_AUTO
| DC_NO_WATER
, tile
, edges
, dir
));
980 if (r
.Failed() || r
.GetCost() >= (_price
[PR_TERRAFORM
] + 2) * 8) return false;
981 Command
<CMD_TERRAFORM_LAND
>::Do(DC_AUTO
| DC_NO_WATER
| DC_EXEC
, tile
, edges
, dir
);
985 static void LevelTownLand(TileIndex tile
)
987 assert(tile
< MapSize());
989 /* Don't terraform if land is plain or if there's a house there. */
990 if (IsTileType(tile
, MP_HOUSE
)) return;
991 Slope tileh
= GetTileSlope(tile
);
992 if (tileh
== SLOPE_FLAT
) return;
994 /* First try up, then down */
995 if (!TerraformTownTile(tile
, ~tileh
& SLOPE_ELEVATED
, true)) {
996 TerraformTownTile(tile
, tileh
& SLOPE_ELEVATED
, false);
1001 * Generate the RoadBits of a grid tile
1003 * @param t current town
1004 * @param tile tile in reference to the town
1005 * @param dir The direction to which we are growing ATM
1006 * @return the RoadBit of the current tile regarding
1007 * the selected town layout
1009 static RoadBits
GetTownRoadGridElement(Town
*t
, TileIndex tile
, DiagDirection dir
)
1011 /* align the grid to the downtown */
1012 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
); // Vector from downtown to the tile
1013 RoadBits rcmd
= ROAD_NONE
;
1015 switch (t
->layout
) {
1016 default: NOT_REACHED();
1019 if ((grid_pos
.x
% 3) == 0) rcmd
|= ROAD_Y
;
1020 if ((grid_pos
.y
% 3) == 0) rcmd
|= ROAD_X
;
1024 if ((grid_pos
.x
% 4) == 0) rcmd
|= ROAD_Y
;
1025 if ((grid_pos
.y
% 4) == 0) rcmd
|= ROAD_X
;
1029 /* Optimise only X-junctions */
1030 if (rcmd
!= ROAD_ALL
) return rcmd
;
1032 RoadBits rb_template
;
1034 switch (GetTileSlope(tile
)) {
1035 default: rb_template
= ROAD_ALL
; break;
1036 case SLOPE_W
: rb_template
= ROAD_NW
| ROAD_SW
; break;
1037 case SLOPE_SW
: rb_template
= ROAD_Y
| ROAD_SW
; break;
1038 case SLOPE_S
: rb_template
= ROAD_SW
| ROAD_SE
; break;
1039 case SLOPE_SE
: rb_template
= ROAD_X
| ROAD_SE
; break;
1040 case SLOPE_E
: rb_template
= ROAD_SE
| ROAD_NE
; break;
1041 case SLOPE_NE
: rb_template
= ROAD_Y
| ROAD_NE
; break;
1042 case SLOPE_N
: rb_template
= ROAD_NE
| ROAD_NW
; break;
1043 case SLOPE_NW
: rb_template
= ROAD_X
| ROAD_NW
; break;
1048 rb_template
= ROAD_NONE
;
1052 /* Stop if the template is compatible to the growth dir */
1053 if (DiagDirToRoadBits(ReverseDiagDir(dir
)) & rb_template
) return rb_template
;
1054 /* If not generate a straight road in the direction of the growth */
1055 return DiagDirToRoadBits(dir
) | DiagDirToRoadBits(ReverseDiagDir(dir
));
1059 * Grows the town with an extra house.
1060 * Check if there are enough neighbor house tiles
1061 * next to the current tile. If there are enough
1062 * add another house.
1064 * @param t The current town
1065 * @param tile The target tile for the extra house
1066 * @return true if an extra house has been added
1068 static bool GrowTownWithExtraHouse(Town
*t
, TileIndex tile
)
1070 /* We can't look further than that. */
1071 if (DistanceFromEdge(tile
) == 0) return false;
1073 uint counter
= 0; // counts the house neighbor tiles
1075 /* Check the tiles E,N,W and S of the current tile for houses */
1076 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
< DIAGDIR_END
; dir
++) {
1077 /* Count both void and house tiles for checking whether there
1078 * are enough houses in the area. This to make it likely that
1079 * houses get build up to the edge of the map. */
1080 switch (GetTileType(TileAddByDiagDir(tile
, dir
))) {
1090 /* If there are enough neighbors stop here */
1092 if (BuildTownHouse(t
, tile
)) {
1093 _grow_town_result
= GROWTH_SUCCEED
;
1103 * Grows the town with a road piece.
1105 * @param t The current town
1106 * @param tile The current tile
1107 * @param rcmd The RoadBits we want to build on the tile
1108 * @return true if the RoadBits have been added else false
1110 static bool GrowTownWithRoad(const Town
*t
, TileIndex tile
, RoadBits rcmd
)
1112 RoadType rt
= GetTownRoadType(t
);
1113 if (Command
<CMD_BUILD_ROAD
>::Do(DC_EXEC
| DC_AUTO
| DC_NO_WATER
, tile
, rcmd
, rt
, DRD_NONE
, t
->index
).Succeeded()) {
1114 _grow_town_result
= GROWTH_SUCCEED
;
1121 * Checks if a town road can be continued into the next tile.
1122 * Road vehicle stations, bridges, and tunnels are fine, as long as they are facing the right direction.
1124 * @param t The current town
1125 * @param tile The tile where the road would be built
1126 * @param road_dir The direction of the road
1127 * @return true if the road can be continued, else false
1129 static bool CanRoadContinueIntoNextTile(const Town
*t
, const TileIndex tile
, const DiagDirection road_dir
)
1131 const int delta
= TileOffsByDiagDir(road_dir
); // +1 tile in the direction of the road
1132 TileIndex next_tile
= tile
+ delta
; // The tile beyond which must be connectable to the target tile
1133 RoadBits rcmd
= DiagDirToRoadBits(ReverseDiagDir(road_dir
));
1134 RoadType rt
= GetTownRoadType(t
);
1136 /* Before we try anything, make sure the tile is on the map and not the void. */
1137 if (!IsValidTile(next_tile
)) return false;
1139 /* If the next tile is a bridge or tunnel, allow if it's continuing in the same direction. */
1140 if (IsTileType(next_tile
, MP_TUNNELBRIDGE
)) {
1141 return GetTunnelBridgeTransportType(next_tile
) == TRANSPORT_ROAD
&& GetTunnelBridgeDirection(next_tile
) == road_dir
;
1144 /* If the next tile is a station, allow if it's a road station facing the proper direction. Otherwise return false. */
1145 if (IsTileType(next_tile
, MP_STATION
)) {
1146 /* If the next tile is a road station, allow if it can be entered by the new tunnel/bridge, otherwise disallow. */
1147 return IsRoadStop(next_tile
) && (GetRoadStopDir(next_tile
) == ReverseDiagDir(road_dir
) || (IsDriveThroughStopTile(next_tile
) && GetRoadStopDir(next_tile
) == road_dir
));
1150 /* If the next tile is a road depot, allow if it's facing the right way. */
1151 if (IsTileType(next_tile
, MP_ROAD
)) {
1152 return IsRoadDepot(next_tile
) && GetRoadDepotDirection(next_tile
) == ReverseDiagDir(road_dir
);
1155 /* If the next tile is a railroad track, check if towns are allowed to build level crossings.
1156 * If level crossing are not allowed, reject the construction. Else allow DoCommand to determine if the rail track is buildable. */
1157 if (IsTileType(next_tile
, MP_RAILWAY
) && !_settings_game
.economy
.allow_town_level_crossings
) return false;
1159 /* If a road tile can be built, the construction is allowed. */
1160 return Command
<CMD_BUILD_ROAD
>::Do(DC_AUTO
| DC_NO_WATER
, next_tile
, rcmd
, rt
, DRD_NONE
, t
->index
).Succeeded();
1164 * Grows the town with a bridge.
1165 * At first we check if a bridge is reasonable.
1166 * If so we check if we are able to build it.
1168 * @param t The current town
1169 * @param tile The current tile
1170 * @param bridge_dir The valid direction in which to grow a bridge
1171 * @return true if a bridge has been build else false
1173 static bool GrowTownWithBridge(const Town
*t
, const TileIndex tile
, const DiagDirection bridge_dir
)
1175 assert(bridge_dir
< DIAGDIR_END
);
1177 const Slope slope
= GetTileSlope(tile
);
1179 /* Make sure the direction is compatible with the slope.
1180 * Well we check if the slope has an up bit set in the
1181 * reverse direction. */
1182 if (slope
!= SLOPE_FLAT
&& slope
& InclinedSlope(bridge_dir
)) return false;
1184 /* Assure that the bridge is connectable to the start side */
1185 if (!(GetTownRoadBits(TileAddByDiagDir(tile
, ReverseDiagDir(bridge_dir
))) & DiagDirToRoadBits(bridge_dir
))) return false;
1187 /* We are in the right direction */
1188 uint bridge_length
= 0; // This value stores the length of the possible bridge
1189 TileIndex bridge_tile
= tile
; // Used to store the other waterside
1191 const int delta
= TileOffsByDiagDir(bridge_dir
);
1193 /* To prevent really small towns from building disproportionately
1194 * long bridges, make the max a function of its population. */
1195 const uint TOWN_BRIDGE_LENGTH_CAP
= 11;
1196 uint base_bridge_length
= 5;
1197 uint max_bridge_length
= std::min(t
->cache
.population
/ 1000 + base_bridge_length
, TOWN_BRIDGE_LENGTH_CAP
);
1199 if (slope
== SLOPE_FLAT
) {
1200 /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1202 if (bridge_length
++ >= base_bridge_length
) {
1203 /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1206 bridge_tile
+= delta
;
1207 } while (IsValidTile(bridge_tile
) && ((IsWaterTile(bridge_tile
) && !IsSea(bridge_tile
)) || IsPlainRailTile(bridge_tile
) || (IsNormalRoadTile(bridge_tile
) && GetDisallowedRoadDirections(bridge_tile
) != DRD_NONE
)));
1210 if (bridge_length
++ >= max_bridge_length
) {
1211 /* Ensure the bridge is not longer than the max allowed length. */
1214 bridge_tile
+= delta
;
1215 } while (IsValidTile(bridge_tile
) && (IsWaterTile(bridge_tile
) || IsPlainRailTile(bridge_tile
) || (IsNormalRoadTile(bridge_tile
) && GetDisallowedRoadDirections(bridge_tile
) != DRD_NONE
)));
1218 /* Don't allow a bridge where the start and end tiles are adjacent with no span between. */
1219 if (bridge_length
== 1) return false;
1221 /* Make sure the road can be continued past the bridge. At this point, bridge_tile holds the end tile of the bridge. */
1222 if (!CanRoadContinueIntoNextTile(t
, bridge_tile
, bridge_dir
)) return false;
1224 for (uint8 times
= 0; times
<= 22; times
++) {
1225 byte bridge_type
= RandomRange(MAX_BRIDGES
- 1);
1227 /* Can we actually build the bridge? */
1228 RoadType rt
= GetTownRoadType(t
);
1229 if (Command
<CMD_BUILD_BRIDGE
>::Do(CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_BRIDGE
>()), tile
, bridge_tile
, TRANSPORT_ROAD
, bridge_type
, rt
).Succeeded()) {
1230 Command
<CMD_BUILD_BRIDGE
>::Do(DC_EXEC
| CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_BRIDGE
>()), tile
, bridge_tile
, TRANSPORT_ROAD
, bridge_type
, rt
);
1231 _grow_town_result
= GROWTH_SUCCEED
;
1235 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1240 * Grows the town with a tunnel.
1241 * First we check if a tunnel is reasonable.
1242 * If so we check if we are able to build it.
1244 * @param t The current town
1245 * @param tile The current tile
1246 * @param tunnel_dir The valid direction in which to grow a tunnel
1247 * @return true if a tunnel has been built, else false
1249 static bool GrowTownWithTunnel(const Town
*t
, const TileIndex tile
, const DiagDirection tunnel_dir
)
1251 assert(tunnel_dir
< DIAGDIR_END
);
1253 Slope slope
= GetTileSlope(tile
);
1255 /* Only consider building a tunnel if the starting tile is sloped properly. */
1256 if (slope
!= InclinedSlope(tunnel_dir
)) return false;
1258 /* Assure that the tunnel is connectable to the start side */
1259 if (!(GetTownRoadBits(TileAddByDiagDir(tile
, ReverseDiagDir(tunnel_dir
))) & DiagDirToRoadBits(tunnel_dir
))) return false;
1261 const int delta
= TileOffsByDiagDir(tunnel_dir
);
1262 int max_tunnel_length
= 0;
1264 /* There are two conditions for building tunnels: Under a mountain and under an obstruction. */
1265 if (CanRoadContinueIntoNextTile(t
, tile
, tunnel_dir
)) {
1266 /* 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. */
1267 TileIndex slope_tile
= tile
;
1268 for (uint8 tiles
= 0; tiles
< 4; tiles
++) {
1269 if (!IsValidTile(slope_tile
)) return false;
1270 slope
= GetTileSlope(slope_tile
);
1271 if (slope
!= InclinedSlope(tunnel_dir
) && !IsSteepSlope(slope
) && !IsSlopeWithOneCornerRaised(slope
)) return false;
1272 slope_tile
+= delta
;
1275 /* More population means longer tunnels, but make sure we can at least cover the smallest mountain which neccesitates tunneling. */
1276 max_tunnel_length
= (t
->cache
.population
/ 1000) + 7;
1278 /* When tunneling under an obstruction, the length limit is 5, enough to tunnel under a four-track railway. */
1279 max_tunnel_length
= 5;
1282 uint8 tunnel_length
= 0;
1283 TileIndex tunnel_tile
= tile
; // Iteratator to store the other end tile of the tunnel.
1285 /* Find the end tile of the tunnel for length and continuation checks. */
1287 if (tunnel_length
++ >= max_tunnel_length
) return false;
1288 tunnel_tile
+= delta
;
1289 /* The tunnel ends when start and end tiles are the same height. */
1290 } while (IsValidTile(tunnel_tile
) && GetTileZ(tile
) != GetTileZ(tunnel_tile
));
1292 /* Don't allow a tunnel where the start and end tiles are adjacent. */
1293 if (tunnel_length
== 1) return false;
1295 /* Make sure the road can be continued past the tunnel. At this point, tunnel_tile holds the end tile of the tunnel. */
1296 if (!CanRoadContinueIntoNextTile(t
, tunnel_tile
, tunnel_dir
)) return false;
1298 /* Attempt to build the tunnel. Return false if it fails to let the town build a road instead. */
1299 RoadType rt
= GetTownRoadType(t
);
1300 if (Command
<CMD_BUILD_TUNNEL
>::Do(CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_TUNNEL
>()), tile
, TRANSPORT_ROAD
, rt
).Succeeded()) {
1301 Command
<CMD_BUILD_TUNNEL
>::Do(DC_EXEC
| CommandFlagsToDCFlags(GetCommandFlags
<CMD_BUILD_TUNNEL
>()), tile
, TRANSPORT_ROAD
, rt
);
1302 _grow_town_result
= GROWTH_SUCCEED
;
1310 * Checks whether at least one surrounding roads allows to build a house here
1312 * @param t the tile where the house will be built
1313 * @return true if at least one surrounding roadtype allows building houses here
1315 static inline bool RoadTypesAllowHouseHere(TileIndex t
)
1317 static const TileIndexDiffC tiles
[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1320 for (const TileIndexDiffC
*ptr
= tiles
; ptr
!= endof(tiles
); ++ptr
) {
1321 TileIndex cur_tile
= t
+ ToTileIndexDiff(*ptr
);
1322 if (!IsValidTile(cur_tile
)) continue;
1324 if (!(IsTileType(cur_tile
, MP_ROAD
) || IsTileType(cur_tile
, MP_STATION
))) continue;
1327 RoadType road_rt
= GetRoadTypeRoad(cur_tile
);
1328 RoadType tram_rt
= GetRoadTypeTram(cur_tile
);
1329 if (road_rt
!= INVALID_ROADTYPE
&& !HasBit(GetRoadTypeInfo(road_rt
)->flags
, ROTF_NO_HOUSES
)) return true;
1330 if (tram_rt
!= INVALID_ROADTYPE
&& !HasBit(GetRoadTypeInfo(tram_rt
)->flags
, ROTF_NO_HOUSES
)) return true;
1333 /* If no road was found surrounding the tile we can allow building the house since there is
1334 * nothing which forbids it, if a road was found but the execution reached this point, then
1335 * all the found roads don't allow houses to be built */
1340 * Grows the given town.
1341 * There are at the moment 3 possible way's for
1342 * the town expansion:
1343 * @li Generate a random tile and check if there is a road allowed
1345 * @li TL_BETTER_ROADS
1346 * @li Check if the town geometry allows a road and which one
1349 * @li Forbid roads, only build houses
1351 * @param tile_ptr The current tile
1352 * @param cur_rb The current tiles RoadBits
1353 * @param target_dir The target road dir
1354 * @param t1 The current town
1356 static void GrowTownInTile(TileIndex
*tile_ptr
, RoadBits cur_rb
, DiagDirection target_dir
, Town
*t1
)
1358 RoadBits rcmd
= ROAD_NONE
; // RoadBits for the road construction command
1359 TileIndex tile
= *tile_ptr
; // The main tile on which we base our growth
1361 assert(tile
< MapSize());
1363 if (cur_rb
== ROAD_NONE
) {
1364 /* Tile has no road. First reset the status counter
1365 * to say that this is the last iteration. */
1366 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1368 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return;
1369 if (!_settings_game
.economy
.allow_town_level_crossings
&& IsTileType(tile
, MP_RAILWAY
)) return;
1371 /* Remove hills etc */
1372 if (!_settings_game
.construction
.build_on_slopes
|| Chance16(1, 6)) LevelTownLand(tile
);
1374 /* Is a road allowed here? */
1375 switch (t1
->layout
) {
1376 default: NOT_REACHED();
1380 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1381 if (rcmd
== ROAD_NONE
) return;
1384 case TL_BETTER_ROADS
:
1386 if (!IsRoadAllowedHere(t1
, tile
, target_dir
)) return;
1388 DiagDirection source_dir
= ReverseDiagDir(target_dir
);
1390 if (Chance16(1, 4)) {
1391 /* Randomize a new target dir */
1392 do target_dir
= RandomDiagDir(); while (target_dir
== source_dir
);
1395 if (!IsRoadAllowedHere(t1
, TileAddByDiagDir(tile
, target_dir
), target_dir
)) {
1396 /* A road is not allowed to continue the randomized road,
1397 * return if the road we're trying to build is curved. */
1398 if (target_dir
!= ReverseDiagDir(source_dir
)) return;
1400 /* Return if neither side of the new road is a house */
1401 if (!IsTileType(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90RIGHT
)), MP_HOUSE
) &&
1402 !IsTileType(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90LEFT
)), MP_HOUSE
)) {
1406 /* That means that the road is only allowed if there is a house
1407 * at any side of the new road. */
1410 rcmd
= DiagDirToRoadBits(target_dir
) | DiagDirToRoadBits(source_dir
);
1414 } else if (target_dir
< DIAGDIR_END
&& !(cur_rb
& DiagDirToRoadBits(ReverseDiagDir(target_dir
)))) {
1415 /* Continue building on a partial road.
1416 * Should be always OK, so we only generate
1417 * the fitting RoadBits */
1418 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1420 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return;
1422 switch (t1
->layout
) {
1423 default: NOT_REACHED();
1427 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1430 case TL_BETTER_ROADS
:
1432 rcmd
= DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1436 bool allow_house
= true; // Value which decides if we want to construct a house
1438 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1439 * it is the starting tile. Half the time, we stay on this side then.*/
1440 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1441 if (GetTunnelBridgeTransportType(tile
) == TRANSPORT_ROAD
&& (target_dir
!= DIAGDIR_END
|| Chance16(1, 2))) {
1442 *tile_ptr
= GetOtherTunnelBridgeEnd(tile
);
1447 /* Possibly extend the road in a direction.
1448 * Randomize a direction and if it has a road, bail out. */
1449 target_dir
= RandomDiagDir();
1450 RoadBits target_rb
= DiagDirToRoadBits(target_dir
);
1451 TileIndex house_tile
; // position of a possible house
1453 if (cur_rb
& target_rb
) {
1454 /* If it's a road turn possibly build a house in a corner.
1455 * Use intersection with straight road as an indicator
1456 * that we randomed corner house position.
1457 * A turn (and we check for that later) always has only
1458 * one common bit with a straight road so it has the same
1459 * chance to be chosen as the house on the side of a road.
1461 if ((cur_rb
& ROAD_X
) != target_rb
) return;
1463 /* Check whether it is a turn and if so determine
1464 * position of the corner tile */
1467 house_tile
= TileAddByDir(tile
, DIR_S
);
1470 house_tile
= TileAddByDir(tile
, DIR_N
);
1473 house_tile
= TileAddByDir(tile
, DIR_W
);
1476 house_tile
= TileAddByDir(tile
, DIR_E
);
1479 return; // not a turn
1481 target_dir
= DIAGDIR_END
;
1483 house_tile
= TileAddByDiagDir(tile
, target_dir
);
1486 /* Don't walk into water. */
1487 if (HasTileWaterGround(house_tile
)) return;
1489 if (!IsValidTile(house_tile
)) return;
1491 if (target_dir
!= DIAGDIR_END
&& (_settings_game
.economy
.allow_town_roads
|| _generating_world
)) {
1492 switch (t1
->layout
) {
1493 default: NOT_REACHED();
1495 case TL_3X3_GRID
: // Use 2x2 grid afterwards!
1496 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1500 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1501 allow_house
= (rcmd
& target_rb
) == ROAD_NONE
;
1504 case TL_BETTER_ROADS
: // Use original afterwards!
1505 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1509 /* Allow a house at the edge. 60% chance or
1510 * always ok if no road allowed. */
1512 allow_house
= (!IsRoadAllowedHere(t1
, house_tile
, target_dir
) || Chance16(6, 10));
1517 allow_house
&= RoadTypesAllowHouseHere(house_tile
);
1520 /* Build a house, but not if there already is a house there. */
1521 if (!IsTileType(house_tile
, MP_HOUSE
)) {
1522 /* Level the land if possible */
1523 if (Chance16(1, 6)) LevelTownLand(house_tile
);
1525 /* And build a house.
1526 * Set result to -1 if we managed to build it. */
1527 if (BuildTownHouse(t1
, house_tile
)) {
1528 _grow_town_result
= GROWTH_SUCCEED
;
1534 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1537 /* Return if a water tile */
1538 if (HasTileWaterGround(tile
)) return;
1540 /* Make the roads look nicer */
1541 rcmd
= CleanUpRoadBits(tile
, rcmd
);
1542 if (rcmd
== ROAD_NONE
) return;
1544 /* Only use the target direction for bridges and tunnels to ensure they're connected.
1545 * The target_dir is as computed previously according to town layout, so
1546 * it will match it perfectly. */
1547 if (GrowTownWithBridge(t1
, tile
, target_dir
)) return;
1548 if (GrowTownWithTunnel(t1
, tile
, target_dir
)) return;
1550 GrowTownWithRoad(t1
, tile
, rcmd
);
1554 * Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
1555 * This only checks trivial but often cases.
1556 * @param tile Start tile for road.
1557 * @param dir Direction for road to follow or build.
1558 * @return true If road is or can be connected in the specified direction.
1560 static bool CanFollowRoad(TileIndex tile
, DiagDirection dir
)
1562 TileIndex target_tile
= tile
+ TileOffsByDiagDir(dir
);
1563 if (!IsValidTile(target_tile
)) return false;
1564 if (HasTileWaterGround(target_tile
)) return false;
1566 RoadBits target_rb
= GetTownRoadBits(target_tile
);
1567 if (_settings_game
.economy
.allow_town_roads
|| _generating_world
) {
1568 /* Check whether a road connection exists or can be build. */
1569 switch (GetTileType(target_tile
)) {
1571 return target_rb
!= ROAD_NONE
;
1574 return IsDriveThroughStopTile(target_tile
);
1576 case MP_TUNNELBRIDGE
:
1577 return GetTunnelBridgeTransportType(target_tile
) == TRANSPORT_ROAD
;
1585 /* Checked for void and water earlier */
1589 /* Check whether a road connection already exists,
1590 * and it leads somewhere else. */
1591 RoadBits back_rb
= DiagDirToRoadBits(ReverseDiagDir(dir
));
1592 return (target_rb
& back_rb
) != 0 && (target_rb
& ~back_rb
) != 0;
1597 * Returns "growth" if a house was built, or no if the build failed.
1598 * @param t town to inquiry
1599 * @param tile to inquiry
1600 * @return true if town expansion was possible
1602 static bool GrowTownAtRoad(Town
*t
, TileIndex tile
)
1605 * @see GrowTownInTile Check the else if
1607 DiagDirection target_dir
= DIAGDIR_END
; // The direction in which we want to extend the town
1609 assert(tile
< MapSize());
1611 /* Number of times to search.
1612 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1613 * them a little handicap. */
1614 switch (t
->layout
) {
1615 case TL_BETTER_ROADS
:
1616 _grow_town_result
= 10 + t
->cache
.num_houses
* 2 / 9;
1621 _grow_town_result
= 10 + t
->cache
.num_houses
* 1 / 9;
1625 _grow_town_result
= 10 + t
->cache
.num_houses
* 4 / 9;
1630 RoadBits cur_rb
= GetTownRoadBits(tile
); // The RoadBits of the current tile
1632 /* Try to grow the town from this point */
1633 GrowTownInTile(&tile
, cur_rb
, target_dir
, t
);
1634 if (_grow_town_result
== GROWTH_SUCCEED
) return true;
1636 /* Exclude the source position from the bitmask
1637 * and return if no more road blocks available */
1638 if (IsValidDiagDirection(target_dir
)) cur_rb
&= ~DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1639 if (cur_rb
== ROAD_NONE
) return false;
1641 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1642 /* Only build in the direction away from the tunnel or bridge. */
1643 target_dir
= ReverseDiagDir(GetTunnelBridgeDirection(tile
));
1645 /* Select a random bit from the blockmask, walk a step
1646 * and continue the search from there. */
1648 if (cur_rb
== ROAD_NONE
) return false;
1649 RoadBits target_bits
;
1651 target_dir
= RandomDiagDir();
1652 target_bits
= DiagDirToRoadBits(target_dir
);
1653 } while (!(cur_rb
& target_bits
));
1654 cur_rb
&= ~target_bits
;
1655 } while (!CanFollowRoad(tile
, target_dir
));
1657 tile
= TileAddByDiagDir(tile
, target_dir
);
1659 if (IsTileType(tile
, MP_ROAD
) && !IsRoadDepot(tile
) && HasTileRoadType(tile
, RTT_ROAD
)) {
1660 /* Don't allow building over roads of other cities */
1661 if (IsRoadOwner(tile
, RTT_ROAD
, OWNER_TOWN
) && Town::GetByTile(tile
) != t
) {
1663 } else if (IsRoadOwner(tile
, RTT_ROAD
, OWNER_NONE
) && _game_mode
== GM_EDITOR
) {
1664 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1665 * owner :) (happy happy happy road now) */
1666 SetRoadOwner(tile
, RTT_ROAD
, OWNER_TOWN
);
1667 SetTownIndex(tile
, t
->index
);
1671 /* Max number of times is checked. */
1672 } while (--_grow_town_result
>= 0);
1678 * Generate a random road block.
1679 * The probability of a straight road
1680 * is somewhat higher than a curved.
1682 * @return A RoadBits value with 2 bits set
1684 static RoadBits
GenRandomRoadBits()
1686 uint32 r
= Random();
1687 uint a
= GB(r
, 0, 2);
1688 uint b
= GB(r
, 8, 2);
1690 return (RoadBits
)((ROAD_NW
<< a
) + (ROAD_NW
<< b
));
1695 * @param t town to grow
1696 * @return true iff something (house, road, bridge, ...) was built
1698 static bool GrowTown(Town
*t
)
1700 static const TileIndexDiffC _town_coord_mod
[] = {
1716 /* Current "company" is a town */
1717 Backup
<CompanyID
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
1719 TileIndex tile
= t
->xy
; // The tile we are working with ATM
1721 /* Find a road that we can base the construction on. */
1722 const TileIndexDiffC
*ptr
;
1723 for (ptr
= _town_coord_mod
; ptr
!= endof(_town_coord_mod
); ++ptr
) {
1724 if (GetTownRoadBits(tile
) != ROAD_NONE
) {
1725 bool success
= GrowTownAtRoad(t
, tile
);
1726 cur_company
.Restore();
1729 tile
= TILE_ADD(tile
, ToTileIndexDiff(*ptr
));
1732 /* No road available, try to build a random road block by
1733 * clearing some land and then building a road there. */
1734 if (_settings_game
.economy
.allow_town_roads
|| _generating_world
) {
1736 for (ptr
= _town_coord_mod
; ptr
!= endof(_town_coord_mod
); ++ptr
) {
1737 /* Only work with plain land that not already has a house */
1738 if (!IsTileType(tile
, MP_HOUSE
) && IsTileFlat(tile
)) {
1739 if (Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, tile
).Succeeded()) {
1740 RoadType rt
= GetTownRoadType(t
);
1741 Command
<CMD_BUILD_ROAD
>::Do(DC_EXEC
| DC_AUTO
, tile
, GenRandomRoadBits(), rt
, DRD_NONE
, t
->index
);
1742 cur_company
.Restore();
1746 tile
= TILE_ADD(tile
, ToTileIndexDiff(*ptr
));
1750 cur_company
.Restore();
1754 void UpdateTownRadius(Town
*t
)
1756 static const uint32 _town_squared_town_zone_radius_data
[23][5] = {
1757 { 4, 0, 0, 0, 0}, // 0
1762 { 64, 0, 4, 0, 0}, // 20
1767 { 81, 0, 16, 0, 4}, // 40
1769 { 81, 36, 25, 0, 9},
1770 { 81, 36, 25, 16, 9},
1771 { 81, 49, 0, 25, 9},
1772 { 81, 64, 0, 25, 9}, // 60
1773 { 81, 64, 0, 36, 9},
1774 { 81, 64, 0, 36, 16},
1775 {100, 81, 0, 49, 16},
1776 {100, 81, 0, 49, 25},
1777 {121, 81, 0, 49, 25}, // 80
1778 {121, 81, 0, 49, 25},
1779 {121, 81, 0, 49, 36}, // 88
1782 if (t
->cache
.num_houses
< 92) {
1783 memcpy(t
->cache
.squared_town_zone_radius
, _town_squared_town_zone_radius_data
[t
->cache
.num_houses
/ 4], sizeof(t
->cache
.squared_town_zone_radius
));
1785 int mass
= t
->cache
.num_houses
/ 8;
1786 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1787 * The offsets are to make sure the radii do not decrease in size when going from the table
1788 * to the calculated value.*/
1789 t
->cache
.squared_town_zone_radius
[0] = mass
* 15 - 40;
1790 t
->cache
.squared_town_zone_radius
[1] = mass
* 9 - 15;
1791 t
->cache
.squared_town_zone_radius
[2] = 0;
1792 t
->cache
.squared_town_zone_radius
[3] = mass
* 5 - 5;
1793 t
->cache
.squared_town_zone_radius
[4] = mass
* 3 + 5;
1797 void UpdateTownMaxPass(Town
*t
)
1799 t
->supplied
[CT_PASSENGERS
].old_max
= t
->cache
.population
>> 3;
1800 t
->supplied
[CT_MAIL
].old_max
= t
->cache
.population
>> 4;
1803 static void UpdateTownGrowthRate(Town
*t
);
1804 static void UpdateTownGrowth(Town
*t
);
1807 * Does the actual town creation.
1810 * @param tile Where to put it
1811 * @param townnameparts The town name
1812 * @param size Parameter for size determination
1813 * @param city whether to build a city or town
1814 * @param layout the (road) layout of the town
1815 * @param manual was the town placed manually?
1817 static void DoCreateTown(Town
*t
, TileIndex tile
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
, bool manual
)
1820 t
->cache
.num_houses
= 0;
1821 t
->time_until_rebuild
= 10;
1822 UpdateTownRadius(t
);
1824 t
->cache
.population
= 0;
1825 /* Spread growth across ticks so even if there are many
1826 * similar towns they're unlikely to grow all in one tick */
1827 t
->grow_counter
= t
->index
% TOWN_GROWTH_TICKS
;
1828 t
->growth_rate
= TownTicksToGameTicks(250);
1829 t
->show_zone
= false;
1831 _town_kdtree
.Insert(t
->index
);
1833 /* Set the default cargo requirement for town growth */
1834 switch (_settings_game
.game_creation
.landscape
) {
1836 if (FindFirstCargoWithTownEffect(TE_FOOD
) != nullptr) t
->goal
[TE_FOOD
] = TOWN_GROWTH_WINTER
;
1840 if (FindFirstCargoWithTownEffect(TE_FOOD
) != nullptr) t
->goal
[TE_FOOD
] = TOWN_GROWTH_DESERT
;
1841 if (FindFirstCargoWithTownEffect(TE_WATER
) != nullptr) t
->goal
[TE_WATER
] = TOWN_GROWTH_DESERT
;
1845 t
->fund_buildings_months
= 0;
1847 for (uint i
= 0; i
!= MAX_COMPANIES
; i
++) t
->ratings
[i
] = RATING_INITIAL
;
1849 t
->have_ratings
= 0;
1850 t
->exclusivity
= INVALID_COMPANY
;
1851 t
->exclusive_counter
= 0;
1855 TownNameParams
tnp(_settings_game
.game_creation
.town_name
);
1856 t
->townnamegrfid
= tnp
.grfid
;
1857 t
->townnametype
= tnp
.type
;
1859 t
->townnameparts
= townnameparts
;
1861 t
->UpdateVirtCoord();
1862 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_FORCE_REBUILD
);
1864 t
->InitializeLayout(layout
);
1866 t
->larger_town
= city
;
1868 int x
= (int)size
* 16 + 3;
1869 if (size
== TSZ_RANDOM
) x
= (Random() & 0xF) + 8;
1870 /* Don't create huge cities when founding town in-game */
1871 if (city
&& (!manual
|| _game_mode
== GM_EDITOR
)) x
*= _settings_game
.economy
.initial_city_size
;
1873 t
->cache
.num_houses
+= x
;
1874 UpdateTownRadius(t
);
1881 t
->cache
.num_houses
-= x
;
1882 UpdateTownRadius(t
);
1883 UpdateTownGrowthRate(t
);
1884 UpdateTownMaxPass(t
);
1885 UpdateAirportsNoise();
1889 * Checks if it's possible to place a town at given tile
1890 * @param tile tile to check
1891 * @return error value or zero cost
1893 static CommandCost
TownCanBePlacedHere(TileIndex tile
)
1895 /* Check if too close to the edge of map */
1896 if (DistanceFromEdge(tile
) < 12) {
1897 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
);
1900 /* Check distance to all other towns. */
1901 if (IsCloseToTown(tile
, 20)) {
1902 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN
);
1905 /* Can only build on clear flat areas, possibly with trees. */
1906 if ((!IsTileType(tile
, MP_CLEAR
) && !IsTileType(tile
, MP_TREES
)) || !IsTileFlat(tile
)) {
1907 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
1910 return CommandCost(EXPENSES_OTHER
);
1914 * Verifies this custom name is unique. Only custom names are checked.
1915 * @param name name to check
1916 * @return is this name unique?
1918 static bool IsUniqueTownName(const std::string
&name
)
1920 for (const Town
*t
: Town::Iterate()) {
1921 if (!t
->name
.empty() && t
->name
== name
) return false;
1928 * Create a new town.
1929 * @param flags type of operation
1930 * @param tile coordinates where town is built
1931 * @param size size of the town (@see TownSize)
1932 * @param city true iff it should be a city
1933 * @param layout town road layout (@see TownLayout)
1934 * @param random_location use random location (randomize \c tile )
1935 * @param townnameparts town name parts
1936 * @param text Custom name for the town. If empty, the town name parts will be used.
1937 * @return the cost of this operation or an error
1939 std::tuple
<CommandCost
, Money
, TownID
> CmdFoundTown(DoCommandFlag flags
, TileIndex tile
, TownSize size
, bool city
, TownLayout layout
, bool random_location
, uint32 townnameparts
, const std::string
&text
)
1941 TownNameParams
par(_settings_game
.game_creation
.town_name
);
1943 if (size
>= TSZ_END
) return { CMD_ERROR
, 0, INVALID_TOWN
};
1944 if (layout
>= NUM_TLS
) return { CMD_ERROR
, 0, INVALID_TOWN
};
1946 /* Some things are allowed only in the scenario editor and for game scripts. */
1947 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) {
1948 if (_settings_game
.economy
.found_town
== TF_FORBIDDEN
) return { CMD_ERROR
, 0, INVALID_TOWN
};
1949 if (size
== TSZ_LARGE
) return { CMD_ERROR
, 0, INVALID_TOWN
};
1950 if (random_location
) return { CMD_ERROR
, 0, INVALID_TOWN
};
1951 if (_settings_game
.economy
.found_town
!= TF_CUSTOM_LAYOUT
&& layout
!= _settings_game
.economy
.town_layout
) {
1952 return { CMD_ERROR
, 0, INVALID_TOWN
};
1954 } else if (_current_company
== OWNER_DEITY
&& random_location
) {
1955 /* Random parameter is not allowed for Game Scripts. */
1956 return { CMD_ERROR
, 0, INVALID_TOWN
};
1960 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1961 if (!VerifyTownName(townnameparts
, &par
)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE
), 0, INVALID_TOWN
};
1963 /* If name is not empty, it has to be unique custom name */
1964 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return { CMD_ERROR
, 0, INVALID_TOWN
};
1965 if (!IsUniqueTownName(text
)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE
), 0, INVALID_TOWN
};
1968 /* Allocate town struct */
1969 if (!Town::CanAllocateItem()) return { CommandCost(STR_ERROR_TOO_MANY_TOWNS
), 0, INVALID_TOWN
};
1971 if (!random_location
) {
1972 CommandCost ret
= TownCanBePlacedHere(tile
);
1973 if (ret
.Failed()) return { ret
, 0, INVALID_TOWN
};
1976 static const byte price_mult
[][TSZ_RANDOM
+ 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1977 /* multidimensional arrays have to have defined length of non-first dimension */
1978 static_assert(lengthof(price_mult
[0]) == 4);
1980 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_BUILD_TOWN
]);
1981 byte mult
= price_mult
[city
][size
];
1983 cost
.MultiplyCost(mult
);
1985 /* Create the town */
1986 TownID new_town
= INVALID_TOWN
;
1987 if (flags
& DC_EXEC
) {
1988 if (cost
.GetCost() > GetAvailableMoneyForCommand()) {
1989 return { CommandCost(EXPENSES_OTHER
), cost
.GetCost(), INVALID_TOWN
};
1992 Backup
<bool> old_generating_world(_generating_world
, true, FILE_LINE
);
1993 UpdateNearestTownForRoadTiles(true);
1995 if (random_location
) {
1996 t
= CreateRandomTown(20, townnameparts
, size
, city
, layout
);
1998 cost
= CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN
);
2000 new_town
= t
->index
;
2004 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, true);
2006 UpdateNearestTownForRoadTiles(false);
2007 old_generating_world
.Restore();
2009 if (t
!= nullptr && !text
.empty()) {
2011 t
->UpdateVirtCoord();
2014 if (_game_mode
!= GM_EDITOR
) {
2015 /* 't' can't be nullptr since 'random' is false outside scenedit */
2016 assert(!random_location
);
2018 if (_current_company
== OWNER_DEITY
) {
2019 SetDParam(0, t
->index
);
2020 AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED
, NT_INDUSTRY_OPEN
, tile
);
2022 SetDParam(0, _current_company
);
2023 NewsStringData
*company_name
= new NewsStringData(GetString(STR_COMPANY_NAME
));
2025 SetDParamStr(0, company_name
->string
);
2026 SetDParam(1, t
->index
);
2028 AddTileNewsItem(STR_NEWS_NEW_TOWN
, NT_INDUSTRY_OPEN
, tile
, company_name
);
2030 AI::BroadcastNewEvent(new ScriptEventTownFounded(t
->index
));
2031 Game::NewEvent(new ScriptEventTownFounded(t
->index
));
2034 return { cost
, 0, new_town
};
2038 * Towns must all be placed on the same grid or when they eventually
2039 * interpenetrate their road networks will not mesh nicely; this
2040 * function adjusts a tile so that it aligns properly.
2042 * @param tile the tile to start at
2043 * @param layout which town layout algo is in effect
2044 * @return the adjusted tile
2046 static TileIndex
AlignTileToGrid(TileIndex tile
, TownLayout layout
)
2049 case TL_2X2_GRID
: return TileXY(TileX(tile
) - TileX(tile
) % 3, TileY(tile
) - TileY(tile
) % 3);
2050 case TL_3X3_GRID
: return TileXY(TileX(tile
) & ~3, TileY(tile
) & ~3);
2051 default: return tile
;
2056 * Towns must all be placed on the same grid or when they eventually
2057 * interpenetrate their road networks will not mesh nicely; this
2058 * function tells you if a tile is properly aligned.
2060 * @param tile the tile to start at
2061 * @param layout which town layout algo is in effect
2062 * @return true if the tile is in the correct location
2064 static bool IsTileAlignedToGrid(TileIndex tile
, TownLayout layout
)
2067 case TL_2X2_GRID
: return TileX(tile
) % 3 == 0 && TileY(tile
) % 3 == 0;
2068 case TL_3X3_GRID
: return TileX(tile
) % 4 == 0 && TileY(tile
) % 4 == 0;
2069 default: return true;
2074 * Used as the user_data for FindFurthestFromWater
2077 TileIndex tile
; ///< holds the tile that was found
2078 uint max_dist
; ///< holds the distance that tile is from the water
2079 TownLayout layout
; ///< tells us what kind of town we're building
2083 * CircularTileSearch callback; finds the tile furthest from any
2084 * water. slightly bit tricky, since it has to do a search of its own
2085 * in order to find the distance to the water from each square in the
2088 * Also, this never returns true, because it needs to take into
2089 * account all locations being searched before it knows which is the
2092 * @param tile Start looking from this tile
2093 * @param user_data Storage area for data that must last across calls;
2094 * must be a pointer to struct SpotData
2096 * @return always false
2098 static bool FindFurthestFromWater(TileIndex tile
, void *user_data
)
2100 SpotData
*sp
= (SpotData
*)user_data
;
2101 uint dist
= GetClosestWaterDistance(tile
, true);
2103 if (IsTileType(tile
, MP_CLEAR
) &&
2105 IsTileAlignedToGrid(tile
, sp
->layout
) &&
2106 dist
> sp
->max_dist
) {
2108 sp
->max_dist
= dist
;
2115 * CircularTileSearch callback; finds the nearest land tile
2117 * @param tile Start looking from this tile
2118 * @param user_data not used
2120 static bool FindNearestEmptyLand(TileIndex tile
, void *user_data
)
2122 return IsTileType(tile
, MP_CLEAR
);
2126 * Given a spot on the map (presumed to be a water tile), find a good
2127 * coastal spot to build a city. We don't want to build too close to
2128 * the edge if we can help it (since that retards city growth) hence
2129 * the search within a search within a search. O(n*m^2), where n is
2130 * how far to search for land, and m is how far inland to look for a
2133 * @param tile Start looking from this spot.
2134 * @param layout the road layout to search for
2135 * @return tile that was found
2137 static TileIndex
FindNearestGoodCoastalTownSpot(TileIndex tile
, TownLayout layout
)
2139 SpotData sp
= { INVALID_TILE
, 0, layout
};
2141 TileIndex coast
= tile
;
2142 if (CircularTileSearch(&coast
, 40, FindNearestEmptyLand
, nullptr)) {
2143 CircularTileSearch(&coast
, 10, FindFurthestFromWater
, &sp
);
2147 /* if we get here just give up */
2148 return INVALID_TILE
;
2151 static Town
*CreateRandomTown(uint attempts
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
)
2153 assert(_game_mode
== GM_EDITOR
|| _generating_world
); // These are the preconditions for CMD_DELETE_TOWN
2155 if (!Town::CanAllocateItem()) return nullptr;
2158 /* Generate a tile index not too close from the edge */
2159 TileIndex tile
= AlignTileToGrid(RandomTile(), layout
);
2161 /* if we tried to place the town on water, slide it over onto
2162 * the nearest likely-looking spot */
2163 if (IsTileType(tile
, MP_WATER
)) {
2164 tile
= FindNearestGoodCoastalTownSpot(tile
, layout
);
2165 if (tile
== INVALID_TILE
) continue;
2168 /* Make sure town can be placed here */
2169 if (TownCanBePlacedHere(tile
).Failed()) continue;
2171 /* Allocate a town struct */
2172 Town
*t
= new Town(tile
);
2174 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, false);
2176 /* if the population is still 0 at the point, then the
2177 * placement is so bad it couldn't grow at all */
2178 if (t
->cache
.population
> 0) return t
;
2180 Backup
<CompanyID
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
2181 [[maybe_unused
]] CommandCost rc
= Command
<CMD_DELETE_TOWN
>::Do(DC_EXEC
, t
->index
);
2182 cur_company
.Restore();
2183 assert(rc
.Succeeded());
2185 /* We already know that we can allocate a single town when
2186 * entering this function. However, we create and delete
2187 * a town which "resets" the allocation checks. As such we
2188 * need to check again when assertions are enabled. */
2189 assert(Town::CanAllocateItem());
2190 } while (--attempts
!= 0);
2195 static const byte _num_initial_towns
[4] = {5, 11, 23, 46}; // very low, low, normal, high
2198 * This function will generate a certain amount of towns, with a certain layout
2199 * It can be called from the scenario editor (i.e.: generate Random Towns)
2200 * as well as from world creation.
2201 * @param layout which towns will be set to, when created
2202 * @return true if towns have been successfully created
2204 bool GenerateTowns(TownLayout layout
)
2206 uint current_number
= 0;
2207 uint difficulty
= (_game_mode
!= GM_EDITOR
) ? _settings_game
.difficulty
.number_towns
: 0;
2208 uint total
= (difficulty
== (uint
)CUSTOM_TOWN_NUMBER_DIFFICULTY
) ? _settings_game
.game_creation
.custom_town_number
: ScaleByMapSize(_num_initial_towns
[difficulty
] + (Random() & 7));
2209 total
= std::min
<uint
>(TownPool::MAX_SIZE
, total
);
2210 uint32 townnameparts
;
2211 TownNames town_names
;
2213 SetGeneratingWorldProgress(GWP_TOWN
, total
);
2215 /* First attempt will be made at creating the suggested number of towns.
2216 * Note that this is really a suggested value, not a required one.
2217 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2219 bool city
= (_settings_game
.economy
.larger_towns
!= 0 && Chance16(1, _settings_game
.economy
.larger_towns
));
2220 IncreaseGeneratingWorldProgress(GWP_TOWN
);
2221 /* Get a unique name for the town. */
2222 if (!GenerateTownName(&townnameparts
, &town_names
)) continue;
2223 /* try 20 times to create a random-sized town for the first loop. */
2224 if (CreateRandomTown(20, townnameparts
, TSZ_RANDOM
, city
, layout
) != nullptr) current_number
++; // If creation was successful, raise a flag.
2229 /* Build the town k-d tree again to make sure it's well balanced */
2230 RebuildTownKdtree();
2232 if (current_number
!= 0) return true;
2234 /* If current_number is still zero at this point, it means that not a single town has been created.
2235 * So give it a last try, but now more aggressive */
2236 if (GenerateTownName(&townnameparts
) &&
2237 CreateRandomTown(10000, townnameparts
, TSZ_RANDOM
, _settings_game
.economy
.larger_towns
!= 0, layout
) != nullptr) {
2241 /* If there are no towns at all and we are generating new game, bail out */
2242 if (Town::GetNumItems() == 0 && _game_mode
!= GM_EDITOR
) {
2243 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN
, INVALID_STRING_ID
, WL_CRITICAL
);
2246 return false; // we are still without a town? we failed, simply
2251 * Returns the bit corresponding to the town zone of the specified tile
2252 * @param t Town on which town zone is to be found
2253 * @param tile TileIndex where town zone needs to be found
2254 * @return the bit position of the given zone, as defined in HouseZones
2256 HouseZonesBits
GetTownRadiusGroup(const Town
*t
, TileIndex tile
)
2258 uint dist
= DistanceSquare(tile
, t
->xy
);
2260 if (t
->fund_buildings_months
&& dist
<= 25) return HZB_TOWN_CENTRE
;
2262 HouseZonesBits smallest
= HZB_TOWN_EDGE
;
2263 for (HouseZonesBits i
= HZB_BEGIN
; i
< HZB_END
; i
++) {
2264 if (dist
< t
->cache
.squared_town_zone_radius
[i
]) smallest
= i
;
2271 * Clears tile and builds a house or house part.
2272 * @param tile tile index
2273 * @param t The town to clear the house for
2274 * @param counter of construction step
2275 * @param stage of construction (used for drawing)
2276 * @param type of house. Index into house specs array
2277 * @param random_bits required for newgrf houses
2278 * @pre house can be built here
2280 static inline void ClearMakeHouseTile(TileIndex tile
, Town
*t
, byte counter
, byte stage
, HouseID type
, byte random_bits
)
2282 [[maybe_unused
]] CommandCost cc
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_EXEC
| DC_AUTO
| DC_NO_WATER
, tile
);
2283 assert(cc
.Succeeded());
2285 IncreaseBuildingCount(t
, type
);
2286 MakeHouseTile(tile
, t
->index
, counter
, stage
, type
, random_bits
);
2287 if (HouseSpec::Get(type
)->building_flags
& BUILDING_IS_ANIMATED
) AddAnimatedTile(tile
);
2289 MarkTileDirtyByTile(tile
);
2294 * Write house information into the map. For houses > 1 tile, all tiles are marked.
2295 * @param t tile index
2296 * @param town The town related to this house
2297 * @param counter of construction step
2298 * @param stage of construction (used for drawing)
2299 * @param type of house. Index into house specs array
2300 * @param random_bits required for newgrf houses
2301 * @pre house can be built here
2303 static void MakeTownHouse(TileIndex t
, Town
*town
, byte counter
, byte stage
, HouseID type
, byte random_bits
)
2305 BuildingFlags size
= HouseSpec::Get(type
)->building_flags
;
2307 ClearMakeHouseTile(t
, town
, counter
, stage
, type
, random_bits
);
2308 if (size
& BUILDING_2_TILES_Y
) ClearMakeHouseTile(t
+ TileDiffXY(0, 1), town
, counter
, stage
, ++type
, random_bits
);
2309 if (size
& BUILDING_2_TILES_X
) ClearMakeHouseTile(t
+ TileDiffXY(1, 0), town
, counter
, stage
, ++type
, random_bits
);
2310 if (size
& BUILDING_HAS_4_TILES
) ClearMakeHouseTile(t
+ TileDiffXY(1, 1), town
, counter
, stage
, ++type
, random_bits
);
2312 ForAllStationsAroundTiles(TileArea(t
, (size
& BUILDING_2_TILES_X
) ? 2 : 1, (size
& BUILDING_2_TILES_Y
) ? 2 : 1), [town
](Station
*st
, TileIndex tile
) {
2313 town
->stations_near
.insert(st
);
2320 * Checks if a house can be built here. Important is slope, bridge above
2321 * and ability to clear the land.
2322 * @param tile tile to check
2323 * @param noslope are slopes (foundations) allowed?
2324 * @return true iff house can be built here
2326 static inline bool CanBuildHouseHere(TileIndex tile
, bool noslope
)
2328 /* cannot build on these slopes... */
2329 Slope slope
= GetTileSlope(tile
);
2330 if ((noslope
&& slope
!= SLOPE_FLAT
) || IsSteepSlope(slope
)) return false;
2332 /* at least one RoadTypes allow building the house here? */
2333 if (!RoadTypesAllowHouseHere(tile
)) return false;
2335 /* building under a bridge? */
2336 if (IsBridgeAbove(tile
)) return false;
2338 /* can we clear the land? */
2339 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_AUTO
| DC_NO_WATER
, tile
).Succeeded();
2344 * Checks if a house can be built at this tile, must have the same max z as parameter.
2345 * @param tile tile to check
2346 * @param z max z of this tile so more parts of a house are at the same height (with foundation)
2347 * @param noslope are slopes (foundations) allowed?
2348 * @return true iff house can be built here
2349 * @see CanBuildHouseHere()
2351 static inline bool CheckBuildHouseSameZ(TileIndex tile
, int z
, bool noslope
)
2353 if (!CanBuildHouseHere(tile
, noslope
)) return false;
2355 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2356 if (GetTileMaxZ(tile
) != z
) return false;
2363 * Checks if a house of size 2x2 can be built at this tile
2364 * @param tile tile, N corner
2365 * @param z maximum tile z so all tile have the same max z
2366 * @param noslope are slopes (foundations) allowed?
2367 * @return true iff house can be built
2368 * @see CheckBuildHouseSameZ()
2370 static bool CheckFree2x2Area(TileIndex tile
, int z
, bool noslope
)
2372 /* we need to check this tile too because we can be at different tile now */
2373 if (!CheckBuildHouseSameZ(tile
, z
, noslope
)) return false;
2375 for (DiagDirection d
= DIAGDIR_SE
; d
< DIAGDIR_END
; d
++) {
2376 tile
+= TileOffsByDiagDir(d
);
2377 if (!CheckBuildHouseSameZ(tile
, z
, noslope
)) return false;
2385 * Checks if current town layout allows building here
2387 * @param tile tile to check
2388 * @return true iff town layout allows building here
2391 static inline bool TownLayoutAllowsHouseHere(Town
*t
, TileIndex tile
)
2393 /* Allow towns everywhere when we don't build roads */
2394 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return true;
2396 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
2398 switch (t
->layout
) {
2400 if ((grid_pos
.x
% 3) == 0 || (grid_pos
.y
% 3) == 0) return false;
2404 if ((grid_pos
.x
% 4) == 0 || (grid_pos
.y
% 4) == 0) return false;
2416 * Checks if current town layout allows 2x2 building here
2418 * @param tile tile to check
2419 * @return true iff town layout allows 2x2 building here
2422 static inline bool TownLayoutAllows2x2HouseHere(Town
*t
, TileIndex tile
)
2424 /* Allow towns everywhere when we don't build roads */
2425 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return true;
2427 /* Compute relative position of tile. (Positive offsets are towards north) */
2428 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
2430 switch (t
->layout
) {
2434 if ((grid_pos
.x
!= 2 && grid_pos
.x
!= -1) ||
2435 (grid_pos
.y
!= 2 && grid_pos
.y
!= -1)) return false;
2439 if ((grid_pos
.x
& 3) < 2 || (grid_pos
.y
& 3) < 2) return false;
2451 * Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout
2452 * Also, tests both building positions that occupy this tile
2453 * @param tile tile where the building should be built
2455 * @param maxz all tiles should have the same height
2456 * @param noslope are slopes forbidden?
2457 * @param second diagdir from first tile to second tile
2459 static bool CheckTownBuild2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
, DiagDirection second
)
2461 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2463 TileIndex tile2
= *tile
+ TileOffsByDiagDir(second
);
2464 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, maxz
, noslope
)) return true;
2466 tile2
= *tile
+ TileOffsByDiagDir(ReverseDiagDir(second
));
2467 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, maxz
, noslope
)) {
2477 * Checks if 2x2 building is allowed here, also takes into account current town layout
2478 * Also, tests all four building positions that occupy this tile
2479 * @param tile tile where the building should be built
2481 * @param maxz all tiles should have the same height
2482 * @param noslope are slopes forbidden?
2484 static bool CheckTownBuild2x2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
)
2486 TileIndex tile2
= *tile
;
2488 for (DiagDirection d
= DIAGDIR_SE
;; d
++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2489 if (TownLayoutAllows2x2HouseHere(t
, tile2
) && CheckFree2x2Area(tile2
, maxz
, noslope
)) {
2493 if (d
== DIAGDIR_END
) break;
2494 tile2
+= TileOffsByDiagDir(ReverseDiagDir(d
)); // go clockwise
2502 * Tries to build a house at this tile
2503 * @param t town the house will belong to
2504 * @param tile where the house will be built
2505 * @return false iff no house can be built at this tile
2507 static bool BuildTownHouse(Town
*t
, TileIndex tile
)
2509 /* forbidden building here by town layout */
2510 if (!TownLayoutAllowsHouseHere(t
, tile
)) return false;
2512 /* no house allowed at all, bail out */
2513 if (!CanBuildHouseHere(tile
, false)) return false;
2515 Slope slope
= GetTileSlope(tile
);
2516 int maxz
= GetTileMaxZ(tile
);
2518 /* Get the town zone type of the current tile, as well as the climate.
2519 * This will allow to easily compare with the specs of the new house to build */
2520 HouseZonesBits rad
= GetTownRadiusGroup(t
, tile
);
2523 int land
= _settings_game
.game_creation
.landscape
;
2524 if (land
== LT_ARCTIC
&& maxz
> HighestSnowLine()) land
= -1;
2526 uint bitmask
= (1 << rad
) + (1 << (land
+ 12));
2528 /* bits 0-4 are used
2529 * bits 11-15 are used
2530 * bits 5-10 are not used. */
2531 HouseID houses
[NUM_HOUSES
];
2533 uint probs
[NUM_HOUSES
];
2534 uint probability_max
= 0;
2536 /* Generate a list of all possible houses that can be built. */
2537 for (uint i
= 0; i
< NUM_HOUSES
; i
++) {
2538 const HouseSpec
*hs
= HouseSpec::Get(i
);
2540 /* Verify that the candidate house spec matches the current tile status */
2541 if ((~hs
->building_availability
& bitmask
) != 0 || !hs
->enabled
|| hs
->grf_prop
.override
!= INVALID_HOUSE_ID
) continue;
2543 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2544 if (hs
->class_id
!= HOUSE_NO_CLASS
) {
2545 /* id_count is always <= class_count, so it doesn't need to be checked */
2546 if (t
->cache
.building_counts
.class_count
[hs
->class_id
] == UINT16_MAX
) continue;
2548 /* If the house has no class, check id_count instead */
2549 if (t
->cache
.building_counts
.id_count
[i
] == UINT16_MAX
) continue;
2552 uint cur_prob
= hs
->probability
;
2553 probability_max
+= cur_prob
;
2554 probs
[num
] = cur_prob
;
2555 houses
[num
++] = (HouseID
)i
;
2558 TileIndex baseTile
= tile
;
2560 while (probability_max
> 0) {
2561 /* Building a multitile building can change the location of tile.
2562 * The building would still be built partially on that tile, but
2563 * its northern tile would be elsewhere. However, if the callback
2564 * fails we would be basing further work from the changed tile.
2565 * So a next 1x1 tile building could be built on the wrong tile. */
2568 uint r
= RandomRange(probability_max
);
2570 for (i
= 0; i
< num
; i
++) {
2571 if (probs
[i
] > r
) break;
2575 HouseID house
= houses
[i
];
2576 probability_max
-= probs
[i
];
2578 /* remove tested house from the set */
2580 houses
[i
] = houses
[num
];
2581 probs
[i
] = probs
[num
];
2583 const HouseSpec
*hs
= HouseSpec::Get(house
);
2585 if (!_generating_world
&& _game_mode
!= GM_EDITOR
&& (hs
->extra_flags
& BUILDING_IS_HISTORICAL
) != 0) {
2589 if (_cur_year
< hs
->min_year
|| _cur_year
> hs
->max_year
) continue;
2591 /* Special houses that there can be only one of. */
2594 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2595 SetBit(oneof
, TOWN_HAS_CHURCH
);
2596 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2597 SetBit(oneof
, TOWN_HAS_STADIUM
);
2600 if (t
->flags
& oneof
) continue;
2602 /* Make sure there is no slope? */
2603 bool noslope
= (hs
->building_flags
& TILE_NOT_SLOPED
) != 0;
2604 if (noslope
&& slope
!= SLOPE_FLAT
) continue;
2606 if (hs
->building_flags
& TILE_SIZE_2x2
) {
2607 if (!CheckTownBuild2x2House(&tile
, t
, maxz
, noslope
)) continue;
2608 } else if (hs
->building_flags
& TILE_SIZE_2x1
) {
2609 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SW
)) continue;
2610 } else if (hs
->building_flags
& TILE_SIZE_1x2
) {
2611 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SE
)) continue;
2613 /* 1x1 house checks are already done */
2616 byte random_bits
= Random();
2618 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ALLOW_CONSTRUCTION
)) {
2619 uint16 callback_res
= GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION
, 0, 0, house
, t
, tile
, true, random_bits
);
2620 if (callback_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_ALLOW_CONSTRUCTION
, callback_res
)) continue;
2623 /* build the house */
2624 t
->cache
.num_houses
++;
2626 /* Special houses that there can be only one of. */
2629 byte construction_counter
= 0;
2630 byte construction_stage
= 0;
2632 if (_generating_world
|| _game_mode
== GM_EDITOR
) {
2633 uint32 r
= Random();
2635 construction_stage
= TOWN_HOUSE_COMPLETED
;
2636 if (Chance16(1, 7)) construction_stage
= GB(r
, 0, 2);
2638 if (construction_stage
== TOWN_HOUSE_COMPLETED
) {
2639 ChangePopulation(t
, hs
->population
);
2641 construction_counter
= GB(r
, 2, 2);
2645 MakeTownHouse(tile
, t
, construction_counter
, construction_stage
, house
, random_bits
);
2646 UpdateTownRadius(t
);
2647 UpdateTownGrowthRate(t
);
2656 * Update data structures when a house is removed
2657 * @param tile Tile of the house
2658 * @param t Town owning the house
2659 * @param house House type
2661 static void DoClearTownHouseHelper(TileIndex tile
, Town
*t
, HouseID house
)
2663 assert(IsTileType(tile
, MP_HOUSE
));
2664 DecreaseBuildingCount(t
, house
);
2665 DoClearSquare(tile
);
2666 DeleteAnimatedTile(tile
);
2668 DeleteNewGRFInspectWindow(GSF_HOUSES
, tile
);
2672 * Determines if a given HouseID is part of a multitile house.
2673 * The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
2675 * @param house Is changed to the HouseID of the north tile of the same house
2676 * @return TileDiff from the tile of the given HouseID to the north tile
2678 TileIndexDiff
GetHouseNorthPart(HouseID
&house
)
2680 if (house
>= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2681 if (HouseSpec::Get(house
- 1)->building_flags
& TILE_SIZE_2x1
) {
2683 return TileDiffXY(-1, 0);
2684 } else if (HouseSpec::Get(house
- 1)->building_flags
& BUILDING_2_TILES_Y
) {
2686 return TileDiffXY(0, -1);
2687 } else if (HouseSpec::Get(house
- 2)->building_flags
& BUILDING_HAS_4_TILES
) {
2689 return TileDiffXY(-1, 0);
2690 } else if (HouseSpec::Get(house
- 3)->building_flags
& BUILDING_HAS_4_TILES
) {
2692 return TileDiffXY(-1, -1);
2698 void ClearTownHouse(Town
*t
, TileIndex tile
)
2700 assert(IsTileType(tile
, MP_HOUSE
));
2702 HouseID house
= GetHouseType(tile
);
2704 /* need to align the tile to point to the upper left corner of the house */
2705 tile
+= GetHouseNorthPart(house
); // modifies house to the ID of the north tile
2707 const HouseSpec
*hs
= HouseSpec::Get(house
);
2709 /* Remove population from the town if the house is finished. */
2710 if (IsHouseCompleted(tile
)) {
2711 ChangePopulation(t
, -hs
->population
);
2714 t
->cache
.num_houses
--;
2716 /* Clear flags for houses that only may exist once/town. */
2717 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2718 ClrBit(t
->flags
, TOWN_HAS_CHURCH
);
2719 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2720 ClrBit(t
->flags
, TOWN_HAS_STADIUM
);
2723 /* Do the actual clearing of tiles */
2724 DoClearTownHouseHelper(tile
, t
, house
);
2725 if (hs
->building_flags
& BUILDING_2_TILES_Y
) DoClearTownHouseHelper(tile
+ TileDiffXY(0, 1), t
, ++house
);
2726 if (hs
->building_flags
& BUILDING_2_TILES_X
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 0), t
, ++house
);
2727 if (hs
->building_flags
& BUILDING_HAS_4_TILES
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 1), t
, ++house
);
2729 RemoveNearbyStations(t
, tile
, hs
->building_flags
);
2731 UpdateTownRadius(t
);
2735 * Rename a town (server-only).
2736 * @param flags type of operation
2737 * @param town_id town ID to rename
2738 * @param text the new name or an empty string when resetting to the default
2739 * @return the cost of this operation or an error
2741 CommandCost
CmdRenameTown(DoCommandFlag flags
, TownID town_id
, const std::string
&text
)
2743 Town
*t
= Town::GetIfValid(town_id
);
2744 if (t
== nullptr) return CMD_ERROR
;
2746 bool reset
= text
.empty();
2749 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return CMD_ERROR
;
2750 if (!IsUniqueTownName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
2753 if (flags
& DC_EXEC
) {
2754 t
->cached_name
.clear();
2761 t
->UpdateVirtCoord();
2762 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, TDIWD_FORCE_RESORT
);
2763 ClearAllStationCachedNames();
2764 ClearAllIndustryCachedNames();
2765 UpdateAllStationVirtCoords();
2767 return CommandCost();
2771 * Determines the first cargo with a certain town effect
2772 * @param effect Town effect of interest
2773 * @return first active cargo slot with that effect
2775 const CargoSpec
*FindFirstCargoWithTownEffect(TownEffect effect
)
2777 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
2778 if (cs
->town_effect
== effect
) return cs
;
2784 * Change the cargo goal of a town.
2785 * @param flags Type of operation.
2786 * @param town_id Town ID to cargo game of.
2787 * @param te TownEffect to change the game of.
2788 * @param goal The new goal value.
2789 * @return Empty cost or an error.
2791 CommandCost
CmdTownCargoGoal(DoCommandFlag flags
, TownID town_id
, TownEffect te
, uint32 goal
)
2793 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2795 if (te
< TE_BEGIN
|| te
>= TE_END
) return CMD_ERROR
;
2797 Town
*t
= Town::GetIfValid(town_id
);
2798 if (t
== nullptr) return CMD_ERROR
;
2800 /* Validate if there is a cargo which is the requested TownEffect */
2801 const CargoSpec
*cargo
= FindFirstCargoWithTownEffect(te
);
2802 if (cargo
== nullptr) return CMD_ERROR
;
2804 if (flags
& DC_EXEC
) {
2806 UpdateTownGrowth(t
);
2807 InvalidateWindowData(WC_TOWN_VIEW
, town_id
);
2810 return CommandCost();
2814 * Set a custom text in the Town window.
2815 * @param flags Type of operation.
2816 * @param town_id Town ID to change the text of.
2817 * @param text The new text (empty to remove the text).
2818 * @return Empty cost or an error.
2820 CommandCost
CmdTownSetText(DoCommandFlag flags
, TownID town_id
, const std::string
&text
)
2822 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2823 Town
*t
= Town::GetIfValid(town_id
);
2824 if (t
== nullptr) return CMD_ERROR
;
2826 if (flags
& DC_EXEC
) {
2828 if (!text
.empty()) t
->text
= text
;
2829 InvalidateWindowData(WC_TOWN_VIEW
, town_id
);
2832 return CommandCost();
2836 * Change the growth rate of the town.
2837 * @param flags Type of operation.
2838 * @param town_id Town ID to cargo game of.
2839 * @param growth_rate Amount of days between growth, or TOWN_GROWTH_RATE_NONE, or 0 to reset custom growth rate.
2840 * @return Empty cost or an error.
2842 CommandCost
CmdTownGrowthRate(DoCommandFlag flags
, TownID town_id
, uint16 growth_rate
)
2844 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2846 Town
*t
= Town::GetIfValid(town_id
);
2847 if (t
== nullptr) return CMD_ERROR
;
2849 if (flags
& DC_EXEC
) {
2850 if (growth_rate
== 0) {
2851 /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
2852 ClrBit(t
->flags
, TOWN_CUSTOM_GROWTH
);
2854 uint old_rate
= t
->growth_rate
;
2855 if (t
->grow_counter
>= old_rate
) {
2856 /* This also catches old_rate == 0 */
2857 t
->grow_counter
= growth_rate
;
2859 /* Scale grow_counter, so half finished houses stay half finished */
2860 t
->grow_counter
= t
->grow_counter
* growth_rate
/ old_rate
;
2862 t
->growth_rate
= growth_rate
;
2863 SetBit(t
->flags
, TOWN_CUSTOM_GROWTH
);
2865 UpdateTownGrowth(t
);
2866 InvalidateWindowData(WC_TOWN_VIEW
, town_id
);
2869 return CommandCost();
2873 * Change the rating of a company in a town
2874 * @param flags Type of operation.
2875 * @param town_id Town ID to change, bit 16..23 =
2876 * @param company_id Company ID to change.
2877 * @param rating New rating of company (signed int16).
2878 * @return Empty cost or an error.
2880 CommandCost
CmdTownRating(DoCommandFlag flags
, TownID town_id
, CompanyID company_id
, int16 rating
)
2882 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2884 Town
*t
= Town::GetIfValid(town_id
);
2885 if (t
== nullptr) return CMD_ERROR
;
2887 if (!Company::IsValidID(company_id
)) return CMD_ERROR
;
2889 int16 new_rating
= Clamp(rating
, RATING_MINIMUM
, RATING_MAXIMUM
);
2890 if (flags
& DC_EXEC
) {
2891 t
->ratings
[company_id
] = new_rating
;
2892 InvalidateWindowData(WC_TOWN_AUTHORITY
, town_id
);
2895 return CommandCost();
2899 * Expand a town (scenario editor only).
2900 * @param flags Type of operation.
2901 * @param TownID Town ID to expand.
2902 * @param grow_amount Amount to grow, or 0 to grow a random size up to the current amount of houses.
2903 * @return Empty cost or an error.
2905 CommandCost
CmdExpandTown(DoCommandFlag flags
, TownID town_id
, uint32 grow_amount
)
2907 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2908 Town
*t
= Town::GetIfValid(town_id
);
2909 if (t
== nullptr) return CMD_ERROR
;
2911 if (flags
& DC_EXEC
) {
2912 /* The more houses, the faster we grow */
2913 if (grow_amount
== 0) {
2914 uint amount
= RandomRange(ClampToU16(t
->cache
.num_houses
/ 10)) + 3;
2915 t
->cache
.num_houses
+= amount
;
2916 UpdateTownRadius(t
);
2918 uint n
= amount
* 10;
2919 do GrowTown(t
); while (--n
);
2921 t
->cache
.num_houses
-= amount
;
2923 for (; grow_amount
> 0; grow_amount
--) {
2924 /* Try several times to grow, as we are really suppose to grow */
2925 for (uint i
= 0; i
< 25; i
++) if (GrowTown(t
)) break;
2928 UpdateTownRadius(t
);
2930 UpdateTownMaxPass(t
);
2933 return CommandCost();
2937 * Delete a town (scenario editor or worldgen only).
2938 * @param flags Type of operation.
2939 * @param town_id Town ID to delete.
2940 * @return Empty cost or an error.
2942 CommandCost
CmdDeleteTown(DoCommandFlag flags
, TownID town_id
)
2944 if (_game_mode
!= GM_EDITOR
&& !_generating_world
) return CMD_ERROR
;
2945 Town
*t
= Town::GetIfValid(town_id
);
2946 if (t
== nullptr) return CMD_ERROR
;
2948 /* Stations refer to towns. */
2949 for (const Station
*st
: Station::Iterate()) {
2950 if (st
->town
== t
) {
2951 /* Non-oil rig stations are always a problem. */
2952 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->airport
.type
!= AT_OILRIG
) return CMD_ERROR
;
2953 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2954 CommandCost ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, st
->airport
.tile
);
2955 if (ret
.Failed()) return ret
;
2959 /* Depots refer to towns. */
2960 for (const Depot
*d
: Depot::Iterate()) {
2961 if (d
->town
== t
) return CMD_ERROR
;
2964 /* Check all tiles for town ownership. First check for bridge tiles, as
2965 * these do not directly have an owner so we need to check adjacent
2966 * tiles. This won't work correctly in the same loop if the adjacent
2967 * tile was already deleted earlier in the loop. */
2968 for (TileIndex current_tile
= 0; current_tile
< MapSize(); ++current_tile
) {
2969 if (IsTileType(current_tile
, MP_TUNNELBRIDGE
) && TestTownOwnsBridge(current_tile
, t
)) {
2970 CommandCost ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, current_tile
);
2971 if (ret
.Failed()) return ret
;
2975 /* Check all remaining tiles for town ownership. */
2976 for (TileIndex current_tile
= 0; current_tile
< MapSize(); ++current_tile
) {
2977 bool try_clear
= false;
2978 switch (GetTileType(current_tile
)) {
2980 try_clear
= HasTownOwnedRoad(current_tile
) && GetTownIndex(current_tile
) == t
->index
;
2984 try_clear
= GetTownIndex(current_tile
) == t
->index
;
2988 try_clear
= Industry::GetByTile(current_tile
)->town
== t
;
2992 if (Town::GetNumItems() == 1) {
2993 /* No towns will be left, remove it! */
2996 Object
*o
= Object::GetByTile(current_tile
);
2998 if (o
->type
== OBJECT_STATUE
) {
2999 /* Statue... always remove. */
3002 /* Tell to find a new town. */
3003 if (flags
& DC_EXEC
) o
->town
= nullptr;
3013 CommandCost ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, current_tile
);
3014 if (ret
.Failed()) return ret
;
3018 /* The town destructor will delete the other things related to the town. */
3019 if (flags
& DC_EXEC
) {
3020 _town_kdtree
.Remove(t
->index
);
3021 if (t
->cache
.sign
.kdtree_valid
) _viewport_sign_kdtree
.Remove(ViewportSignKdtreeItem::MakeTown(t
->index
));
3025 return CommandCost();
3029 * Factor in the cost of each town action.
3032 const byte _town_action_costs
[TACT_COUNT
] = {
3033 2, 4, 9, 35, 48, 53, 117, 175
3036 static CommandCost
TownActionAdvertiseSmall(Town
*t
, DoCommandFlag flags
)
3038 if (flags
& DC_EXEC
) {
3039 ModifyStationRatingAround(t
->xy
, _current_company
, 0x40, 10);
3041 return CommandCost();
3044 static CommandCost
TownActionAdvertiseMedium(Town
*t
, DoCommandFlag flags
)
3046 if (flags
& DC_EXEC
) {
3047 ModifyStationRatingAround(t
->xy
, _current_company
, 0x70, 15);
3049 return CommandCost();
3052 static CommandCost
TownActionAdvertiseLarge(Town
*t
, DoCommandFlag flags
)
3054 if (flags
& DC_EXEC
) {
3055 ModifyStationRatingAround(t
->xy
, _current_company
, 0xA0, 20);
3057 return CommandCost();
3060 static CommandCost
TownActionRoadRebuild(Town
*t
, DoCommandFlag flags
)
3062 /* Check if the company is allowed to fund new roads. */
3063 if (!_settings_game
.economy
.fund_roads
) return CMD_ERROR
;
3065 if (flags
& DC_EXEC
) {
3066 t
->road_build_months
= 6;
3068 SetDParam(0, _current_company
);
3069 NewsStringData
*company_name
= new NewsStringData(GetString(STR_COMPANY_NAME
));
3071 SetDParam(0, t
->index
);
3072 SetDParamStr(1, company_name
->string
);
3074 AddNewsItem(STR_NEWS_ROAD_REBUILDING
, NT_GENERAL
, NF_NORMAL
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
, company_name
);
3075 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3076 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3078 return CommandCost();
3082 * Check whether the land can be cleared.
3083 * @param tile Tile to check.
3084 * @return The tile can be cleared.
3086 static bool TryClearTile(TileIndex tile
)
3088 Backup
<CompanyID
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
3089 CommandCost r
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_NONE
, tile
);
3090 cur_company
.Restore();
3091 return r
.Succeeded();
3094 /** Structure for storing data while searching the best place to build a statue. */
3095 struct StatueBuildSearchData
{
3096 TileIndex best_position
; ///< Best position found so far.
3097 int tile_count
; ///< Number of tiles tried.
3099 StatueBuildSearchData(TileIndex best_pos
, int count
) : best_position(best_pos
), tile_count(count
) { }
3103 * Search callback function for #TownActionBuildStatue.
3104 * @param tile Tile on which to perform the search.
3105 * @param user_data Reference to the statue search data.
3106 * @return Result of the test.
3108 static bool SearchTileForStatue(TileIndex tile
, void *user_data
)
3110 static const int STATUE_NUMBER_INNER_TILES
= 25; // Number of tiles int the center of the city, where we try to protect houses.
3112 StatueBuildSearchData
*statue_data
= (StatueBuildSearchData
*)user_data
;
3113 statue_data
->tile_count
++;
3115 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3116 if (IsSteepSlope(GetTileSlope(tile
))) return false;
3117 /* Don't build statues under bridges. */
3118 if (IsBridgeAbove(tile
)) return false;
3120 /* A clear-able open space is always preferred. */
3121 if ((IsTileType(tile
, MP_CLEAR
) || IsTileType(tile
, MP_TREES
)) && TryClearTile(tile
)) {
3122 statue_data
->best_position
= tile
;
3126 bool house
= IsTileType(tile
, MP_HOUSE
);
3128 /* Searching inside the inner circle. */
3129 if (statue_data
->tile_count
<= STATUE_NUMBER_INNER_TILES
) {
3130 /* Save first house in inner circle. */
3131 if (house
&& statue_data
->best_position
== INVALID_TILE
&& TryClearTile(tile
)) {
3132 statue_data
->best_position
= tile
;
3135 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3136 return statue_data
->tile_count
== STATUE_NUMBER_INNER_TILES
&& statue_data
->best_position
!= INVALID_TILE
;
3139 /* Searching outside the circle, just pick the first possible spot. */
3140 statue_data
->best_position
= tile
; // Is optimistic, the condition below must also hold.
3141 return house
&& TryClearTile(tile
);
3145 * Perform a 9x9 tiles circular search from the center of the town
3146 * in order to find a free tile to place a statue
3147 * @param t town to search in
3148 * @param flags Used to check if the statue must be built or not.
3149 * @return Empty cost or an error.
3151 static CommandCost
TownActionBuildStatue(Town
*t
, DoCommandFlag flags
)
3153 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
3155 TileIndex tile
= t
->xy
;
3156 StatueBuildSearchData
statue_data(INVALID_TILE
, 0);
3157 if (!CircularTileSearch(&tile
, 9, SearchTileForStatue
, &statue_data
)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE
);
3159 if (flags
& DC_EXEC
) {
3160 Backup
<CompanyID
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
3161 Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_EXEC
, statue_data
.best_position
);
3162 cur_company
.Restore();
3163 BuildObject(OBJECT_STATUE
, statue_data
.best_position
, _current_company
, t
);
3164 SetBit(t
->statues
, _current_company
); // Once found and built, "inform" the Town.
3165 MarkTileDirtyByTile(statue_data
.best_position
);
3167 return CommandCost();
3170 static CommandCost
TownActionFundBuildings(Town
*t
, DoCommandFlag flags
)
3172 /* Check if it's allowed to buy the rights */
3173 if (!_settings_game
.economy
.fund_buildings
) return CMD_ERROR
;
3175 if (flags
& DC_EXEC
) {
3176 /* And grow for 3 months */
3177 t
->fund_buildings_months
= 3;
3179 /* Enable growth (also checking GameScript's opinion) */
3180 UpdateTownGrowth(t
);
3182 /* Build a new house, but add a small delay to make sure
3183 * that spamming funding doesn't let town grow any faster
3184 * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3185 * Also emulate original behaviour when town was only growing in
3186 * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3187 * tick-perfect and gives player some time window where they can
3188 * spam funding with the exact same efficiency.
3190 t
->grow_counter
= std::min
<uint16
>(t
->grow_counter
, 2 * TOWN_GROWTH_TICKS
- (t
->growth_rate
- t
->grow_counter
) % TOWN_GROWTH_TICKS
);
3192 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3194 return CommandCost();
3197 static CommandCost
TownActionBuyRights(Town
*t
, DoCommandFlag flags
)
3199 /* Check if it's allowed to buy the rights */
3200 if (!_settings_game
.economy
.exclusive_rights
) return CMD_ERROR
;
3202 if (flags
& DC_EXEC
) {
3203 t
->exclusive_counter
= 12;
3204 t
->exclusivity
= _current_company
;
3206 ModifyStationRatingAround(t
->xy
, _current_company
, 130, 17);
3208 SetWindowClassesDirty(WC_STATION_VIEW
);
3210 /* Spawn news message */
3211 CompanyNewsInformation
*cni
= new CompanyNewsInformation(Company::Get(_current_company
));
3212 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE
);
3213 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION
);
3214 SetDParam(2, t
->index
);
3215 SetDParamStr(3, cni
->company_name
);
3216 AddNewsItem(STR_MESSAGE_NEWS_FORMAT
, NT_GENERAL
, NF_COMPANY
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
, cni
);
3217 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3218 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3220 return CommandCost();
3223 static CommandCost
TownActionBribe(Town
*t
, DoCommandFlag flags
)
3225 if (flags
& DC_EXEC
) {
3226 if (Chance16(1, 14)) {
3227 /* set as unwanted for 6 months */
3228 t
->unwanted
[_current_company
] = 6;
3230 /* set all close by station ratings to 0 */
3231 for (Station
*st
: Station::Iterate()) {
3232 if (st
->town
== t
&& st
->owner
== _current_company
) {
3233 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) st
->goods
[i
].rating
= 0;
3237 /* only show error message to the executing player. All errors are handled command.c
3238 * but this is special, because it can only 'fail' on a DC_EXEC */
3239 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED
, INVALID_STRING_ID
, WL_INFO
);
3241 /* decrease by a lot!
3242 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3243 * be independent of any cheat settings
3245 if (t
->ratings
[_current_company
] > RATING_BRIBE_DOWN_TO
) {
3246 t
->ratings
[_current_company
] = RATING_BRIBE_DOWN_TO
;
3247 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3250 ChangeTownRating(t
, RATING_BRIBE_UP_STEP
, RATING_BRIBE_MAXIMUM
, DC_EXEC
);
3253 return CommandCost();
3256 typedef CommandCost
TownActionProc(Town
*t
, DoCommandFlag flags
);
3257 static TownActionProc
* const _town_action_proc
[] = {
3258 TownActionAdvertiseSmall
,
3259 TownActionAdvertiseMedium
,
3260 TownActionAdvertiseLarge
,
3261 TownActionRoadRebuild
,
3262 TownActionBuildStatue
,
3263 TownActionFundBuildings
,
3264 TownActionBuyRights
,
3269 * Get a list of available actions to do at a town.
3270 * @param nump if not nullptr add put the number of available actions in it
3271 * @param cid the company that is querying the town
3272 * @param t the town that is queried
3273 * @return bitmasked value of enabled actions
3275 uint
GetMaskOfTownActions(int *nump
, CompanyID cid
, const Town
*t
)
3278 TownActions buttons
= TACT_NONE
;
3280 /* Spectators and unwanted have no options */
3281 if (cid
!= COMPANY_SPECTATOR
&& !(_settings_game
.economy
.bribe
&& t
->unwanted
[cid
])) {
3283 /* Things worth more than this are not shown */
3284 Money avail
= Company::Get(cid
)->money
+ _price
[PR_STATION_VALUE
] * 200;
3286 /* Check the action bits for validity and
3287 * if they are valid add them */
3288 for (uint i
= 0; i
!= lengthof(_town_action_costs
); i
++) {
3289 const TownActions cur
= (TownActions
)(1 << i
);
3291 /* Is the company not able to bribe ? */
3292 if (cur
== TACT_BRIBE
&& (!_settings_game
.economy
.bribe
|| t
->ratings
[cid
] >= RATING_BRIBE_MAXIMUM
)) continue;
3294 /* Is the company not able to buy exclusive rights ? */
3295 if (cur
== TACT_BUY_RIGHTS
&& !_settings_game
.economy
.exclusive_rights
) continue;
3297 /* Is the company not able to fund buildings ? */
3298 if (cur
== TACT_FUND_BUILDINGS
&& !_settings_game
.economy
.fund_buildings
) continue;
3300 /* Is the company not able to fund local road reconstruction? */
3301 if (cur
== TACT_ROAD_REBUILD
&& !_settings_game
.economy
.fund_roads
) continue;
3303 /* Is the company not able to build a statue ? */
3304 if (cur
== TACT_BUILD_STATUE
&& HasBit(t
->statues
, cid
)) continue;
3306 if (avail
>= _town_action_costs
[i
] * _price
[PR_TOWN_ACTION
] >> 8) {
3313 if (nump
!= nullptr) *nump
= num
;
3319 * This performs an action such as advertising, building a statue, funding buildings,
3320 * but also bribing the town-council
3321 * @param flags type of operation
3322 * @param town_id town to do the action at
3323 * @param action action to perform, @see _town_action_proc for the list of available actions
3324 * @return the cost of this operation or an error
3326 CommandCost
CmdDoTownAction(DoCommandFlag flags
, TownID town_id
, uint8 action
)
3328 Town
*t
= Town::GetIfValid(town_id
);
3329 if (t
== nullptr || action
>= lengthof(_town_action_proc
)) return CMD_ERROR
;
3331 if (!HasBit(GetMaskOfTownActions(nullptr, _current_company
, t
), action
)) return CMD_ERROR
;
3333 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_TOWN_ACTION
] * _town_action_costs
[action
] >> 8);
3335 CommandCost ret
= _town_action_proc
[action
](t
, flags
);
3336 if (ret
.Failed()) return ret
;
3338 if (flags
& DC_EXEC
) {
3339 SetWindowDirty(WC_TOWN_AUTHORITY
, town_id
);
3345 template <typename Func
>
3346 static void ForAllStationsNearTown(Town
*t
, Func func
)
3348 /* Ideally the search radius should be close to the actual town zone 0 radius.
3349 * The true radius is not stored or calculated anywhere, only the squared radius. */
3350 /* The efficiency of this search might be improved for large towns and many stations on the map,
3351 * by using an integer square root approximation giving a value not less than the true square root. */
3352 uint search_radius
= t
->cache
.squared_town_zone_radius
[0] / 2;
3353 ForAllStationsRadius(t
->xy
, search_radius
, [&](const Station
* st
) {
3354 if (DistanceSquare(st
->xy
, t
->xy
) <= t
->cache
.squared_town_zone_radius
[0]) {
3360 static void UpdateTownRating(Town
*t
)
3362 /* Increase company ratings if they're low */
3363 for (const Company
*c
: Company::Iterate()) {
3364 if (t
->ratings
[c
->index
] < RATING_GROWTH_MAXIMUM
) {
3365 t
->ratings
[c
->index
] = std::min((int)RATING_GROWTH_MAXIMUM
, t
->ratings
[c
->index
] + RATING_GROWTH_UP_STEP
);
3369 ForAllStationsNearTown(t
, [&](const Station
*st
) {
3370 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3371 if (Company::IsValidID(st
->owner
)) {
3372 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_UP_STEP
;
3373 t
->ratings
[st
->owner
] = std::min
<int>(new_rating
, INT16_MAX
); // do not let it overflow
3376 if (Company::IsValidID(st
->owner
)) {
3377 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_DOWN_STEP
;
3378 t
->ratings
[st
->owner
] = std::max(new_rating
, INT16_MIN
);
3383 /* clamp all ratings to valid values */
3384 for (uint i
= 0; i
< MAX_COMPANIES
; i
++) {
3385 t
->ratings
[i
] = Clamp(t
->ratings
[i
], RATING_MINIMUM
, RATING_MAXIMUM
);
3388 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3393 * Updates town grow counter after growth rate change.
3394 * Preserves relative house builting progress whenever it can.
3395 * @param t The town to calculate grow counter for
3396 * @param prev_growth_rate Town growth rate before it changed (one that was used with grow counter to be updated)
3398 static void UpdateTownGrowCounter(Town
*t
, uint16 prev_growth_rate
)
3400 if (t
->growth_rate
== TOWN_GROWTH_RATE_NONE
) return;
3401 if (prev_growth_rate
== TOWN_GROWTH_RATE_NONE
) {
3402 t
->grow_counter
= std::min
<uint16
>(t
->growth_rate
, t
->grow_counter
);
3405 t
->grow_counter
= RoundDivSU((uint32
)t
->grow_counter
* (t
->growth_rate
+ 1), prev_growth_rate
+ 1);
3409 * Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
3410 * @param t The town to calculate stations for
3411 * @returns Amount of active stations
3413 static int CountActiveStations(Town
*t
)
3416 ForAllStationsNearTown(t
, [&](const Station
* st
) {
3417 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3425 * Calculates town growth rate in normal conditions (custom growth rate not set).
3426 * If town growth speed is set to None(0) returns the same rate as if it was Normal(2).
3427 * @param t The town to calculate growth rate for
3428 * @returns Calculated growth rate
3430 static uint
GetNormalGrowthRate(Town
*t
)
3434 * Unserviced+unfunded towns get an additional malus in UpdateTownGrowth(),
3435 * so the "320" is actually not better than the "420".
3437 static const uint16 _grow_count_values
[2][6] = {
3438 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3439 { 320, 420, 300, 220, 160, 100 } // Normal values
3442 int n
= CountActiveStations(t
);
3443 uint16 m
= _grow_count_values
[t
->fund_buildings_months
!= 0 ? 0 : 1][std::min(n
, 5)];
3445 uint growth_multiplier
= _settings_game
.economy
.town_growth_rate
!= 0 ? _settings_game
.economy
.town_growth_rate
- 1 : 1;
3447 m
>>= growth_multiplier
;
3448 if (t
->larger_town
) m
/= 2;
3450 return TownTicksToGameTicks(m
/ (t
->cache
.num_houses
/ 50 + 1));
3454 * Updates town growth rate.
3455 * @param t The town to update growth rate for
3457 static void UpdateTownGrowthRate(Town
*t
)
3459 if (HasBit(t
->flags
, TOWN_CUSTOM_GROWTH
)) return;
3460 uint old_rate
= t
->growth_rate
;
3461 t
->growth_rate
= GetNormalGrowthRate(t
);
3462 UpdateTownGrowCounter(t
, old_rate
);
3463 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3467 * Updates town growth state (whether it is growing or not).
3468 * @param t The town to update growth for
3470 static void UpdateTownGrowth(Town
*t
)
3472 UpdateTownGrowthRate(t
);
3474 ClrBit(t
->flags
, TOWN_IS_GROWING
);
3475 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3477 if (_settings_game
.economy
.town_growth_rate
== 0 && t
->fund_buildings_months
== 0) return;
3479 if (t
->fund_buildings_months
== 0) {
3480 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3481 for (int i
= TE_BEGIN
; i
< TE_END
; i
++) {
3482 switch (t
->goal
[i
]) {
3483 case TOWN_GROWTH_WINTER
:
3484 if (TileHeight(t
->xy
) >= GetSnowLine() && t
->received
[i
].old_act
== 0 && t
->cache
.population
> 90) return;
3486 case TOWN_GROWTH_DESERT
:
3487 if (GetTropicZone(t
->xy
) == TROPICZONE_DESERT
&& t
->received
[i
].old_act
== 0 && t
->cache
.population
> 60) return;
3490 if (t
->goal
[i
] > t
->received
[i
].old_act
) return;
3496 if (HasBit(t
->flags
, TOWN_CUSTOM_GROWTH
)) {
3497 if (t
->growth_rate
!= TOWN_GROWTH_RATE_NONE
) SetBit(t
->flags
, TOWN_IS_GROWING
);
3498 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3502 if (t
->fund_buildings_months
== 0 && CountActiveStations(t
) == 0 && !Chance16(1, 12)) return;
3504 SetBit(t
->flags
, TOWN_IS_GROWING
);
3505 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3508 static void UpdateTownAmounts(Town
*t
)
3510 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) t
->supplied
[i
].NewMonth();
3511 for (int i
= TE_BEGIN
; i
< TE_END
; i
++) t
->received
[i
].NewMonth();
3512 if (t
->fund_buildings_months
!= 0) t
->fund_buildings_months
--;
3514 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3517 static void UpdateTownUnwanted(Town
*t
)
3519 for (const Company
*c
: Company::Iterate()) {
3520 if (t
->unwanted
[c
->index
] > 0) t
->unwanted
[c
->index
]--;
3525 * Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
3526 * @param tile The tile where the station shall be constructed.
3527 * @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
3528 * @return Succeeded or failed command.
3530 CommandCost
CheckIfAuthorityAllowsNewStation(TileIndex tile
, DoCommandFlag flags
)
3532 /* The required rating is hardcoded to RATING_VERYPOOR (see below), not the authority attitude setting, so we can bail out like this. */
3533 if (_settings_game
.difficulty
.town_council_tolerance
== TOWN_COUNCIL_PERMISSIVE
) return CommandCost();
3535 if (!Company::IsValidID(_current_company
) || (flags
& DC_NO_TEST_TOWN_RATING
)) return CommandCost();
3537 Town
*t
= ClosestTownFromTile(tile
, _settings_game
.economy
.dist_local_authority
);
3538 if (t
== nullptr) return CommandCost();
3540 if (t
->ratings
[_current_company
] > RATING_VERYPOOR
) return CommandCost();
3542 SetDParam(0, t
->index
);
3543 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
3547 * Return the town closest to the given tile within \a threshold.
3548 * @param tile Starting point of the search.
3549 * @param threshold Biggest allowed distance to the town.
3550 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3552 * @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
3554 Town
*CalcClosestTownFromTile(TileIndex tile
, uint threshold
)
3556 if (Town::GetNumItems() == 0) return nullptr;
3558 TownID tid
= _town_kdtree
.FindNearest(TileX(tile
), TileY(tile
));
3559 Town
*town
= Town::Get(tid
);
3560 if (DistanceManhattan(tile
, town
->xy
) < threshold
) return town
;
3565 * Return the town closest (in distance or ownership) to a given tile, within a given threshold.
3566 * @param tile Starting point of the search.
3567 * @param threshold Biggest allowed distance to the town.
3568 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3570 * @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
3572 Town
*ClosestTownFromTile(TileIndex tile
, uint threshold
)
3574 switch (GetTileType(tile
)) {
3576 if (IsRoadDepot(tile
)) return CalcClosestTownFromTile(tile
, threshold
);
3578 if (!HasTownOwnedRoad(tile
)) {
3579 TownID tid
= GetTownIndex(tile
);
3581 if (tid
== INVALID_TOWN
) {
3582 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3583 if (_generating_world
) return CalcClosestTownFromTile(tile
, threshold
);
3584 assert(Town::GetNumItems() == 0);
3588 assert(Town::IsValidID(tid
));
3589 Town
*town
= Town::Get(tid
);
3591 if (DistanceManhattan(tile
, town
->xy
) >= threshold
) town
= nullptr;
3598 return Town::GetByTile(tile
);
3601 return CalcClosestTownFromTile(tile
, threshold
);
3605 static bool _town_rating_test
= false; ///< If \c true, town rating is in test-mode.
3606 static SmallMap
<const Town
*, int> _town_test_ratings
; ///< Map of towns to modified ratings, while in town rating test-mode.
3609 * Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
3610 * The function is safe to use in nested calls.
3611 * @param mode Test mode switch (\c true means go to test-mode, \c false means leave test-mode).
3613 void SetTownRatingTestMode(bool mode
)
3615 static int ref_count
= 0; // Number of times test-mode is switched on.
3617 if (ref_count
== 0) {
3618 _town_test_ratings
.clear();
3622 assert(ref_count
> 0);
3625 _town_rating_test
= !(ref_count
== 0);
3629 * Get the rating of a town for the #_current_company.
3630 * @param t Town to get the rating from.
3631 * @return Rating of the current company in the given town.
3633 static int GetRating(const Town
*t
)
3635 if (_town_rating_test
) {
3636 SmallMap
<const Town
*, int>::iterator it
= _town_test_ratings
.Find(t
);
3637 if (it
!= _town_test_ratings
.End()) {
3641 return t
->ratings
[_current_company
];
3645 * Changes town rating of the current company
3646 * @param t Town to affect
3647 * @param add Value to add
3648 * @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be achievable with this change.
3649 * @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
3651 void ChangeTownRating(Town
*t
, int add
, int max
, DoCommandFlag flags
)
3653 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3654 if (t
== nullptr || (flags
& DC_NO_MODIFY_TOWN_RATING
) ||
3655 !Company::IsValidID(_current_company
) ||
3656 (_cheats
.magic_bulldozer
.value
&& add
< 0)) {
3660 int rating
= GetRating(t
);
3664 if (rating
< max
) rating
= max
;
3669 if (rating
> max
) rating
= max
;
3672 if (_town_rating_test
) {
3673 _town_test_ratings
[t
] = rating
;
3675 SetBit(t
->have_ratings
, _current_company
);
3676 t
->ratings
[_current_company
] = rating
;
3677 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3682 * Does the town authority allow the (destructive) action of the current company?
3683 * @param flags Checking flags of the command.
3684 * @param t Town that must allow the company action.
3685 * @param type Type of action that is wanted.
3686 * @return A succeeded command if the action is allowed, a failed command if it is not allowed.
3688 CommandCost
CheckforTownRating(DoCommandFlag flags
, Town
*t
, TownRatingCheckType type
)
3690 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3691 if (t
== nullptr || !Company::IsValidID(_current_company
) ||
3692 _cheats
.magic_bulldozer
.value
|| (flags
& DC_NO_TEST_TOWN_RATING
)) {
3693 return CommandCost();
3696 /* minimum rating needed to be allowed to remove stuff */
3697 static const int needed_rating
[][TOWN_RATING_CHECK_TYPE_COUNT
] = {
3698 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3699 { RATING_ROAD_NEEDED_LENIENT
, RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
}, // Lenient
3700 { RATING_ROAD_NEEDED_NEUTRAL
, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
}, // Neutral
3701 { RATING_ROAD_NEEDED_HOSTILE
, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
}, // Hostile
3702 { RATING_ROAD_NEEDED_PERMISSIVE
, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
}, // Permissive
3705 /* check if you're allowed to remove the road/bridge/tunnel
3706 * owned by a town no removal if rating is lower than ... depends now on
3707 * difficulty setting. Minimum town rating selected by difficulty level
3709 int needed
= needed_rating
[_settings_game
.difficulty
.town_council_tolerance
][type
];
3711 if (GetRating(t
) < needed
) {
3712 SetDParam(0, t
->index
);
3713 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
3716 return CommandCost();
3719 void TownsMonthlyLoop()
3721 for (Town
*t
: Town::Iterate()) {
3722 if (t
->road_build_months
!= 0) t
->road_build_months
--;
3724 if (t
->exclusive_counter
!= 0) {
3725 if (--t
->exclusive_counter
== 0) t
->exclusivity
= INVALID_COMPANY
;
3728 UpdateTownAmounts(t
);
3729 UpdateTownGrowth(t
);
3730 UpdateTownRating(t
);
3731 UpdateTownUnwanted(t
);
3736 void TownsYearlyLoop()
3738 /* Increment house ages */
3739 for (TileIndex t
= 0; t
< MapSize(); t
++) {
3740 if (!IsTileType(t
, MP_HOUSE
)) continue;
3741 IncrementHouseAge(t
);
3745 static CommandCost
TerraformTile_Town(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
3747 if (AutoslopeEnabled()) {
3748 HouseID house
= GetHouseType(tile
);
3749 GetHouseNorthPart(house
); // modifies house to the ID of the north tile
3750 const HouseSpec
*hs
= HouseSpec::Get(house
);
3752 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3753 if (((hs
->building_flags
& TILE_NOT_SLOPED
) == 0) && !IsSteepSlope(tileh_new
) &&
3754 (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
3755 bool allow_terraform
= true;
3757 /* Call the autosloping callback per tile, not for the whole building at once. */
3758 house
= GetHouseType(tile
);
3759 hs
= HouseSpec::Get(house
);
3760 if (HasBit(hs
->callback_mask
, CBM_HOUSE_AUTOSLOPE
)) {
3761 /* If the callback fails, allow autoslope. */
3762 uint16 res
= GetHouseCallback(CBID_HOUSE_AUTOSLOPE
, 0, 0, house
, Town::GetByTile(tile
), tile
);
3763 if (res
!= CALLBACK_FAILED
&& ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_AUTOSLOPE
, res
)) allow_terraform
= false;
3766 if (allow_terraform
) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3770 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
3773 /** Tile callback functions for a town */
3774 extern const TileTypeProcs _tile_type_town_procs
= {
3775 DrawTile_Town
, // draw_tile_proc
3776 GetSlopePixelZ_Town
, // get_slope_z_proc
3777 ClearTile_Town
, // clear_tile_proc
3778 AddAcceptedCargo_Town
, // add_accepted_cargo_proc
3779 GetTileDesc_Town
, // get_tile_desc_proc
3780 GetTileTrackStatus_Town
, // get_tile_track_status_proc
3781 nullptr, // click_tile_proc
3782 AnimateTile_Town
, // animate_tile_proc
3783 TileLoop_Town
, // tile_loop_proc
3784 ChangeTileOwner_Town
, // change_tile_owner_proc
3785 AddProducedCargo_Town
, // add_produced_cargo_proc
3786 nullptr, // vehicle_enter_tile_proc
3787 GetFoundation_Town
, // get_foundation_proc
3788 TerraformTile_Town
, // terraform_tile_proc
3792 HouseSpec _house_specs
[NUM_HOUSES
];
3796 memset(&_house_specs
, 0, sizeof(_house_specs
));
3797 memcpy(&_house_specs
, &_original_house_specs
, sizeof(_original_house_specs
));
3799 /* Reset any overrides that have been set. */
3800 _house_mngr
.ResetOverride();