4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file town_cmd.cpp Handling of town tiles. */
13 #include "road_internal.h" /* Cleaning up road bits */
15 #include "landscape.h"
16 #include "viewport_func.h"
17 #include "cmd_helper.h"
18 #include "command_func.h"
20 #include "station_base.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 "townname_func.h"
42 #include "core/random_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "depot_base.h"
45 #include "object_map.h"
46 #include "object_base.h"
48 #include "game/game.hpp"
50 #include "table/strings.h"
51 #include "table/town_land.h"
53 #include "safeguards.h"
56 uint32 _town_cargoes_accepted
; ///< Bitmap of all cargoes accepted by houses.
58 /* Initialize the town-pool */
59 TownPool
_town_pool("Town");
60 INSTANTIATE_POOL_METHODS(Town
)
67 if (CleaningPool()) return;
69 /* Delete town authority window
70 * and remove from list of sorted towns */
71 DeleteWindowById(WC_TOWN_VIEW
, this->index
);
73 /* Check no industry is related to us. */
75 FOR_ALL_INDUSTRIES(i
) assert(i
->town
!= this);
77 /* ... and no object is related to us. */
79 FOR_ALL_OBJECTS(o
) assert(o
->town
!= this);
81 /* Check no tile is related to us. */
82 for (TileIndex tile
= 0; tile
< MapSize(); ++tile
) {
83 switch (GetTileType(tile
)) {
85 assert(GetTownIndex(tile
) != this->index
);
89 assert(!HasTownOwnedRoad(tile
) || GetTownIndex(tile
) != this->index
);
93 assert(!IsTileOwner(tile
, OWNER_TOWN
) || ClosestTownFromTile(tile
, UINT_MAX
) != this);
101 /* Clear the persistent storage list. */
102 this->psa_list
.clear();
104 DeleteSubsidyWith(ST_TOWN
, this->index
);
105 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS
, this->index
);
106 CargoPacket::InvalidateAllFrom(ST_TOWN
, this->index
);
107 MarkWholeScreenDirty();
112 * Invalidating of the "nearest town cache" has to be done
113 * after removing item from the pool.
114 * @param index index of deleted item
116 void Town::PostDestructor(size_t index
)
118 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 0);
119 UpdateNearestTownForRoadTiles(false);
121 /* Give objects a new home! */
124 if (o
->town
== nullptr) o
->town
= CalcClosestTownFromTile(o
->location
.tile
, UINT_MAX
);
129 * Assigns town layout. If Random, generates one based on TileHash.
131 void Town::InitializeLayout(TownLayout layout
)
133 if (layout
!= TL_RANDOM
) {
134 this->layout
= layout
;
138 this->layout
= TileHash(TileX(this->xy
), TileY(this->xy
)) % (NUM_TLS
- 1);
142 * Return a random valid town.
143 * @return random town, nullptr if there are no towns
145 /* static */ Town
*Town::GetRandom()
147 if (Town::GetNumItems() == 0) return nullptr;
148 int num
= RandomRange((uint16
)Town::GetNumItems());
149 size_t index
= MAX_UVALUE(size_t);
155 /* Make sure we have a valid town */
156 while (!Town::IsValidID(index
)) {
158 assert(index
< Town::GetPoolSize());
162 return Town::Get(index
);
166 * Updates the town label of the town after changes in rating. The colour scheme is:
167 * Red: Appalling and Very poor ratings.
168 * Orange: Poor and mediocre ratings.
169 * Yellow: Good rating.
170 * White: Very good rating (standard).
171 * Green: Excellent and outstanding ratings.
173 void Town::UpdateLabel()
175 if (!(_game_mode
== GM_EDITOR
) && (_local_company
< MAX_COMPANIES
)) {
176 int r
= this->ratings
[_local_company
];
177 (this->town_label
= 0, r
<= RATING_VERYPOOR
) || // Appalling and Very Poor
178 (this->town_label
++, r
<= RATING_MEDIOCRE
) || // Poor and Mediocre
179 (this->town_label
++, r
<= RATING_GOOD
) || // Good
180 (this->town_label
++, r
<= RATING_VERYGOOD
) || // Very Good
181 (this->town_label
++, true); // Excellent and Outstanding
186 * Get the cost for removing this house
187 * @return the cost (inflation corrected etc)
189 Money
HouseSpec::GetRemovalCost() const
191 return (_price
[PR_CLEAR_HOUSE
] * this->removal_cost
) >> 8;
195 static int _grow_town_result
;
197 /* Describe the possible states */
198 enum TownGrowthResult
{
200 GROWTH_SEARCH_STOPPED
= 0
201 // GROWTH_SEARCH_RUNNING >= 1
204 static bool BuildTownHouse(Town
*t
, TileIndex tile
);
205 static Town
*CreateRandomTown(uint attempts
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
);
207 static void TownDrawHouseLift(const TileInfo
*ti
)
209 AddChildSpriteScreen(SPR_LIFT
, PAL_NONE
, 14, 60 - GetLiftPosition(ti
->tile
));
212 typedef void TownDrawTileProc(const TileInfo
*ti
);
213 static TownDrawTileProc
* const _town_draw_tile_procs
[1] = {
218 * Return a random direction
220 * @return a random direction
222 static inline DiagDirection
RandomDiagDir()
224 return (DiagDirection
)(3 & Random());
228 * House Tile drawing handler.
229 * Part of the tile loop process
230 * @param ti TileInfo of the tile to draw
232 static void DrawTile_Town(TileInfo
*ti
)
234 HouseID house_id
= GetHouseType(ti
->tile
);
236 if (house_id
>= NEW_HOUSE_OFFSET
) {
237 /* Houses don't necessarily need new graphics. If they don't have a
238 * spritegroup associated with them, then the sprite for the substitute
239 * house id is drawn instead. */
240 if (HouseSpec::Get(house_id
)->grf_prop
.spritegroup
[0] != nullptr) {
241 DrawNewHouseTile(ti
, house_id
);
244 house_id
= HouseSpec::Get(house_id
)->grf_prop
.subst_id
;
248 /* Retrieve pointer to the draw town tile struct */
249 const DrawBuildingsTileStruct
*dcts
= &_town_draw_tile_data
[house_id
<< 4 | TileHash2Bit(ti
->x
, ti
->y
) << 2 | GetHouseBuildingStage(ti
->tile
)];
251 if (ti
->tileh
!= SLOPE_FLAT
) DrawFoundation(ti
, FOUNDATION_LEVELED
);
253 DrawGroundSprite(dcts
->ground
.sprite
, dcts
->ground
.pal
);
255 DrawOverlay(ti
, MP_HOUSE
);
257 /* If houses are invisible, do not draw the upper part */
258 if (IsInvisibilitySet(TO_HOUSES
)) return;
260 /* Add a house on top of the ground? */
261 SpriteID image
= dcts
->building
.sprite
;
263 AddSortableSpriteToDraw(image
, dcts
->building
.pal
,
264 ti
->x
+ dcts
->subtile_x
,
265 ti
->y
+ dcts
->subtile_y
,
270 IsTransparencySet(TO_HOUSES
)
273 if (IsTransparencySet(TO_HOUSES
)) return;
277 int proc
= dcts
->draw_proc
- 1;
279 if (proc
>= 0) _town_draw_tile_procs
[proc
](ti
);
283 static int GetSlopePixelZ_Town(TileIndex tile
, uint x
, uint y
)
285 return GetTileMaxPixelZ(tile
);
288 /** Tile callback routine */
289 static Foundation
GetFoundation_Town(TileIndex tile
, Slope tileh
)
291 HouseID hid
= GetHouseType(tile
);
293 /* For NewGRF house tiles we might not be drawing a foundation. We need to
294 * account for this, as other structures should
295 * draw the wall of the foundation in this case.
297 if (hid
>= NEW_HOUSE_OFFSET
) {
298 const HouseSpec
*hs
= HouseSpec::Get(hid
);
299 if (hs
->grf_prop
.spritegroup
[0] != nullptr && HasBit(hs
->callback_mask
, CBM_HOUSE_DRAW_FOUNDATIONS
)) {
300 uint32 callback_res
= GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS
, 0, 0, hid
, Town::GetByTile(tile
), tile
);
301 if (callback_res
!= CALLBACK_FAILED
&& !ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_DRAW_FOUNDATIONS
, callback_res
)) return FOUNDATION_NONE
;
304 return FlatteningFoundation(tileh
);
308 * Animate a tile for a town
309 * Only certain houses can be animated
310 * The newhouses animation supersedes regular ones
311 * @param tile TileIndex of the house to animate
313 static void AnimateTile_Town(TileIndex tile
)
315 if (GetHouseType(tile
) >= NEW_HOUSE_OFFSET
) {
316 AnimateNewHouseTile(tile
);
320 if (_tick_counter
& 3) return;
322 /* If the house is not one with a lift anymore, then stop this animating.
323 * Not exactly sure when this happens, but probably when a house changes.
324 * Before this was just a return...so it'd leak animated tiles..
325 * That bug seems to have been here since day 1?? */
326 if (!(HouseSpec::Get(GetHouseType(tile
))->building_flags
& BUILDING_IS_ANIMATED
)) {
327 DeleteAnimatedTile(tile
);
331 if (!LiftHasDestination(tile
)) {
334 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
335 * This is due to the fact that the first floor is, in the graphics,
336 * the height of 2 'normal' floors.
337 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
340 } while (i
== 1 || i
* 6 == GetLiftPosition(tile
));
342 SetLiftDestination(tile
, i
);
345 int pos
= GetLiftPosition(tile
);
346 int dest
= GetLiftDestination(tile
) * 6;
347 pos
+= (pos
< dest
) ? 1 : -1;
348 SetLiftPosition(tile
, pos
);
352 DeleteAnimatedTile(tile
);
355 MarkTileDirtyByTile(tile
, ZOOM_LVL_DRAW_MAP
);
359 * Determines if a town is close to a tile
360 * @param tile TileIndex of the tile to query
361 * @param dist maximum distance to be accepted
362 * @returns true if the tile correspond to the distance criteria
364 static bool IsCloseToTown(TileIndex tile
, uint dist
)
366 /* On a large map with many towns, it may be faster to check the surroundings of the tile.
367 * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
368 if (Town::GetNumItems() > (size_t) (dist
* dist
* 2)) {
369 const int tx
= TileX(tile
);
370 const int ty
= TileY(tile
);
371 TileArea tile_area
= TileArea(
372 TileXY(max(0, tx
- (int) dist
), max(0, ty
- (int) dist
)),
373 TileXY(min(MapMaxX(), tx
+ (int) dist
), min(MapMaxY(), ty
+ (int) dist
))
375 TILE_AREA_LOOP(atile
, tile_area
) {
376 if (GetTileType(atile
) == MP_HOUSE
) {
377 Town
*t
= Town::GetByTile(atile
);
378 if (DistanceManhattan(tile
, t
->xy
) < dist
) return true;
387 if (DistanceManhattan(tile
, t
->xy
) < dist
) return true;
393 * Resize the sign(label) of the town after changes in
394 * population (creation or growth or else)
396 void Town::UpdateVirtCoord()
399 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
400 SetDParam(0, this->index
);
401 SetDParam(1, this->cache
.population
);
402 this->cache
.sign
.UpdatePosition(pt
.x
, pt
.y
- 24 * ZOOM_LVL_BASE
, this->Label());
404 SetWindowDirty(WC_TOWN_VIEW
, this->index
);
407 /** Update the virtual coords needed to draw the town sign for all towns. */
408 void UpdateAllTownVirtCoords()
413 t
->UpdateVirtCoord();
418 * Change the towns population
419 * @param t Town which population has changed
420 * @param mod population change (can be positive or negative)
422 static void ChangePopulation(Town
*t
, int mod
)
424 t
->cache
.population
+= mod
;
425 InvalidateWindowData(WC_TOWN_VIEW
, t
->index
); // Cargo requirements may appear/vanish for small populations
426 t
->UpdateVirtCoord();
428 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 1);
432 * Determines the world population
433 * Basically, count population of all towns, one by one
434 * @return uint32 the calculated population of the world
436 uint32
GetWorldPopulation()
441 FOR_ALL_TOWNS(t
) pop
+= t
->cache
.population
;
446 * Helper function for house completion stages progression
447 * @param tile TileIndex of the house (or parts of it) to "grow"
449 static void MakeSingleHouseBigger(TileIndex tile
)
451 assert(IsTileType(tile
, MP_HOUSE
));
453 /* progress in construction stages */
454 IncHouseConstructionTick(tile
);
455 if (GetHouseConstructionTick(tile
) != 0) return;
457 AnimateNewHouseConstruction(tile
);
459 if (IsHouseCompleted(tile
)) {
460 /* Now that construction is complete, we can add the population of the
461 * building to the town. */
462 ChangePopulation(Town::GetByTile(tile
), HouseSpec::Get(GetHouseType(tile
))->population
);
465 MarkTileDirtyByTile(tile
, ZOOM_LVL_DRAW_MAP
);
469 * Make the house advance in its construction stages until completion
470 * @param tile TileIndex of house
472 static void MakeTownHouseBigger(TileIndex tile
)
474 uint flags
= HouseSpec::Get(GetHouseType(tile
))->building_flags
;
475 if (flags
& BUILDING_HAS_1_TILE
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 0, 0));
476 if (flags
& BUILDING_2_TILES_Y
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 0, 1));
477 if (flags
& BUILDING_2_TILES_X
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 1, 0));
478 if (flags
& BUILDING_HAS_4_TILES
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 1, 1));
482 * Generate cargo for a town (house).
484 * The amount of cargo should be and will be greater than zero.
486 * @param t current town
487 * @param ct type of cargo to generate, usually CT_PASSENGERS or CT_MAIL
488 * @param amount how many units of cargo
489 * @param stations available stations for this house
490 * @param economy_adjust true if amount should be reduced during recession
492 static void TownGenerateCargo(Town
*t
, CargoID ct
, uint amount
, StationFinder
&stations
, bool economy_adjust
)
494 // custom cargo generation factor
495 int cf
= _settings_game
.economy
.town_cargo_factor
;
497 // when the economy flunctuates, everyone wants to stay at home
498 if (economy_adjust
&& EconomyIsInRecession()) {
499 amount
= (amount
+ 1) >> 1;
502 // apply custom factor?
504 // approx (amount / 2^cf)
505 // adjust with a constant offset of {(2 ^ cf) - 1} (i.e. add cf * 1-bits) before dividing to ensure that it doesn't become zero
506 // this skews the curve a little so that isn't entirely exponential, but will still decrease
507 amount
= (amount
+ ((1 << -cf
) - 1)) >> -cf
;
511 // approx (amount * 2^cf)
513 amount
= amount
<< cf
;
516 // with the adjustments above, this should never happen
519 // calculate for town stats
523 t
->supplied
[ct
].new_max
+= amount
;
524 t
->supplied
[ct
].new_act
+= MoveGoodsToStation(ct
, amount
, ST_TOWN
, t
->index
, stations
.GetStations());
528 const CargoSpec
*cs
= CargoSpec::Get(ct
);
529 t
->supplied
[cs
->Index()].new_max
+= amount
;
530 t
->supplied
[cs
->Index()].new_act
+= MoveGoodsToStation(ct
, amount
, ST_TOWN
, t
->index
, stations
.GetStations());
537 * Tile callback function.
539 * Periodic tic handler for houses and town
540 * @param tile been asked to do its stuff
542 static void TileLoop_Town(TileIndex tile
)
544 HouseID house_id
= GetHouseType(tile
);
546 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
547 * doesn't exist any more, so don't continue here. */
548 if (house_id
>= NEW_HOUSE_OFFSET
&& !NewHouseTileLoop(tile
)) return;
550 if (!IsHouseCompleted(tile
)) {
551 /* Construction is not completed. See if we can go further in construction*/
552 MakeTownHouseBigger(tile
);
556 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
558 /* If the lift has a destination, it is already an animated tile. */
559 if ((hs
->building_flags
& BUILDING_IS_ANIMATED
) &&
560 house_id
< NEW_HOUSE_OFFSET
&&
561 !LiftHasDestination(tile
) &&
563 AddAnimatedTile(tile
);
566 Town
*t
= Town::GetByTile(tile
);
569 StationFinder
stations(TileArea(tile
, 1, 1));
571 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
572 for (uint i
= 0; i
< 256; i
++) {
573 uint16 callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, r
, house_id
, t
, tile
);
575 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
577 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
578 if (cargo
== CT_INVALID
) continue;
580 uint amt
= GB(callback
, 0, 8);
581 if (amt
== 0) continue;
583 // XXX: no economy flunctuation for GRF cargos?
584 TownGenerateCargo(t
, cargo
, amt
, stations
, false);
587 if (GB(r
, 0, 8) < hs
->population
) {
588 uint amt
= GB(r
, 16, 3) + 1;
590 TownGenerateCargo(t
, CT_PASSENGERS
, amt
, stations
, true);
593 if (GB(r
, 8, 8) < hs
->mail_generation
) {
594 uint amt
= GB(r
, 24, 3) + 1;
596 TownGenerateCargo(t
, CT_MAIL
, amt
, stations
, true);
600 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
602 const int32 ticks_per_tile_loop
= 256;
604 if ((hs
->building_flags
& BUILDING_HAS_1_TILE
) &&
606 CanDeleteHouse(tile
) &&
607 GetHouseAge(tile
) >= hs
->minimum_life
&&
608 t
->time_until_rebuild
<= (_date
- (hs
->minimum_life
* DAYS_IN_YEAR
))) {
610 int32 tile_loops_until_rebuild
= GB(r
, 16, 8) + 192;
611 t
->time_until_rebuild
= _date
+ ((tile_loops_until_rebuild
* ticks_per_tile_loop
) / DEFAULT_DAY_TICKS
);
613 ClearTownHouse(t
, tile
);
615 /* Rebuild with another house? */
616 if (GB(r
, 24, 8) >= 12) BuildTownHouse(t
, tile
);
619 cur_company
.Restore();
622 static CommandCost
ClearTile_Town(TileIndex tile
, DoCommandFlag flags
)
624 if (flags
& DC_AUTO
) return CommandError(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
625 if (!CanDeleteHouse(tile
)) return CommandError();
627 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
629 CommandCost
cost(EXPENSES_CONSTRUCTION
);
630 cost
.AddCost(hs
->GetRemovalCost());
632 int rating
= hs
->remove_rating_decrease
;
633 Town
*t
= Town::GetByTile(tile
);
635 if (Company::IsValidID(_current_company
)) {
636 if (rating
> t
->ratings
[_current_company
] && !(flags
& DC_NO_TEST_TOWN_RATING
) && !_cheats
.magic_bulldozer
.value
) {
637 SetDParam(0, t
->index
);
638 return CommandError(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
642 ChangeTownRating(t
, -rating
, RATING_HOUSE_MINIMUM
, flags
);
643 if (flags
& DC_EXEC
) {
644 ClearTownHouse(t
, tile
);
650 static void AddProducedCargo_Town(TileIndex tile
, CargoArray
&produced
)
652 HouseID house_id
= GetHouseType(tile
);
653 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
654 Town
*t
= Town::GetByTile(tile
);
656 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
657 for (uint i
= 0; i
< 256; i
++) {
658 uint16 callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, 0, house_id
, t
, tile
);
660 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
662 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
664 if (cargo
== CT_INVALID
) continue;
668 if (hs
->population
> 0) {
669 produced
[CT_PASSENGERS
]++;
671 if (hs
->mail_generation
> 0) {
677 static inline void AddAcceptedCargoSetMask(CargoID cargo
, uint amount
, CargoArray
&acceptance
, uint32
*always_accepted
)
679 if (cargo
== CT_INVALID
|| amount
== 0) return;
680 acceptance
[cargo
] += amount
;
681 SetBit(*always_accepted
, cargo
);
684 static void AddAcceptedCargo_Town(TileIndex tile
, CargoArray
&acceptance
, uint32
*always_accepted
)
686 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
689 /* Set the initial accepted cargo types */
690 for (uint8 i
= 0; i
< lengthof(accepts
); i
++) {
691 accepts
[i
] = hs
->accepts_cargo
[i
];
694 /* Check for custom accepted cargo types */
695 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ACCEPT_CARGO
)) {
696 uint16 callback
= GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
697 if (callback
!= CALLBACK_FAILED
) {
698 /* Replace accepted cargo types with translated values from callback */
699 accepts
[0] = GetCargoTranslation(GB(callback
, 0, 5), hs
->grf_prop
.grffile
);
700 accepts
[1] = GetCargoTranslation(GB(callback
, 5, 5), hs
->grf_prop
.grffile
);
701 accepts
[2] = GetCargoTranslation(GB(callback
, 10, 5), hs
->grf_prop
.grffile
);
705 /* Check for custom cargo acceptance */
706 if (HasBit(hs
->callback_mask
, CBM_HOUSE_CARGO_ACCEPTANCE
)) {
707 uint16 callback
= GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
708 if (callback
!= CALLBACK_FAILED
) {
709 AddAcceptedCargoSetMask(accepts
[0], GB(callback
, 0, 4), acceptance
, always_accepted
);
710 AddAcceptedCargoSetMask(accepts
[1], GB(callback
, 4, 4), acceptance
, always_accepted
);
711 if (_settings_game
.game_creation
.landscape
!= LT_TEMPERATE
&& HasBit(callback
, 12)) {
712 /* The 'S' bit indicates food instead of goods */
713 AddAcceptedCargoSetMask(CT_FOOD
, GB(callback
, 8, 4), acceptance
, always_accepted
);
715 AddAcceptedCargoSetMask(accepts
[2], GB(callback
, 8, 4), acceptance
, always_accepted
);
721 /* No custom acceptance, so fill in with the default values */
722 for (uint8 i
= 0; i
< lengthof(accepts
); i
++) {
723 AddAcceptedCargoSetMask(accepts
[i
], hs
->cargo_acceptance
[i
], acceptance
, always_accepted
);
727 static void GetTileDesc_Town(TileIndex tile
, TileDesc
*td
)
729 const HouseID house
= GetHouseType(tile
);
730 const HouseSpec
*hs
= HouseSpec::Get(house
);
731 bool house_completed
= IsHouseCompleted(tile
);
733 td
->str
= hs
->building_name
;
735 uint16 callback_res
= GetHouseCallback(CBID_HOUSE_CUSTOM_NAME
, house_completed
? 1 : 0, 0, house
, Town::GetByTile(tile
), tile
);
736 if (callback_res
!= CALLBACK_FAILED
&& callback_res
!= 0x400) {
737 if (callback_res
> 0x400) {
738 ErrorUnknownCallbackResult(hs
->grf_prop
.grffile
->grfid
, CBID_HOUSE_CUSTOM_NAME
, callback_res
);
740 StringID new_name
= GetGRFStringID(hs
->grf_prop
.grffile
->grfid
, 0xD000 + callback_res
);
741 if (new_name
!= STR_NULL
&& new_name
!= STR_UNDEFINED
) {
747 if (!house_completed
) {
748 SetDParamX(td
->dparam
, 0, td
->str
);
749 td
->str
= STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION
;
752 if (hs
->grf_prop
.grffile
!= nullptr) {
753 const GRFConfig
*gc
= GetGRFConfig(hs
->grf_prop
.grffile
->grfid
);
754 td
->grf
= gc
->GetName();
757 td
->owner
[0] = OWNER_TOWN
;
760 static TrackStatus
GetTileTrackStatus_Town(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
766 static void ChangeTileOwner_Town(TileIndex tile
, Owner old_owner
, Owner new_owner
)
771 /** Update the total cargo acceptance of the whole town.
772 * @param t The town to update.
774 void UpdateTownCargoTotal(Town
*t
)
776 t
->cargo_accepted_total
= 0;
778 const TileArea
&area
= t
->cargo_accepted
.GetArea();
779 TILE_AREA_LOOP(tile
, area
) {
780 if (TileX(tile
) % AcceptanceMatrix::GRID
== 0 && TileY(tile
) % AcceptanceMatrix::GRID
== 0) {
781 t
->cargo_accepted_total
|= t
->cargo_accepted
[tile
];
787 * Update accepted town cargoes around a specific tile.
788 * @param t The town to update.
789 * @param start Update the values around this tile.
790 * @param update_total Set to true if the total cargo acceptance should be updated.
792 static void UpdateTownCargoes(Town
*t
, TileIndex start
, bool update_total
= true)
794 CargoArray accepted
, produced
;
797 /* Gather acceptance for all houses in an area around the start tile.
798 * The area is composed of the square the tile is in, extended one square in all
799 * directions as the coverage area of a single station is bigger than just one square. */
800 TileArea area
= AcceptanceMatrix::GetAreaForTile(start
, 1);
801 TILE_AREA_LOOP(tile
, area
) {
802 if (!IsTileType(tile
, MP_HOUSE
) || GetTownIndex(tile
) != t
->index
) continue;
804 AddAcceptedCargo_Town(tile
, accepted
, &dummy
);
805 AddProducedCargo_Town(tile
, produced
);
808 /* Create bitmap of produced and accepted cargoes. */
810 for (uint cid
= 0; cid
< NUM_CARGO
; cid
++) {
811 if (accepted
[cid
] >= 8) SetBit(acc
, cid
);
812 if (produced
[cid
] > 0) SetBit(t
->cargo_produced
, cid
);
814 t
->cargo_accepted
[start
] = acc
;
816 if (update_total
) UpdateTownCargoTotal(t
);
819 /** Update cargo acceptance for the complete town.
820 * @param t The town to update.
822 void UpdateTownCargoes(Town
*t
)
824 t
->cargo_produced
= 0;
826 const TileArea
&area
= t
->cargo_accepted
.GetArea();
827 if (area
.tile
== INVALID_TILE
) return;
829 /* Update acceptance for each grid square. */
830 TILE_AREA_LOOP(tile
, area
) {
831 if (TileX(tile
) % AcceptanceMatrix::GRID
== 0 && TileY(tile
) % AcceptanceMatrix::GRID
== 0) {
832 UpdateTownCargoes(t
, tile
, false);
836 /* Update the total acceptance. */
837 UpdateTownCargoTotal(t
);
840 /** Updates the bitmap of all cargoes accepted by houses. */
841 void UpdateTownCargoBitmap()
844 _town_cargoes_accepted
= 0;
846 FOR_ALL_TOWNS(town
) {
847 _town_cargoes_accepted
|= town
->cargo_accepted_total
;
851 static bool GrowTown(Town
*t
);
853 static void TownTickHandler(Town
*t
)
855 if (t
->IsGrowing()) {
856 auto i
= t
->grow_counter
- 1;
862 /* If growth failed wait a bit before retrying */
863 i
= min(t
->growth_rate
, TOWN_GROWTH_TICKS
- 1);
873 if (_game_mode
== GM_EDITOR
) return;
882 * Return the RoadBits of a tile
884 * @note There are many other functions doing things like that.
885 * @note Needs to be checked for needlessness.
886 * @param tile The tile we want to analyse
887 * @return The roadbits of the given tile
889 static RoadBits
GetTownRoadBits(TileIndex tile
)
891 if (IsRoadDepotTile(tile
) || IsStandardRoadStopTile(tile
)) return ROAD_NONE
;
893 return GetAnyRoadBits(tile
, ROADTYPE_ROAD
, true);
897 * Check for parallel road inside a given distance.
898 * Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
899 * is there a parallel road left or right of it within distance dist_multi?
901 * @param tile current tile
902 * @param dir target direction
903 * @param dist_multi distance multiplayer
904 * @return true if there is a parallel road
906 static bool IsNeighborRoadTile(TileIndex tile
, const DiagDirection dir
, uint dist_multi
)
908 if (!IsValidTile(tile
)) return false;
910 /* Lookup table for the used diff values */
911 const TileIndexDiff tid_lt
[3] = {
912 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90RIGHT
)),
913 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90LEFT
)),
914 TileOffsByDiagDir(ReverseDiagDir(dir
)),
917 dist_multi
= (dist_multi
+ 1) * 4;
918 for (uint pos
= 4; pos
< dist_multi
; pos
++) {
919 /* Go (pos / 4) tiles to the left or the right */
920 TileIndexDiff cur
= tid_lt
[(pos
& 1) ? 0 : 1] * (pos
/ 4);
922 /* Use the current tile as origin, or go one tile backwards */
923 if (pos
& 2) cur
+= tid_lt
[2];
925 /* Test for roadbit parallel to dir and facing towards the middle axis */
926 if (IsValidTile(tile
+ cur
) &&
927 GetTownRoadBits(TILE_ADD(tile
, cur
)) & DiagDirToRoadBits((pos
& 2) ? dir
: ReverseDiagDir(dir
))) return true;
933 * Check if a Road is allowed on a given tile
935 * @param t The current town
936 * @param tile The target tile
937 * @param dir The direction in which we want to extend the town
938 * @return true if it is allowed else false
940 static bool IsRoadAllowedHere(Town
*t
, TileIndex tile
, DiagDirection dir
)
942 if (DistanceFromEdge(tile
) == 0) return false;
944 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
945 if (IsBridgeAbove(tile
) && GetBridgeAxis(tile
) == DiagDirToAxis(dir
)) return false;
947 /* Check if there already is a road at this point? */
948 if (GetTownRoadBits(tile
) == ROAD_NONE
) {
949 /* No, try if we are able to build a road piece there.
950 * If that fails clear the land, and if that fails exit.
951 * This is to make sure that we can build a road here later. */
952 RoadTypeIdentifier
rtid(ROADTYPE_ROAD
, ROADSUBTYPE_NORMAL
); // TODO
953 if (DoCommand(tile
, ((dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? ROAD_Y
: ROAD_X
) | (rtid
.Pack() << 4), 0, DC_AUTO
, CMD_BUILD_ROAD
).Failed() &&
954 DoCommand(tile
, 0, 0, DC_AUTO
, CMD_LANDSCAPE_CLEAR
).Failed()) {
959 Slope cur_slope
= _settings_game
.construction
.build_on_slopes
? GetFoundationSlope(tile
) : GetTileSlope(tile
);
960 bool ret
= !IsNeighborRoadTile(tile
, dir
, t
->layout
== TL_ORIGINAL
? 1 : 2);
961 if (cur_slope
== SLOPE_FLAT
) return ret
;
963 /* If the tile is not a slope in the right direction, then
964 * maybe terraform some. */
965 Slope desired_slope
= (dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? SLOPE_NW
: SLOPE_NE
;
966 if (desired_slope
!= cur_slope
&& ComplementSlope(desired_slope
) != cur_slope
) {
967 if (Chance16(1, 8)) {
968 CommandCost res
= CommandError();
969 if (!_generating_world
&& Chance16(1, 10)) {
970 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
971 res
= DoCommand(tile
, Chance16(1, 16) ? cur_slope
: cur_slope
^ SLOPE_ELEVATED
, 0,
972 DC_EXEC
| DC_AUTO
| DC_NO_WATER
, CMD_TERRAFORM_LAND
);
974 if (res
.Failed() && Chance16(1, 3)) {
975 /* We can consider building on the slope, though. */
984 static bool TerraformTownTile(TileIndex tile
, int edges
, int dir
)
986 assert(tile
< MapSize());
988 CommandCost r
= DoCommand(tile
, edges
, dir
, DC_AUTO
| DC_NO_WATER
, CMD_TERRAFORM_LAND
);
989 if (r
.Failed() || r
.GetCost() >= (_price
[PR_TERRAFORM
] + 2) * 8) return false;
990 DoCommand(tile
, edges
, dir
, DC_AUTO
| DC_NO_WATER
| DC_EXEC
, CMD_TERRAFORM_LAND
);
994 static void LevelTownLand(TileIndex tile
)
996 assert(tile
< MapSize());
998 /* Don't terraform if land is plain or if there's a house there. */
999 if (IsTileType(tile
, MP_HOUSE
)) return;
1000 Slope tileh
= GetTileSlope(tile
);
1001 if (tileh
== SLOPE_FLAT
) return;
1003 /* First try up, then down */
1004 if (!TerraformTownTile(tile
, ~tileh
& SLOPE_ELEVATED
, 1)) {
1005 TerraformTownTile(tile
, tileh
& SLOPE_ELEVATED
, 0);
1010 * Generate the RoadBits of a grid tile
1012 * @param t current town
1013 * @param tile tile in reference to the town
1014 * @param dir The direction to which we are growing ATM
1015 * @return the RoadBit of the current tile regarding
1016 * the selected town layout
1018 static RoadBits
GetTownRoadGridElement(Town
*t
, TileIndex tile
, DiagDirection dir
)
1020 /* align the grid to the downtown */
1021 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
); // Vector from downtown to the tile
1022 RoadBits rcmd
= ROAD_NONE
;
1024 switch (t
->layout
) {
1025 default: NOT_REACHED();
1028 if ((grid_pos
.x
% 3) == 0) rcmd
|= ROAD_Y
;
1029 if ((grid_pos
.y
% 3) == 0) rcmd
|= ROAD_X
;
1033 if ((grid_pos
.x
% 4) == 0) rcmd
|= ROAD_Y
;
1034 if ((grid_pos
.y
% 4) == 0) rcmd
|= ROAD_X
;
1038 /* Optimise only X-junctions */
1039 if (rcmd
!= ROAD_ALL
) return rcmd
;
1041 RoadBits rb_template
;
1043 switch (GetTileSlope(tile
)) {
1044 default: rb_template
= ROAD_ALL
; break;
1045 case SLOPE_W
: rb_template
= ROAD_NW
| ROAD_SW
; break;
1046 case SLOPE_SW
: rb_template
= ROAD_Y
| ROAD_SW
; break;
1047 case SLOPE_S
: rb_template
= ROAD_SW
| ROAD_SE
; break;
1048 case SLOPE_SE
: rb_template
= ROAD_X
| ROAD_SE
; break;
1049 case SLOPE_E
: rb_template
= ROAD_SE
| ROAD_NE
; break;
1050 case SLOPE_NE
: rb_template
= ROAD_Y
| ROAD_NE
; break;
1051 case SLOPE_N
: rb_template
= ROAD_NE
| ROAD_NW
; break;
1052 case SLOPE_NW
: rb_template
= ROAD_X
| ROAD_NW
; break;
1057 rb_template
= ROAD_NONE
;
1061 /* Stop if the template is compatible to the growth dir */
1062 if (DiagDirToRoadBits(ReverseDiagDir(dir
)) & rb_template
) return rb_template
;
1063 /* If not generate a straight road in the direction of the growth */
1064 return DiagDirToRoadBits(dir
) | DiagDirToRoadBits(ReverseDiagDir(dir
));
1068 * Grows the town with an extra house.
1069 * Check if there are enough neighbor house tiles
1070 * next to the current tile. If there are enough
1071 * add another house.
1073 * @param t The current town
1074 * @param tile The target tile for the extra house
1075 * @return true if an extra house has been added
1077 static bool GrowTownWithExtraHouse(Town
*t
, TileIndex tile
)
1079 /* We can't look further than that. */
1080 if (DistanceFromEdge(tile
) == 0) return false;
1082 uint counter
= 0; // counts the house neighbor tiles
1084 /* Check the tiles E,N,W and S of the current tile for houses */
1085 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
< DIAGDIR_END
; dir
++) {
1086 /* Count both void and house tiles for checking whether there
1087 * are enough houses in the area. This to make it likely that
1088 * houses get build up to the edge of the map. */
1089 switch (GetTileType(TileAddByDiagDir(tile
, dir
))) {
1099 /* If there are enough neighbors stop here */
1101 if (BuildTownHouse(t
, tile
)) {
1102 _grow_town_result
= GROWTH_SUCCEED
;
1112 * Grows the town with a road piece.
1114 * @param t The current town
1115 * @param tile The current tile
1116 * @param rcmd The RoadBits we want to build on the tile
1117 * @return true if the RoadBits have been added else false
1119 static bool GrowTownWithRoad(const Town
*t
, TileIndex tile
, RoadBits rcmd
)
1121 RoadTypeIdentifier
rtid(ROADTYPE_ROAD
, ROADSUBTYPE_NORMAL
); // TODO
1122 if (DoCommand(tile
, rcmd
| (rtid
.Pack() << 4), t
->index
, DC_EXEC
| DC_AUTO
| DC_NO_WATER
, CMD_BUILD_ROAD
).Succeeded()) {
1123 _grow_town_result
= GROWTH_SUCCEED
;
1130 * Grows the town with a bridge.
1131 * At first we check if a bridge is reasonable.
1132 * If so we check if we are able to build it.
1134 * @param t The current town
1135 * @param tile The current tile
1136 * @param bridge_dir The valid direction in which to grow a bridge
1137 * @return true if a bridge has been build else false
1139 static bool GrowTownWithBridge(const Town
*t
, const TileIndex tile
, const DiagDirection bridge_dir
)
1141 assert(bridge_dir
< DIAGDIR_END
);
1143 const Slope slope
= GetTileSlope(tile
);
1145 /* Make sure the direction is compatible with the slope.
1146 * Well we check if the slope has an up bit set in the
1147 * reverse direction. */
1148 if (slope
!= SLOPE_FLAT
&& slope
& InclinedSlope(bridge_dir
)) return false;
1150 /* Assure that the bridge is connectable to the start side */
1151 if (!(GetTownRoadBits(TileAddByDiagDir(tile
, ReverseDiagDir(bridge_dir
))) & DiagDirToRoadBits(bridge_dir
))) return false;
1153 /* We are in the right direction */
1154 uint8 bridge_length
= 0; // This value stores the length of the possible bridge
1155 TileIndex bridge_tile
= tile
; // Used to store the other waterside
1157 const int delta
= TileOffsByDiagDir(bridge_dir
);
1159 if (slope
== SLOPE_FLAT
) {
1160 /* Bridges starting on flat tiles are only allowed when crossing rivers or rails. */
1162 if (bridge_length
++ >= 5) {
1163 /* Allow to cross rivers, not big lakes, nor large amounts of rails. */
1166 bridge_tile
+= delta
;
1167 } while (IsValidTile(bridge_tile
) && ((IsWaterTile(bridge_tile
) && !IsSea(bridge_tile
)) || IsPlainRailTile(bridge_tile
)));
1170 if (bridge_length
++ >= 11) {
1171 /* Max 11 tile long bridges */
1174 bridge_tile
+= delta
;
1175 } while (IsValidTile(bridge_tile
) && (IsWaterTile(bridge_tile
) || IsPlainRailTile(bridge_tile
)));
1178 /* no water tiles in between? */
1179 if (bridge_length
== 1) return false;
1181 for (uint8 times
= 0; times
<= 22; times
++) {
1182 byte bridge_type
= RandomRange(MAX_BRIDGES
- 1);
1184 /* Can we actually build the bridge? */
1185 RoadTypeIdentifier
rtid(ROADTYPE_ROAD
, ROADSUBTYPE_NORMAL
); // TODO
1186 if (DoCommand(tile
, bridge_tile
, bridge_type
| rtid
.Pack() << 8 | TRANSPORT_ROAD
<< 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE
)), CMD_BUILD_BRIDGE
).Succeeded()) {
1187 DoCommand(tile
, bridge_tile
, bridge_type
| rtid
.Pack() << 8 | TRANSPORT_ROAD
<< 15, DC_EXEC
| CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE
)), CMD_BUILD_BRIDGE
);
1188 _grow_town_result
= GROWTH_SUCCEED
;
1192 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1198 * Checks whether at least one surrounding roads allows to build a house here
1200 * @param t the tile where the house will be built
1201 * @return true if at least one surrounding roadtype allows building houses here
1203 static inline bool RoadTypesAllowHouseHere(TileIndex t
)
1205 static const TileIndexDiffC tiles
[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1206 const TileIndexDiffC
*ptr
;
1209 for (ptr
= tiles
; ptr
!= endof(tiles
); ++ptr
) {
1210 TileIndex cur_tile
= t
+ ToTileIndexDiff(*ptr
);
1212 if (!(IsTileType(cur_tile
, MP_ROAD
) || IsTileType(cur_tile
, MP_STATION
))) continue;
1215 RoadTypeIdentifier rtid
;
1216 RoadTypeIdentifiers rtids
= RoadTypeIdentifiers::FromTile(cur_tile
);
1217 FOR_EACH_SET_ROADTYPEIDENTIFIER(rtid
, rtids
)
1219 /* Found one road which allows the type, it is enough to allow building the house here */
1220 if (!HasBit(GetRoadTypeInfo(rtid
)->flags
, ROTF_NO_HOUSES
)) return true;
1224 /* If no road was found surrounding the tile we can allow building the house since there is
1225 * nothing which forbids it, if a road was found but the execution reached this point, then
1226 * all the found roads don't allow houses to be built */
1231 * Grows the given town.
1232 * There are at the moment 3 possible way's for
1233 * the town expansion:
1234 * @li Generate a random tile and check if there is a road allowed
1236 * @li TL_BETTER_ROADS
1237 * @li Check if the town geometry allows a road and which one
1240 * @li Forbid roads, only build houses
1242 * @param tile_ptr The current tile
1243 * @param cur_rb The current tiles RoadBits
1244 * @param target_dir The target road dir
1245 * @param t1 The current town
1247 static void GrowTownInTile(TileIndex
*tile_ptr
, RoadBits cur_rb
, DiagDirection target_dir
, Town
*t1
)
1249 RoadBits rcmd
= ROAD_NONE
; // RoadBits for the road construction command
1250 TileIndex tile
= *tile_ptr
; // The main tile on which we base our growth
1252 assert(tile
< MapSize());
1254 if (cur_rb
== ROAD_NONE
) {
1255 /* Tile has no road. First reset the status counter
1256 * to say that this is the last iteration. */
1257 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1259 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return;
1260 if (!_settings_game
.economy
.allow_town_level_crossings
&& IsTileType(tile
, MP_RAILWAY
)) return;
1262 /* Remove hills etc */
1263 if (!_settings_game
.construction
.build_on_slopes
|| Chance16(1, 6)) LevelTownLand(tile
);
1265 /* Is a road allowed here? */
1266 switch (t1
->layout
) {
1267 default: NOT_REACHED();
1271 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1272 if (rcmd
== ROAD_NONE
) return;
1275 case TL_BETTER_ROADS
:
1277 if (!IsRoadAllowedHere(t1
, tile
, target_dir
)) return;
1279 DiagDirection source_dir
= ReverseDiagDir(target_dir
);
1281 if (Chance16(1, 4)) {
1282 /* Randomize a new target dir */
1283 do target_dir
= RandomDiagDir(); while (target_dir
== source_dir
);
1286 if (!IsRoadAllowedHere(t1
, TileAddByDiagDir(tile
, target_dir
), target_dir
)) {
1287 /* A road is not allowed to continue the randomized road,
1288 * return if the road we're trying to build is curved. */
1289 if (target_dir
!= ReverseDiagDir(source_dir
)) return;
1291 /* Return if neither side of the new road is a house */
1292 if (!IsTileType(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90RIGHT
)), MP_HOUSE
) &&
1293 !IsTileType(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90LEFT
)), MP_HOUSE
)) {
1297 /* That means that the road is only allowed if there is a house
1298 * at any side of the new road. */
1301 rcmd
= DiagDirToRoadBits(target_dir
) | DiagDirToRoadBits(source_dir
);
1305 } else if (target_dir
< DIAGDIR_END
&& !(cur_rb
& DiagDirToRoadBits(ReverseDiagDir(target_dir
)))) {
1306 /* Continue building on a partial road.
1307 * Should be always OK, so we only generate
1308 * the fitting RoadBits */
1309 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1311 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return;
1313 switch (t1
->layout
) {
1314 default: NOT_REACHED();
1318 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1321 case TL_BETTER_ROADS
:
1323 rcmd
= DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1327 bool allow_house
= true; // Value which decides if we want to construct a house
1329 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1330 * it is the starting tile. Half the time, we stay on this side then.*/
1331 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1332 if (GetTunnelBridgeTransportType(tile
) == TRANSPORT_ROAD
&& (target_dir
!= DIAGDIR_END
|| Chance16(1, 2))) {
1333 *tile_ptr
= GetOtherTunnelBridgeEnd(tile
);
1338 /* Possibly extend the road in a direction.
1339 * Randomize a direction and if it has a road, bail out. */
1340 target_dir
= RandomDiagDir();
1341 if (cur_rb
& DiagDirToRoadBits(target_dir
)) return;
1343 /* This is the tile we will reach if we extend to this direction. */
1344 TileIndex house_tile
= TileAddByDiagDir(tile
, target_dir
); // position of a possible house
1346 /* Don't walk into water. */
1347 if (HasTileWaterGround(house_tile
)) return;
1349 if (!IsValidTile(house_tile
)) return;
1351 if (_settings_game
.economy
.allow_town_roads
|| _generating_world
) {
1352 switch (t1
->layout
) {
1353 default: NOT_REACHED();
1355 case TL_3X3_GRID
: // Use 2x2 grid afterwards!
1356 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1360 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1361 allow_house
= (rcmd
& DiagDirToRoadBits(target_dir
)) == ROAD_NONE
;
1364 case TL_BETTER_ROADS
: // Use original afterwards!
1365 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1369 /* Allow a house at the edge. 60% chance or
1370 * always ok if no road allowed. */
1371 rcmd
= DiagDirToRoadBits(target_dir
);
1372 allow_house
= (!IsRoadAllowedHere(t1
, house_tile
, target_dir
) || Chance16(6, 10));
1377 allow_house
&= RoadTypesAllowHouseHere(house_tile
);
1380 /* Build a house, but not if there already is a house there. */
1381 if (!IsTileType(house_tile
, MP_HOUSE
)) {
1382 /* Level the land if possible */
1383 if (Chance16(1, 6)) LevelTownLand(house_tile
);
1385 /* And build a house.
1386 * Set result to -1 if we managed to build it. */
1387 if (BuildTownHouse(t1
, house_tile
)) {
1388 _grow_town_result
= GROWTH_SUCCEED
;
1394 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1397 /* Return if a water tile */
1398 if (HasTileWaterGround(tile
)) return;
1400 /* Make the roads look nicer */
1401 rcmd
= CleanUpRoadBits(tile
, rcmd
);
1402 if (rcmd
== ROAD_NONE
) return;
1404 /* Only use the target direction for bridges to ensure they're connected.
1405 * The target_dir is as computed previously according to town layout, so
1406 * it will match it perfectly. */
1407 if (GrowTownWithBridge(t1
, tile
, target_dir
)) return;
1409 GrowTownWithRoad(t1
, tile
, rcmd
);
1413 * Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
1414 * This only checks trivial but often cases.
1415 * @param tile Start tile for road.
1416 * @param dir Direction for road to follow or build.
1417 * @return true If road is or can be connected in the specified direction.
1419 static bool CanFollowRoad(TileIndex tile
, DiagDirection dir
)
1421 TileIndex target_tile
= tile
+ TileOffsByDiagDir(dir
);
1422 if (!IsValidTile(target_tile
)) return false;
1423 if (HasTileWaterGround(target_tile
)) return false;
1425 RoadBits target_rb
= GetTownRoadBits(target_tile
);
1426 if (_settings_game
.economy
.allow_town_roads
|| _generating_world
) {
1427 /* Check whether a road connection exists or can be build. */
1428 switch (GetTileType(target_tile
)) {
1430 return target_rb
!= ROAD_NONE
;
1433 return IsDriveThroughStopTile(target_tile
);
1435 case MP_TUNNELBRIDGE
:
1436 return GetTunnelBridgeTransportType(target_tile
) == TRANSPORT_ROAD
;
1444 /* Checked for void and water earlier */
1448 /* Check whether a road connection already exists,
1449 * and it leads somewhere else. */
1450 RoadBits back_rb
= DiagDirToRoadBits(ReverseDiagDir(dir
));
1451 return (target_rb
& back_rb
) != 0 && (target_rb
& ~back_rb
) != 0;
1456 * Returns "growth" if a house was built, or no if the build failed.
1457 * @param t town to inquiry
1458 * @param tile to inquiry
1459 * @return true if town expansion was possible
1461 static bool GrowTownAtRoad(Town
*t
, TileIndex tile
)
1464 * @see GrowTownInTile Check the else if
1466 DiagDirection target_dir
= DIAGDIR_END
; // The direction in which we want to extend the town
1468 assert(tile
< MapSize());
1470 /* Number of times to search.
1471 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1472 * them a little handicap. */
1473 switch (t
->layout
) {
1474 case TL_BETTER_ROADS
:
1475 _grow_town_result
= 10 + t
->cache
.num_houses
* 2 / 9;
1480 _grow_town_result
= 10 + t
->cache
.num_houses
* 1 / 9;
1484 _grow_town_result
= 10 + t
->cache
.num_houses
* 4 / 9;
1489 RoadBits cur_rb
= GetTownRoadBits(tile
); // The RoadBits of the current tile
1491 /* Try to grow the town from this point */
1492 GrowTownInTile(&tile
, cur_rb
, target_dir
, t
);
1493 if (_grow_town_result
== GROWTH_SUCCEED
) return true;
1495 /* Exclude the source position from the bitmask
1496 * and return if no more road blocks available */
1497 if (IsValidDiagDirection(target_dir
)) cur_rb
&= ~DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1498 if (cur_rb
== ROAD_NONE
) return false;
1500 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1501 /* Only build in the direction away from the tunnel or bridge. */
1502 target_dir
= ReverseDiagDir(GetTunnelBridgeDirection(tile
));
1504 /* Select a random bit from the blockmask, walk a step
1505 * and continue the search from there. */
1507 if (cur_rb
== ROAD_NONE
) return false;
1508 RoadBits target_bits
;
1510 target_dir
= RandomDiagDir();
1511 target_bits
= DiagDirToRoadBits(target_dir
);
1512 } while (!(cur_rb
& target_bits
));
1513 cur_rb
&= ~target_bits
;
1514 } while (!CanFollowRoad(tile
, target_dir
));
1516 tile
= TileAddByDiagDir(tile
, target_dir
);
1518 if (IsTileType(tile
, MP_ROAD
) && !IsRoadDepot(tile
) && HasTileRoadType(tile
, ROADTYPE_ROAD
)) {
1519 /* Don't allow building over roads of other cities */
1520 if (IsRoadOwner(tile
, ROADTYPE_ROAD
, OWNER_TOWN
) && Town::GetByTile(tile
) != t
) {
1522 } else if (IsRoadOwner(tile
, ROADTYPE_ROAD
, OWNER_NONE
) && _game_mode
== GM_EDITOR
) {
1523 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1524 * owner :) (happy happy happy road now) */
1525 SetRoadOwner(tile
, ROADTYPE_ROAD
, OWNER_TOWN
);
1526 SetTownIndex(tile
, t
->index
);
1530 /* Max number of times is checked. */
1531 } while (--_grow_town_result
>= 0);
1537 * Generate a random road block.
1538 * The probability of a straight road
1539 * is somewhat higher than a curved.
1541 * @return A RoadBits value with 2 bits set
1543 static RoadBits
GenRandomRoadBits()
1545 uint32 r
= Random();
1546 uint a
= GB(r
, 0, 2);
1547 uint b
= GB(r
, 8, 2);
1549 return (RoadBits
)((ROAD_NW
<< a
) + (ROAD_NW
<< b
));
1554 * @param t town to grow
1555 * @return true iff something (house, road, bridge, ...) was built
1557 static bool GrowTown(Town
*t
)
1559 static const TileIndexDiffC _town_coord_mod
[] = {
1575 /* Current "company" is a town */
1576 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
1578 TileIndex tile
= t
->xy
; // The tile we are working with ATM
1580 /* Find a road that we can base the construction on. */
1581 const TileIndexDiffC
*ptr
;
1582 for (ptr
= _town_coord_mod
; ptr
!= endof(_town_coord_mod
); ++ptr
) {
1583 if (GetTownRoadBits(tile
) != ROAD_NONE
) {
1584 bool success
= GrowTownAtRoad(t
, tile
);
1585 cur_company
.Restore();
1588 tile
= TILE_ADD(tile
, ToTileIndexDiff(*ptr
));
1591 /* No road available, try to build a random road block by
1592 * clearing some land and then building a road there. */
1593 if (_settings_game
.economy
.allow_town_roads
|| _generating_world
) {
1595 for (ptr
= _town_coord_mod
; ptr
!= endof(_town_coord_mod
); ++ptr
) {
1596 /* Only work with plain land that not already has a house */
1597 if (!IsTileType(tile
, MP_HOUSE
) && IsTileFlat(tile
)) {
1598 if (DoCommand(tile
, 0, 0, DC_AUTO
| DC_NO_WATER
, CMD_LANDSCAPE_CLEAR
).Succeeded()) {
1599 RoadTypeIdentifier
rtid(ROADTYPE_ROAD
, ROADSUBTYPE_NORMAL
); // TODO
1600 DoCommand(tile
, GenRandomRoadBits() | (rtid
.Pack() << 4), t
->index
, DC_EXEC
| DC_AUTO
, CMD_BUILD_ROAD
);
1601 cur_company
.Restore();
1605 tile
= TILE_ADD(tile
, ToTileIndexDiff(*ptr
));
1609 cur_company
.Restore();
1613 void UpdateTownRadius(Town
*t
)
1615 static const uint32 _town_squared_town_zone_radius_data
[23][5] = {
1616 { 4, 0, 0, 0, 0}, // 0
1621 { 64, 0, 4, 0, 0}, // 20
1626 { 81, 0, 16, 0, 4}, // 40
1628 { 81, 36, 25, 0, 9},
1629 { 81, 36, 25, 16, 9},
1630 { 81, 49, 0, 25, 9},
1631 { 81, 64, 0, 25, 9}, // 60
1632 { 81, 64, 0, 36, 9},
1633 { 81, 64, 0, 36, 16},
1634 {100, 81, 0, 49, 16},
1635 {100, 81, 0, 49, 25},
1636 {121, 81, 0, 49, 25}, // 80
1637 {121, 81, 0, 49, 25},
1638 {121, 81, 0, 49, 36}, // 88
1641 if (t
->cache
.num_houses
< 92) {
1642 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
));
1644 int mass
= t
->cache
.num_houses
/ 8;
1645 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1646 * The offsets are to make sure the radii do not decrease in size when going from the table
1647 * to the calculated value.*/
1648 t
->cache
.squared_town_zone_radius
[0] = mass
* 15 - 40;
1649 t
->cache
.squared_town_zone_radius
[1] = mass
* 9 - 15;
1650 t
->cache
.squared_town_zone_radius
[2] = 0;
1651 t
->cache
.squared_town_zone_radius
[3] = mass
* 5 - 5;
1652 t
->cache
.squared_town_zone_radius
[4] = mass
* 3 + 5;
1656 void UpdateTownMaxPass(Town
*t
)
1658 t
->supplied
[CT_PASSENGERS
].old_max
= t
->cache
.population
>> 3;
1659 t
->supplied
[CT_MAIL
].old_max
= t
->cache
.population
>> 4;
1663 * Does the actual town creation.
1666 * @param tile Where to put it
1667 * @param townnameparts The town name
1668 * @param size Parameter for size determination
1669 * @param city whether to build a city or town
1670 * @param layout the (road) layout of the town
1671 * @param manual was the town placed manually?
1673 static void DoCreateTown(Town
*t
, TileIndex tile
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
, bool manual
)
1675 const int32 tile_loops_until_rebuild
= 10;
1676 const int32 ticks_per_tile_loop
= 256;
1679 t
->cache
.num_houses
= 0;
1680 t
->time_until_rebuild
= _date
+ ((tile_loops_until_rebuild
* ticks_per_tile_loop
) / DEFAULT_DAY_TICKS
);
1681 UpdateTownRadius(t
);
1683 t
->cache
.population
= 0;
1684 /* Spread growth across ticks so even if there are many
1685 * similar towns they're unlikely to grow all in one tick */
1686 t
->grow_counter
= t
->index
% TOWN_GROWTH_TICKS
;
1687 t
->growth_rate
= TownTicksToGameTicks(250);
1689 /* Set the default cargo requirement for town growth */
1690 switch (_settings_game
.game_creation
.landscape
) {
1692 if (FindFirstCargoWithTownEffect(TE_FOOD
) != nullptr) t
->goal
[TE_FOOD
] = TOWN_GROWTH_WINTER
;
1696 if (FindFirstCargoWithTownEffect(TE_FOOD
) != nullptr) t
->goal
[TE_FOOD
] = TOWN_GROWTH_DESERT
;
1697 if (FindFirstCargoWithTownEffect(TE_WATER
) != nullptr) t
->goal
[TE_WATER
] = TOWN_GROWTH_DESERT
;
1701 t
->fund_buildings_months
= 0;
1703 for (uint i
= 0; i
!= MAX_COMPANIES
; i
++) t
->ratings
[i
] = RATING_INITIAL
;
1705 t
->have_ratings
= 0;
1706 t
->exclusivity
= INVALID_COMPANY
;
1707 t
->exclusive_counter
= 0;
1710 extern int _nb_orig_names
;
1711 if (_settings_game
.game_creation
.town_name
< _nb_orig_names
) {
1712 /* Original town name */
1713 t
->townnamegrfid
= 0;
1714 t
->townnametype
= SPECSTR_TOWNNAME_START
+ _settings_game
.game_creation
.town_name
;
1716 /* Newgrf town name */
1717 t
->townnamegrfid
= GetGRFTownNameId(_settings_game
.game_creation
.town_name
- _nb_orig_names
);
1718 t
->townnametype
= GetGRFTownNameType(_settings_game
.game_creation
.town_name
- _nb_orig_names
);
1720 t
->townnameparts
= townnameparts
;
1722 t
->UpdateVirtCoord();
1723 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 0);
1725 t
->InitializeLayout(layout
);
1727 t
->larger_town
= city
;
1729 int x
= (int)size
* 16 + 3;
1730 if (size
== TSZ_RANDOM
) x
= (Random() & 0xF) + 8;
1731 /* Don't create huge cities when founding town in-game */
1732 if (city
&& (!manual
|| _game_mode
== GM_EDITOR
)) x
*= _settings_game
.economy
.initial_city_size
;
1734 t
->cache
.num_houses
+= x
;
1735 UpdateTownRadius(t
);
1742 t
->cache
.num_houses
-= x
;
1743 UpdateTownRadius(t
);
1744 UpdateTownMaxPass(t
);
1745 UpdateAirportsNoise();
1749 * Checks if it's possible to place a town at given tile
1750 * @param tile tile to check
1751 * @return error value or zero cost
1753 static CommandCost
TownCanBePlacedHere(TileIndex tile
)
1755 /* Check if too close to the edge of map */
1756 if (DistanceFromEdge(tile
) < 12) {
1757 return CommandError(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
);
1760 /* Check distance to all other towns. */
1761 if (IsCloseToTown(tile
, _settings_game
.economy
.town_min_distance
)) {
1762 return CommandError(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN
);
1765 /* Check max height level. */
1766 if (GetTileZ(tile
) > _settings_game
.economy
.max_town_heightlevel
) {
1767 return CommandError(STR_ERROR_SITE_UNSUITABLE
);
1770 /* Cannot build above the tree line. */
1771 if (_settings_game
.construction
.trees_around_snow_line_enabled
&& (GetTileZ(tile
) >= HighestSnowLine() + (_settings_game
.construction
.trees_around_snow_line_range
/ 2))) {
1772 return CommandError(STR_ERROR_SITE_UNSUITABLE
);
1775 /* Can only build on clear flat areas, possibly with trees. */
1776 if ((!IsTileType(tile
, MP_CLEAR
) && !IsTileType(tile
, MP_TREES
)) || !IsTileFlat(tile
)) {
1777 return CommandError(STR_ERROR_SITE_UNSUITABLE
);
1780 return CommandCost(EXPENSES_OTHER
);
1784 * Verifies this custom name is unique. Only custom names are checked.
1785 * @param name name to check
1786 * @return is this name unique?
1788 static bool IsUniqueTownName(const char *name
)
1793 if (t
->name
!= nullptr && strcmp(t
->name
, name
) == 0) return false;
1800 * Create a new town.
1801 * @param tile coordinates where town is built
1802 * @param flags type of operation
1803 * @param p1 0..1 size of the town (@see TownSize)
1804 * 2 true iff it should be a city
1805 * 3..5 town road layout (@see TownLayout)
1806 * 6 use random location (randomize \c tile )
1807 * @param p2 town name parts
1808 * @param text Custom name for the town. If empty, the town name parts will be used.
1809 * @return the cost of this operation or an error
1811 CommandCost
CmdFoundTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1813 TownSize size
= Extract
<TownSize
, 0, 2>(p1
);
1814 bool city
= HasBit(p1
, 2);
1815 TownLayout layout
= Extract
<TownLayout
, 3, 3>(p1
);
1816 TownNameParams
par(_settings_game
.game_creation
.town_name
);
1817 bool random
= HasBit(p1
, 6);
1818 uint32 townnameparts
= p2
;
1820 if (size
>= TSZ_END
) return CommandError();
1821 if (layout
>= NUM_TLS
) return CommandError();
1823 /* Some things are allowed only in the scenario editor and for game scripts. */
1824 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) {
1825 if (_settings_game
.economy
.found_town
== TF_FORBIDDEN
) return CommandError();
1826 if (size
== TSZ_LARGE
) return CommandError();
1827 if (random
) return CommandError();
1828 if (_settings_game
.economy
.found_town
!= TF_CUSTOM_LAYOUT
&& layout
!= _settings_game
.economy
.town_layout
) {
1829 return CommandError();
1831 } else if (_current_company
== OWNER_DEITY
&& random
) {
1832 /* Random parameter is not allowed for Game Scripts. */
1833 return CommandError();
1836 if (StrEmpty(text
)) {
1837 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1838 if (!VerifyTownName(townnameparts
, &par
)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1840 /* If name is not empty, it has to be unique custom name */
1841 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return CommandError();
1842 if (!IsUniqueTownName(text
)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1845 /* Allocate town struct */
1846 if (!Town::CanAllocateItem()) return CommandError(STR_ERROR_TOO_MANY_TOWNS
);
1849 CommandCost ret
= TownCanBePlacedHere(tile
);
1850 if (ret
.Failed()) return ret
;
1853 static const byte price_mult
[][TSZ_RANDOM
+ 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1854 /* multidimensional arrays have to have defined length of non-first dimension */
1855 assert_compile(lengthof(price_mult
[0]) == 4);
1857 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_BUILD_TOWN
]);
1858 byte mult
= price_mult
[city
][size
];
1860 cost
.MultiplyCost(mult
);
1862 /* Create the town */
1863 if (flags
& DC_EXEC
) {
1864 if (cost
.GetCost() > GetAvailableMoneyForCommand()) {
1865 _additional_cash_required
= cost
.GetCost();
1866 return CommandCost(EXPENSES_OTHER
);
1869 Backup
<bool> old_generating_world(_generating_world
, true, FILE_LINE
);
1870 UpdateNearestTownForRoadTiles(true);
1873 t
= CreateRandomTown(20, townnameparts
, size
, city
, layout
);
1875 cost
= CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN
);
1877 _new_town_id
= t
->index
;
1881 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, true);
1883 UpdateNearestTownForRoadTiles(false);
1884 old_generating_world
.Restore();
1886 if (t
!= nullptr && !StrEmpty(text
)) {
1887 t
->name
= stredup(text
);
1888 t
->UpdateVirtCoord();
1891 if (_game_mode
!= GM_EDITOR
) {
1892 /* 't' can't be nullptr since 'random' is false outside scenedit */
1894 char company_name
[MAX_LENGTH_COMPANY_NAME_CHARS
* MAX_CHAR_LENGTH
];
1895 SetDParam(0, _current_company
);
1896 GetString(company_name
, STR_COMPANY_NAME
, lastof(company_name
));
1898 char *cn
= stredup(company_name
);
1899 SetDParamStr(0, cn
);
1900 SetDParam(1, t
->index
);
1902 AddTileNewsItem(STR_NEWS_NEW_TOWN
, NT_INDUSTRY_OPEN
, tile
, cn
);
1903 AI::BroadcastNewEvent(new ScriptEventTownFounded(t
->index
));
1904 Game::NewEvent(new ScriptEventTownFounded(t
->index
));
1911 * Towns must all be placed on the same grid or when they eventually
1912 * interpenetrate their road networks will not mesh nicely; this
1913 * function adjusts a tile so that it aligns properly.
1915 * @param tile the tile to start at
1916 * @param layout which town layout algo is in effect
1917 * @return the adjusted tile
1919 static TileIndex
AlignTileToGrid(TileIndex tile
, TownLayout layout
)
1922 case TL_2X2_GRID
: return TileXY(TileX(tile
) - TileX(tile
) % 3, TileY(tile
) - TileY(tile
) % 3);
1923 case TL_3X3_GRID
: return TileXY(TileX(tile
) & ~3, TileY(tile
) & ~3);
1924 default: return tile
;
1929 * Towns must all be placed on the same grid or when they eventually
1930 * interpenetrate their road networks will not mesh nicely; this
1931 * function tells you if a tile is properly aligned.
1933 * @param tile the tile to start at
1934 * @param layout which town layout algo is in effect
1935 * @return true if the tile is in the correct location
1937 static bool IsTileAlignedToGrid(TileIndex tile
, TownLayout layout
)
1940 case TL_2X2_GRID
: return TileX(tile
) % 3 == 0 && TileY(tile
) % 3 == 0;
1941 case TL_3X3_GRID
: return TileX(tile
) % 4 == 0 && TileY(tile
) % 4 == 0;
1942 default: return true;
1947 * Used as the user_data for FindFurthestFromWater
1950 TileIndex tile
; ///< holds the tile that was found
1951 uint max_dist
; ///< holds the distance that tile is from the water
1952 TownLayout layout
; ///< tells us what kind of town we're building
1956 * CircularTileSearch callback; finds the tile furthest from any
1957 * water. slightly bit tricky, since it has to do a search of its own
1958 * in order to find the distance to the water from each square in the
1961 * Also, this never returns true, because it needs to take into
1962 * account all locations being searched before it knows which is the
1965 * @param tile Start looking from this tile
1966 * @param user_data Storage area for data that must last across calls;
1967 * must be a pointer to struct SpotData
1969 * @return always false
1971 static bool FindFurthestFromWater(TileIndex tile
, void *user_data
)
1973 SpotData
*sp
= (SpotData
*)user_data
;
1974 uint dist
= GetClosestWaterDistance(tile
, true);
1976 if (IsTileType(tile
, MP_CLEAR
) &&
1978 IsTileAlignedToGrid(tile
, sp
->layout
) &&
1979 dist
> sp
->max_dist
) {
1981 sp
->max_dist
= dist
;
1988 * CircularTileSearch callback; finds the nearest land tile
1990 * @param tile Start looking from this tile
1991 * @param user_data not used
1993 static bool FindNearestEmptyLand(TileIndex tile
, void *user_data
)
1995 return IsTileType(tile
, MP_CLEAR
);
1999 * Given a spot on the map (presumed to be a water tile), find a good
2000 * coastal spot to build a city. We don't want to build too close to
2001 * the edge if we can help it (since that retards city growth) hence
2002 * the search within a search within a search. O(n*m^2), where n is
2003 * how far to search for land, and m is how far inland to look for a
2006 * @param tile Start looking from this spot.
2007 * @param layout the road layout to search for
2008 * @return tile that was found
2010 static TileIndex
FindNearestGoodCoastalTownSpot(TileIndex tile
, TownLayout layout
)
2012 SpotData sp
= { INVALID_TILE
, 0, layout
};
2014 TileIndex coast
= tile
;
2015 if (CircularTileSearch(&coast
, 40, FindNearestEmptyLand
, nullptr)) {
2016 CircularTileSearch(&coast
, 10, FindFurthestFromWater
, &sp
);
2020 /* if we get here just give up */
2021 return INVALID_TILE
;
2024 static Town
*CreateRandomTown(uint attempts
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
)
2026 assert(_game_mode
== GM_EDITOR
|| _generating_world
); // These are the preconditions for CMD_DELETE_TOWN
2028 if (!Town::CanAllocateItem()) return nullptr;
2031 /* Generate a tile index not too close from the edge */
2032 TileIndex tile
= AlignTileToGrid(RandomTile(), layout
);
2034 /* if we tried to place the town on water, slide it over onto
2035 * the nearest likely-looking spot */
2036 if (IsTileType(tile
, MP_WATER
)) {
2037 tile
= FindNearestGoodCoastalTownSpot(tile
, layout
);
2038 if (tile
== INVALID_TILE
) continue;
2041 /* Make sure town can be placed here */
2042 if (TownCanBePlacedHere(tile
).Failed()) continue;
2044 /* Allocate a town struct */
2045 Town
*t
= new Town(tile
);
2047 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, false);
2049 /* if the population is still 0 at the point, then the
2050 * placement is so bad it couldn't grow at all */
2051 if (t
->cache
.population
> 0) return t
;
2053 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
2054 CommandCost rc
= DoCommand(t
->xy
, t
->index
, 0, DC_EXEC
, CMD_DELETE_TOWN
);
2055 cur_company
.Restore();
2056 assert(rc
.Succeeded());
2058 /* We already know that we can allocate a single town when
2059 * entering this function. However, we create and delete
2060 * a town which "resets" the allocation checks. As such we
2061 * need to check again when assertions are enabled. */
2062 assert(Town::CanAllocateItem());
2063 } while (--attempts
!= 0);
2068 static const byte _num_initial_towns
[4] = {5, 11, 23, 46}; // very low, low, normal, high
2071 * This function will generate a certain amount of towns, with a certain layout
2072 * It can be called from the scenario editor (i.e.: generate Random Towns)
2073 * as well as from world creation.
2074 * @param layout which towns will be set to, when created
2075 * @return true if towns have been successfully created
2077 bool GenerateTowns(TownLayout layout
)
2079 uint current_number
= 0;
2080 uint difficulty
= (_game_mode
!= GM_EDITOR
) ? _settings_game
.difficulty
.number_towns
: 0;
2081 uint total
= (difficulty
== (uint
)CUSTOM_TOWN_NUMBER_DIFFICULTY
) ? _settings_game
.game_creation
.custom_town_number
: ScaleByMapSize(_num_initial_towns
[difficulty
] + (Random() & 7));
2082 total
= min(TownPool::MAX_SIZE
, total
);
2083 uint32 townnameparts
;
2084 TownNames town_names
;
2086 SetGeneratingWorldProgress(GWP_TOWN
, total
);
2088 /* First attempt will be made at creating the suggested number of towns.
2089 * Note that this is really a suggested value, not a required one.
2090 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2092 bool city
= (_settings_game
.economy
.larger_towns
!= 0 && Chance16(1, _settings_game
.economy
.larger_towns
));
2093 IncreaseGeneratingWorldProgress(GWP_TOWN
);
2094 /* Get a unique name for the town. */
2095 if (!GenerateTownName(&townnameparts
, &town_names
)) continue;
2096 /* try 20 times to create a random-sized town for the first loop. */
2097 if (CreateRandomTown(20, townnameparts
, TSZ_RANDOM
, city
, layout
) != nullptr) current_number
++; // If creation was successful, raise a flag.
2102 if (current_number
!= 0) return true;
2104 /* If current_number is still zero at this point, it means that not a single town has been created.
2105 * So give it a last try, but now more aggressive */
2106 if (GenerateTownName(&townnameparts
) &&
2107 CreateRandomTown(10000, townnameparts
, TSZ_RANDOM
, _settings_game
.economy
.larger_towns
!= 0, layout
) != nullptr) {
2111 /* If there are no towns at all and we are generating new game, bail out */
2112 if (Town::GetNumItems() == 0 && _game_mode
!= GM_EDITOR
) {
2113 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN
, INVALID_STRING_ID
, WL_CRITICAL
);
2116 return false; // we are still without a town? we failed, simply
2121 * Returns the bit corresponding to the town zone of the specified tile
2122 * @param t Town on which town zone is to be found
2123 * @param tile TileIndex where town zone needs to be found
2124 * @return the bit position of the given zone, as defined in HouseZones
2126 HouseZonesBits
GetTownRadiusGroup(const Town
*t
, TileIndex tile
)
2128 uint dist
= DistanceSquare(tile
, t
->xy
);
2130 if (t
->fund_buildings_months
&& dist
<= 25) return HZB_TOWN_CENTRE
;
2132 HouseZonesBits smallest
= HZB_TOWN_EDGE
;
2133 for (HouseZonesBits i
= HZB_BEGIN
; i
< HZB_END
; i
++) {
2134 if (dist
< t
->cache
.squared_town_zone_radius
[i
]) smallest
= i
;
2141 * Clears tile and builds a house or house part.
2142 * @param tile tile index
2143 * @param t The town to clear the house for
2144 * @param counter of construction step
2145 * @param stage of construction (used for drawing)
2146 * @param type of house. Index into house specs array
2147 * @param random_bits required for newgrf houses
2148 * @pre house can be built here
2150 static inline void ClearMakeHouseTile(TileIndex tile
, Town
*t
, byte counter
, byte stage
, HouseID type
, byte random_bits
)
2152 CommandCost cc
= DoCommand(tile
, 0, 0, DC_EXEC
| DC_AUTO
| DC_NO_WATER
, CMD_LANDSCAPE_CLEAR
);
2154 assert(cc
.Succeeded());
2156 IncreaseBuildingCount(t
, type
);
2157 MakeHouseTile(tile
, t
->index
, counter
, stage
, type
, random_bits
);
2158 if (HouseSpec::Get(type
)->building_flags
& BUILDING_IS_ANIMATED
) AddAnimatedTile(tile
);
2160 MarkTileDirtyByTile(tile
);
2165 * Write house information into the map. For houses > 1 tile, all tiles are marked.
2166 * @param t tile index
2167 * @param town The town related to this house
2168 * @param counter of construction step
2169 * @param stage of construction (used for drawing)
2170 * @param type of house. Index into house specs array
2171 * @param random_bits required for newgrf houses
2172 * @pre house can be built here
2174 static void MakeTownHouse(TileIndex t
, Town
*town
, byte counter
, byte stage
, HouseID type
, byte random_bits
)
2176 BuildingFlags size
= HouseSpec::Get(type
)->building_flags
;
2178 ClearMakeHouseTile(t
, town
, counter
, stage
, type
, random_bits
);
2179 if (size
& BUILDING_2_TILES_Y
) ClearMakeHouseTile(t
+ TileDiffXY(0, 1), town
, counter
, stage
, ++type
, random_bits
);
2180 if (size
& BUILDING_2_TILES_X
) ClearMakeHouseTile(t
+ TileDiffXY(1, 0), town
, counter
, stage
, ++type
, random_bits
);
2181 if (size
& BUILDING_HAS_4_TILES
) ClearMakeHouseTile(t
+ TileDiffXY(1, 1), town
, counter
, stage
, ++type
, random_bits
);
2186 * Checks if a house can be built here. Important is slope, bridge above
2187 * and ability to clear the land.
2188 * @param tile tile to check
2189 * @param noslope are slopes (foundations) allowed?
2190 * @return true iff house can be built here
2192 static inline bool CanBuildHouseHere(TileIndex tile
, bool noslope
)
2194 /* cannot build on these slopes... */
2195 Slope slope
= GetTileSlope(tile
);
2196 if ((noslope
&& slope
!= SLOPE_FLAT
) || IsSteepSlope(slope
)) return false;
2198 /* at least one RoadTypes allow building the house here? */
2199 if (!RoadTypesAllowHouseHere(tile
)) return false;
2201 /* building under a bridge? */
2202 if (IsBridgeAbove(tile
)) return false;
2204 /* can we clear the land? */
2205 return DoCommand(tile
, 0, 0, DC_AUTO
| DC_NO_WATER
, CMD_LANDSCAPE_CLEAR
).Succeeded();
2210 * Checks if a house can be built at this tile, must have the same max z as parameter.
2211 * @param tile tile to check
2212 * @param z max z of this tile so more parts of a house are at the same height (with foundation)
2213 * @param noslope are slopes (foundations) allowed?
2214 * @return true iff house can be built here
2215 * @see CanBuildHouseHere()
2217 static inline bool CheckBuildHouseSameZ(TileIndex tile
, int z
, bool noslope
)
2219 if (!CanBuildHouseHere(tile
, noslope
)) return false;
2221 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2222 if (GetTileMaxZ(tile
) != z
) return false;
2229 * Checks if a house of size 2x2 can be built at this tile
2230 * @param tile tile, N corner
2231 * @param z maximum tile z so all tile have the same max z
2232 * @param noslope are slopes (foundations) allowed?
2233 * @return true iff house can be built
2234 * @see CheckBuildHouseSameZ()
2236 static bool CheckFree2x2Area(TileIndex tile
, int z
, bool noslope
)
2238 /* we need to check this tile too because we can be at different tile now */
2239 if (!CheckBuildHouseSameZ(tile
, z
, noslope
)) return false;
2241 for (DiagDirection d
= DIAGDIR_SE
; d
< DIAGDIR_END
; d
++) {
2242 tile
+= TileOffsByDiagDir(d
);
2243 if (!CheckBuildHouseSameZ(tile
, z
, noslope
)) return false;
2251 * Checks if current town layout allows building here
2253 * @param tile tile to check
2254 * @return true iff town layout allows building here
2257 static inline bool TownLayoutAllowsHouseHere(Town
*t
, TileIndex tile
)
2259 /* Allow towns everywhere when we don't build roads */
2260 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return true;
2262 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
2264 switch (t
->layout
) {
2266 if ((grid_pos
.x
% 3) == 0 || (grid_pos
.y
% 3) == 0) return false;
2270 if ((grid_pos
.x
% 4) == 0 || (grid_pos
.y
% 4) == 0) return false;
2282 * Checks if current town layout allows 2x2 building here
2284 * @param tile tile to check
2285 * @return true iff town layout allows 2x2 building here
2288 static inline bool TownLayoutAllows2x2HouseHere(Town
*t
, TileIndex tile
)
2290 /* Allow towns everywhere when we don't build roads */
2291 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return true;
2293 /* Compute relative position of tile. (Positive offsets are towards north) */
2294 TileIndexDiffC grid_pos
= TileIndexToTileIndexDiffC(t
->xy
, tile
);
2296 switch (t
->layout
) {
2300 if ((grid_pos
.x
!= 2 && grid_pos
.x
!= -1) ||
2301 (grid_pos
.y
!= 2 && grid_pos
.y
!= -1)) return false;
2305 if ((grid_pos
.x
& 3) < 2 || (grid_pos
.y
& 3) < 2) return false;
2317 * Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout
2318 * Also, tests both building positions that occupy this tile
2319 * @param tile tile where the building should be built
2321 * @param maxz all tiles should have the same height
2322 * @param noslope are slopes forbidden?
2323 * @param second diagdir from first tile to second tile
2325 static bool CheckTownBuild2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
, DiagDirection second
)
2327 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2329 TileIndex tile2
= *tile
+ TileOffsByDiagDir(second
);
2330 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, maxz
, noslope
)) return true;
2332 tile2
= *tile
+ TileOffsByDiagDir(ReverseDiagDir(second
));
2333 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, maxz
, noslope
)) {
2343 * Checks if 2x2 building is allowed here, also takes into account current town layout
2344 * Also, tests all four building positions that occupy this tile
2345 * @param tile tile where the building should be built
2347 * @param maxz all tiles should have the same height
2348 * @param noslope are slopes forbidden?
2350 static bool CheckTownBuild2x2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
)
2352 TileIndex tile2
= *tile
;
2354 for (DiagDirection d
= DIAGDIR_SE
;; d
++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2355 if (TownLayoutAllows2x2HouseHere(t
, tile2
) && CheckFree2x2Area(tile2
, maxz
, noslope
)) {
2359 if (d
== DIAGDIR_END
) break;
2360 tile2
+= TileOffsByDiagDir(ReverseDiagDir(d
)); // go clockwise
2368 * Tries to build a house at this tile
2369 * @param t town the house will belong to
2370 * @param tile where the house will be built
2371 * @return false iff no house can be built at this tile
2373 static bool BuildTownHouse(Town
*t
, TileIndex tile
)
2375 /* forbidden building here by town layout */
2376 if (!TownLayoutAllowsHouseHere(t
, tile
)) return false;
2378 /* no house allowed at all, bail out */
2379 if (!CanBuildHouseHere(tile
, false)) return false;
2381 Slope slope
= GetTileSlope(tile
);
2382 int maxz
= GetTileMaxZ(tile
);
2384 /* Get the town zone type of the current tile, as well as the climate.
2385 * This will allow to easily compare with the specs of the new house to build */
2386 HouseZonesBits rad
= GetTownRadiusGroup(t
, tile
);
2389 int land
= _settings_game
.game_creation
.landscape
;
2390 if (land
== LT_ARCTIC
&& maxz
> HighestSnowLine()) land
= -1;
2392 uint bitmask
= (1 << rad
) + (1 << (land
+ 12));
2394 /* bits 0-4 are used
2395 * bits 11-15 are used
2396 * bits 5-10 are not used. */
2397 HouseID houses
[NUM_HOUSES
];
2399 uint probs
[NUM_HOUSES
];
2400 uint probability_max
= 0;
2402 /* Generate a list of all possible houses that can be built. */
2403 for (uint i
= 0; i
< NUM_HOUSES
; i
++) {
2404 const HouseSpec
*hs
= HouseSpec::Get(i
);
2406 /* Verify that the candidate house spec matches the current tile status */
2407 if ((~hs
->building_availability
& bitmask
) != 0 || !hs
->enabled
|| hs
->grf_prop
.override
!= INVALID_HOUSE_ID
) continue;
2409 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2410 if (hs
->class_id
!= HOUSE_NO_CLASS
) {
2411 /* id_count is always <= class_count, so it doesn't need to be checked */
2412 if (t
->cache
.building_counts
.class_count
[hs
->class_id
] == UINT16_MAX
) continue;
2414 /* If the house has no class, check id_count instead */
2415 if (t
->cache
.building_counts
.id_count
[i
] == UINT16_MAX
) continue;
2418 /* Without NewHouses, all houses have probability '1' */
2419 uint cur_prob
= (_loaded_newgrf_features
.has_newhouses
? hs
->probability
: 1);
2420 probability_max
+= cur_prob
;
2421 probs
[num
] = cur_prob
;
2422 houses
[num
++] = (HouseID
)i
;
2425 TileIndex baseTile
= tile
;
2427 while (probability_max
> 0) {
2428 /* Building a multitile building can change the location of tile.
2429 * The building would still be built partially on that tile, but
2430 * its northern tile would be elsewhere. However, if the callback
2431 * fails we would be basing further work from the changed tile.
2432 * So a next 1x1 tile building could be built on the wrong tile. */
2435 uint r
= RandomRange(probability_max
);
2437 for (i
= 0; i
< num
; i
++) {
2438 if (probs
[i
] > r
) break;
2442 HouseID house
= houses
[i
];
2443 probability_max
-= probs
[i
];
2445 /* remove tested house from the set */
2447 houses
[i
] = houses
[num
];
2448 probs
[i
] = probs
[num
];
2450 const HouseSpec
*hs
= HouseSpec::Get(house
);
2452 if (_loaded_newgrf_features
.has_newhouses
&& !_generating_world
&&
2453 _game_mode
!= GM_EDITOR
&& (hs
->extra_flags
& BUILDING_IS_HISTORICAL
) != 0) {
2457 if (_cur_year
< hs
->min_year
|| _cur_year
> hs
->max_year
) continue;
2459 /* Special houses that there can be only one of. */
2462 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2463 SetBit(oneof
, TOWN_HAS_CHURCH
);
2464 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2465 SetBit(oneof
, TOWN_HAS_STADIUM
);
2468 if (t
->flags
& oneof
) continue;
2470 /* Make sure there is no slope? */
2471 bool noslope
= (hs
->building_flags
& TILE_NOT_SLOPED
) != 0;
2472 if (noslope
&& slope
!= SLOPE_FLAT
) continue;
2474 if (hs
->building_flags
& TILE_SIZE_2x2
) {
2475 if (!CheckTownBuild2x2House(&tile
, t
, maxz
, noslope
)) continue;
2476 } else if (hs
->building_flags
& TILE_SIZE_2x1
) {
2477 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SW
)) continue;
2478 } else if (hs
->building_flags
& TILE_SIZE_1x2
) {
2479 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SE
)) continue;
2481 /* 1x1 house checks are already done */
2484 byte random_bits
= Random();
2486 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ALLOW_CONSTRUCTION
)) {
2487 uint16 callback_res
= GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION
, 0, 0, house
, t
, tile
, true, random_bits
);
2488 if (callback_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_ALLOW_CONSTRUCTION
, callback_res
)) continue;
2491 /* build the house */
2492 t
->cache
.num_houses
++;
2494 /* Special houses that there can be only one of. */
2497 byte construction_counter
= 0;
2498 byte construction_stage
= 0;
2500 if (_generating_world
|| _game_mode
== GM_EDITOR
) {
2501 uint32 r
= Random();
2503 construction_stage
= TOWN_HOUSE_COMPLETED
;
2504 if (Chance16(1, 7)) construction_stage
= GB(r
, 0, 2);
2506 if (construction_stage
== TOWN_HOUSE_COMPLETED
) {
2507 ChangePopulation(t
, hs
->population
);
2509 construction_counter
= GB(r
, 2, 2);
2513 MakeTownHouse(tile
, t
, construction_counter
, construction_stage
, house
, random_bits
);
2514 UpdateTownRadius(t
);
2515 UpdateTownCargoes(t
, tile
);
2524 * Update data structures when a house is removed
2525 * @param tile Tile of the house
2526 * @param t Town owning the house
2527 * @param house House type
2529 static void DoClearTownHouseHelper(TileIndex tile
, Town
*t
, HouseID house
)
2531 assert(IsTileType(tile
, MP_HOUSE
));
2532 DecreaseBuildingCount(t
, house
);
2533 DoClearSquare(tile
);
2534 DeleteAnimatedTile(tile
);
2536 DeleteNewGRFInspectWindow(GSF_HOUSES
, tile
);
2540 * Determines if a given HouseID is part of a multitile house.
2541 * The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
2543 * @param house Is changed to the HouseID of the north tile of the same house
2544 * @return TileDiff from the tile of the given HouseID to the north tile
2546 TileIndexDiff
GetHouseNorthPart(HouseID
&house
)
2548 if (house
>= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2549 if (HouseSpec::Get(house
- 1)->building_flags
& TILE_SIZE_2x1
) {
2551 return TileDiffXY(-1, 0);
2552 } else if (HouseSpec::Get(house
- 1)->building_flags
& BUILDING_2_TILES_Y
) {
2554 return TileDiffXY(0, -1);
2555 } else if (HouseSpec::Get(house
- 2)->building_flags
& BUILDING_HAS_4_TILES
) {
2557 return TileDiffXY(-1, 0);
2558 } else if (HouseSpec::Get(house
- 3)->building_flags
& BUILDING_HAS_4_TILES
) {
2560 return TileDiffXY(-1, -1);
2566 void ClearTownHouse(Town
*t
, TileIndex tile
)
2568 assert(IsTileType(tile
, MP_HOUSE
));
2570 HouseID house
= GetHouseType(tile
);
2572 /* need to align the tile to point to the upper left corner of the house */
2573 tile
+= GetHouseNorthPart(house
); // modifies house to the ID of the north tile
2575 const HouseSpec
*hs
= HouseSpec::Get(house
);
2577 /* Remove population from the town if the house is finished. */
2578 if (IsHouseCompleted(tile
)) {
2579 ChangePopulation(t
, -hs
->population
);
2582 t
->cache
.num_houses
--;
2584 /* Clear flags for houses that only may exist once/town. */
2585 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2586 ClrBit(t
->flags
, TOWN_HAS_CHURCH
);
2587 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2588 ClrBit(t
->flags
, TOWN_HAS_STADIUM
);
2591 /* Do the actual clearing of tiles */
2592 uint eflags
= hs
->building_flags
;
2593 DoClearTownHouseHelper(tile
, t
, house
);
2594 if (eflags
& BUILDING_2_TILES_Y
) DoClearTownHouseHelper(tile
+ TileDiffXY(0, 1), t
, ++house
);
2595 if (eflags
& BUILDING_2_TILES_X
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 0), t
, ++house
);
2596 if (eflags
& BUILDING_HAS_4_TILES
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 1), t
, ++house
);
2598 UpdateTownRadius(t
);
2600 /* Update cargo acceptance. */
2601 UpdateTownCargoes(t
, tile
);
2605 * Rename a town (server-only).
2606 * @param tile unused
2607 * @param flags type of operation
2608 * @param p1 town ID to rename
2610 * @param text the new name or an empty string when resetting to the default
2611 * @return the cost of this operation or an error
2613 CommandCost
CmdRenameTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2615 Town
*t
= Town::GetIfValid(p1
);
2616 if (t
== nullptr) return CommandError();
2618 bool reset
= StrEmpty(text
);
2621 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return CommandError();
2622 if (!IsUniqueTownName(text
)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE
);
2625 if (flags
& DC_EXEC
) {
2627 t
->name
= reset
? nullptr : stredup(text
);
2629 t
->UpdateVirtCoord();
2630 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 1);
2631 UpdateAllStationVirtCoords();
2633 return CommandCost();
2637 * Determines the first cargo with a certain town effect
2638 * @param effect Town effect of interest
2639 * @return first active cargo slot with that effect
2641 const CargoSpec
*FindFirstCargoWithTownEffect(TownEffect effect
)
2643 const CargoSpec
*cs
;
2644 FOR_ALL_CARGOSPECS(cs
) {
2645 if (cs
->town_effect
== effect
) return cs
;
2650 static void UpdateTownGrowRate(Town
*t
);
2653 * Change the cargo goal of a town.
2654 * @param tile Unused.
2655 * @param flags Type of operation.
2656 * @param p1 various bitstuffed elements
2657 * - p1 = (bit 0 - 15) - Town ID to cargo game of.
2658 * - p1 = (bit 16 - 23) - TownEffect to change the game of.
2659 * @param p2 The new goal value.
2660 * @param text Unused.
2661 * @return Empty cost or an error.
2663 CommandCost
CmdTownCargoGoal(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2665 if (_current_company
!= OWNER_DEITY
) return CommandError();
2667 TownEffect te
= (TownEffect
)GB(p1
, 16, 8);
2668 if (te
< TE_BEGIN
|| te
>= TE_END
) return CommandError();
2670 uint16 index
= GB(p1
, 0, 16);
2671 Town
*t
= Town::GetIfValid(index
);
2672 if (t
== nullptr) return CommandError();
2674 /* Validate if there is a cargo which is the requested TownEffect */
2675 const CargoSpec
*cargo
= FindFirstCargoWithTownEffect(te
);
2676 if (cargo
== nullptr) return CommandError();
2678 if (flags
& DC_EXEC
) {
2680 UpdateTownGrowRate(t
);
2681 InvalidateWindowData(WC_TOWN_VIEW
, index
);
2684 return CommandCost();
2688 * Set a custom text in the Town window.
2689 * @param tile Unused.
2690 * @param flags Type of operation.
2691 * @param p1 Town ID to change the text of.
2693 * @param text The new text (empty to remove the text).
2694 * @return Empty cost or an error.
2696 CommandCost
CmdTownSetText(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2698 if (_current_company
!= OWNER_DEITY
) return CommandError();
2699 Town
*t
= Town::GetIfValid(p1
);
2700 if (t
== nullptr) return CommandError();
2702 if (flags
& DC_EXEC
) {
2704 t
->text
= StrEmpty(text
) ? nullptr : stredup(text
);
2705 InvalidateWindowData(WC_TOWN_VIEW
, p1
);
2708 return CommandCost();
2712 * Change the growth rate of the town.
2713 * @param tile Unused.
2714 * @param flags Type of operation.
2715 * @param p1 Town ID to cargo game of.
2716 * @param p2 Amount of days between growth, or TOWN_GROWTH_RATE_NONE, or 0 to reset custom growth rate.
2717 * @param text Unused.
2718 * @return Empty cost or an error.
2720 CommandCost
CmdTownGrowthRate(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2722 if (_current_company
!= OWNER_DEITY
) return CommandError();
2724 Town
*t
= Town::GetIfValid(p1
);
2725 if (t
== nullptr) return CommandError();
2727 if (flags
& DC_EXEC
) {
2729 /* Just clear the flag, UpdateTownGrowRate will determine a proper growth rate */
2730 ClrBit(t
->flags
, TOWN_CUSTOM_GROWTH
);
2732 const Ticks old_rate
= t
->growth_rate
;
2734 if (t
->grow_counter
>= old_rate
) {
2735 /* This also catches old_rate == 0 */
2736 t
->grow_counter
= p2
;
2738 /* Scale grow_counter, so half finished houses stay half finished */
2739 t
->grow_counter
= t
->grow_counter
* p2
/ old_rate
;
2741 t
->growth_rate
= p2
;
2742 SetBit(t
->flags
, TOWN_CUSTOM_GROWTH
);
2744 UpdateTownGrowRate(t
);
2745 InvalidateWindowData(WC_TOWN_VIEW
, p1
);
2748 return CommandCost();
2752 * Expand a town (scenario editor only).
2753 * @param tile Unused.
2754 * @param flags Type of operation.
2755 * @param p1 Town ID to expand.
2756 * @param p2 Amount to grow, or 0 to grow a random size up to the current amount of houses.
2757 * @param text Unused.
2758 * @return Empty cost or an error.
2760 CommandCost
CmdExpandTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2762 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) return CommandError();
2763 Town
*t
= Town::GetIfValid(p1
);
2764 if (t
== nullptr) return CommandError();
2766 if (flags
& DC_EXEC
) {
2767 /* The more houses, the faster we grow */
2769 uint amount
= RandomRange(ClampToU16(t
->cache
.num_houses
/ 10)) + 3;
2770 t
->cache
.num_houses
+= amount
;
2771 UpdateTownRadius(t
);
2773 uint n
= amount
* 10;
2774 do GrowTown(t
); while (--n
);
2776 t
->cache
.num_houses
-= amount
;
2778 for (; p2
> 0; p2
--) {
2779 /* Try several times to grow, as we are really suppose to grow */
2780 for (uint i
= 0; i
< 25; i
++) if (GrowTown(t
)) break;
2783 UpdateTownRadius(t
);
2785 UpdateTownMaxPass(t
);
2788 return CommandCost();
2792 * Delete a town (scenario editor or worldgen only).
2793 * @param tile Unused.
2794 * @param flags Type of operation.
2795 * @param p1 Town ID to delete.
2797 * @param text Unused.
2798 * @return Empty cost or an error.
2800 CommandCost
CmdDeleteTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2802 if (_game_mode
!= GM_EDITOR
&& !_generating_world
) return CommandError();
2803 Town
*t
= Town::GetIfValid(p1
);
2804 if (t
== nullptr) return CommandError();
2806 /* Stations refer to towns. */
2808 FOR_ALL_STATIONS(st
) {
2809 if (st
->town
== t
) {
2810 /* Non-oil rig stations are always a problem. */
2811 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->airport
.type
!= AT_OILRIG
) return CommandError();
2812 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2813 CommandCost ret
= DoCommand(st
->airport
.tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2814 if (ret
.Failed()) return ret
;
2818 /* Depots refer to towns. */
2821 if (d
->town
== t
) return CommandError();
2824 /* Check all tiles for town ownership. */
2825 for (TileIndex tile
= 0; tile
< MapSize(); ++tile
) {
2826 bool try_clear
= false;
2827 switch (GetTileType(tile
)) {
2829 try_clear
= HasTownOwnedRoad(tile
) && GetTownIndex(tile
) == t
->index
;
2832 case MP_TUNNELBRIDGE
:
2833 try_clear
= IsTileOwner(tile
, OWNER_TOWN
) && ClosestTownFromTile(tile
, UINT_MAX
) == t
;
2837 try_clear
= GetTownIndex(tile
) == t
->index
;
2841 try_clear
= Industry::GetByTile(tile
)->town
== t
;
2845 if (Town::GetNumItems() == 1) {
2846 /* No towns will be left, remove it! */
2849 Object
*o
= Object::GetByTile(tile
);
2851 if (o
->type
== OBJECT_STATUE
) {
2852 /* Statue... always remove. */
2855 /* Tell to find a new town. */
2856 if (flags
& DC_EXEC
) o
->town
= nullptr;
2866 CommandCost ret
= DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2867 if (ret
.Failed()) return ret
;
2871 /* The town destructor will delete the other things related to the town. */
2872 if (flags
& DC_EXEC
) delete t
;
2874 return CommandCost();
2878 * Factor in the cost of each town action.
2881 const byte _town_action_costs
[TACT_COUNT
] = {
2882 2, 4, 9, 35, 48, 53, 117, 175
2885 static CommandCost
TownActionAdvertiseSmall(Town
*t
, DoCommandFlag flags
)
2887 if (flags
& DC_EXEC
) {
2888 ModifyStationRatingAround(t
->xy
, _current_company
, 0x40, 10);
2890 return CommandCost();
2893 static CommandCost
TownActionAdvertiseMedium(Town
*t
, DoCommandFlag flags
)
2895 if (flags
& DC_EXEC
) {
2896 ModifyStationRatingAround(t
->xy
, _current_company
, 0x70, 15);
2898 return CommandCost();
2901 static CommandCost
TownActionAdvertiseLarge(Town
*t
, DoCommandFlag flags
)
2903 if (flags
& DC_EXEC
) {
2904 ModifyStationRatingAround(t
->xy
, _current_company
, 0xA0, 20);
2906 return CommandCost();
2909 static CommandCost
TownActionRoadRebuild(Town
*t
, DoCommandFlag flags
)
2911 /* Check if the company is allowed to fund new roads. */
2912 if (!_settings_game
.economy
.fund_roads
) return CommandError();
2914 if (flags
& DC_EXEC
) {
2915 t
->road_build_months
= 6;
2917 char company_name
[MAX_LENGTH_COMPANY_NAME_CHARS
* MAX_CHAR_LENGTH
];
2918 SetDParam(0, _current_company
);
2919 GetString(company_name
, STR_COMPANY_NAME
, lastof(company_name
));
2921 char *cn
= stredup(company_name
);
2922 SetDParam(0, t
->index
);
2923 SetDParamStr(1, cn
);
2925 AddNewsItem(STR_NEWS_ROAD_REBUILDING
, NT_GENERAL
, NF_NORMAL
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
, cn
);
2926 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
2927 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
2929 return CommandCost();
2933 * Check whether the land can be cleared.
2934 * @param tile Tile to check.
2935 * @return The tile can be cleared.
2937 static bool TryClearTile(TileIndex tile
)
2939 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
2940 CommandCost r
= DoCommand(tile
, 0, 0, DC_NONE
, CMD_LANDSCAPE_CLEAR
);
2941 cur_company
.Restore();
2942 return r
.Succeeded();
2945 /** Structure for storing data while searching the best place to build a statue. */
2946 struct StatueBuildSearchData
{
2947 TileIndex best_position
; ///< Best position found so far.
2948 int tile_count
; ///< Number of tiles tried.
2950 StatueBuildSearchData(TileIndex best_pos
, int count
) : best_position(best_pos
), tile_count(count
) { }
2954 * Search callback function for #TownActionBuildStatue.
2955 * @param tile Tile on which to perform the search.
2956 * @param user_data Reference to the statue search data.
2957 * @return Result of the test.
2959 static bool SearchTileForStatue(TileIndex tile
, void *user_data
)
2961 static const int STATUE_NUMBER_INNER_TILES
= 25; // Number of tiles int the center of the city, where we try to protect houses.
2963 StatueBuildSearchData
*statue_data
= (StatueBuildSearchData
*)user_data
;
2964 statue_data
->tile_count
++;
2966 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2967 if (IsSteepSlope(GetTileSlope(tile
))) return false;
2968 /* Don't build statues under bridges. */
2969 if (IsBridgeAbove(tile
)) return false;
2971 /* A clear-able open space is always preferred. */
2972 if ((IsTileType(tile
, MP_CLEAR
) || IsTileType(tile
, MP_TREES
)) && TryClearTile(tile
)) {
2973 statue_data
->best_position
= tile
;
2977 bool house
= IsTileType(tile
, MP_HOUSE
);
2979 /* Searching inside the inner circle. */
2980 if (statue_data
->tile_count
<= STATUE_NUMBER_INNER_TILES
) {
2981 /* Save first house in inner circle. */
2982 if (house
&& statue_data
->best_position
== INVALID_TILE
&& TryClearTile(tile
)) {
2983 statue_data
->best_position
= tile
;
2986 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2987 return statue_data
->tile_count
== STATUE_NUMBER_INNER_TILES
&& statue_data
->best_position
!= INVALID_TILE
;
2990 /* Searching outside the circle, just pick the first possible spot. */
2991 statue_data
->best_position
= tile
; // Is optimistic, the condition below must also hold.
2992 return house
&& TryClearTile(tile
);
2996 * Perform a 9x9 tiles circular search from the center of the town
2997 * in order to find a free tile to place a statue
2998 * @param t town to search in
2999 * @param flags Used to check if the statue must be built or not.
3000 * @return Empty cost or an error.
3002 static CommandCost
TownActionBuildStatue(Town
*t
, DoCommandFlag flags
)
3004 if (!Object::CanAllocateItem()) return CommandError(STR_ERROR_TOO_MANY_OBJECTS
);
3006 TileIndex tile
= t
->xy
;
3007 StatueBuildSearchData
statue_data(INVALID_TILE
, 0);
3008 if (!CircularTileSearch(&tile
, 9, SearchTileForStatue
, &statue_data
)) return CommandError(STR_ERROR_STATUE_NO_SUITABLE_PLACE
);
3010 if (flags
& DC_EXEC
) {
3011 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
3012 DoCommand(statue_data
.best_position
, 0, 0, DC_EXEC
, CMD_LANDSCAPE_CLEAR
);
3013 cur_company
.Restore();
3014 BuildObject(OBJECT_STATUE
, statue_data
.best_position
, _current_company
, t
);
3015 SetBit(t
->statues
, _current_company
); // Once found and built, "inform" the Town.
3016 MarkTileDirtyByTile(statue_data
.best_position
);
3018 return CommandCost();
3021 static CommandCost
TownActionFundBuildings(Town
*t
, DoCommandFlag flags
)
3023 /* Check if it's allowed to buy the rights */
3024 if (!_settings_game
.economy
.fund_buildings
) return CommandError();
3026 if (flags
& DC_EXEC
) {
3027 /* And grow for 3 months */
3028 t
->fund_buildings_months
= 3;
3030 /* Enable growth (also checking GameScript's opinion) */
3031 UpdateTownGrowRate(t
);
3033 /* Build a new house, but add a small delay to make sure
3034 * that spamming funding doesn't let town grow any faster
3035 * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3036 * Also emulate original behaviour when town was only growing in
3037 * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3038 * tick-perfect and gives player some time window where he can
3039 * spam funding with the exact same effeciency.
3041 t
->grow_counter
= min(t
->grow_counter
, 2 * TOWN_GROWTH_TICKS
- (t
->growth_rate
- t
->grow_counter
) % TOWN_GROWTH_TICKS
);
3043 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3045 return CommandCost();
3048 static CommandCost
TownActionBuyRights(Town
*t
, DoCommandFlag flags
)
3050 /* Check if it's allowed to buy the rights */
3051 if (!_settings_game
.economy
.exclusive_rights
) return CommandError();
3053 if (flags
& DC_EXEC
) {
3054 t
->exclusive_counter
= 12;
3055 t
->exclusivity
= _current_company
;
3057 ModifyStationRatingAround(t
->xy
, _current_company
, 130, 17);
3059 SetWindowClassesDirty(WC_STATION_VIEW
);
3061 /* Spawn news message */
3062 CompanyNewsInformation
*cni
= MallocT
<CompanyNewsInformation
>(1);
3063 cni
->FillData(Company::Get(_current_company
));
3064 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE
);
3065 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION
);
3066 SetDParam(2, t
->index
);
3067 SetDParamStr(3, cni
->company_name
);
3068 AddNewsItem(STR_MESSAGE_NEWS_FORMAT
, NT_GENERAL
, NF_COMPANY
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
, cni
);
3069 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3070 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
3072 return CommandCost();
3075 static CommandCost
TownActionBribe(Town
*t
, DoCommandFlag flags
)
3077 if (flags
& DC_EXEC
) {
3078 if (Chance16(1, 14)) {
3079 /* set as unwanted for 6 months */
3080 t
->unwanted
[_current_company
] = 6;
3082 /* set all close by station ratings to 0 */
3084 FOR_ALL_STATIONS(st
) {
3085 if (st
->town
== t
&& st
->owner
== _current_company
) {
3086 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) st
->goods
[i
].rating
= 0;
3090 /* only show error message to the executing player. All errors are handled command.c
3091 * but this is special, because it can only 'fail' on a DC_EXEC */
3092 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED
, INVALID_STRING_ID
, WL_INFO
);
3094 /* decrease by a lot!
3095 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3096 * be independent of any cheat settings
3098 if (t
->ratings
[_current_company
] > RATING_BRIBE_DOWN_TO
) {
3099 t
->ratings
[_current_company
] = RATING_BRIBE_DOWN_TO
;
3100 t
->UpdateVirtCoord();
3101 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3104 ChangeTownRating(t
, RATING_BRIBE_UP_STEP
, RATING_BRIBE_MAXIMUM
, DC_EXEC
);
3107 return CommandCost();
3110 typedef CommandCost
TownActionProc(Town
*t
, DoCommandFlag flags
);
3111 static TownActionProc
* const _town_action_proc
[] = {
3112 TownActionAdvertiseSmall
,
3113 TownActionAdvertiseMedium
,
3114 TownActionAdvertiseLarge
,
3115 TownActionRoadRebuild
,
3116 TownActionBuildStatue
,
3117 TownActionFundBuildings
,
3118 TownActionBuyRights
,
3123 * Get a list of available actions to do at a town.
3124 * @param nump if not nullptr add put the number of available actions in it
3125 * @param cid the company that is querying the town
3126 * @param t the town that is queried
3127 * @return bitmasked value of enabled actions
3129 uint
GetMaskOfTownActions(int *nump
, CompanyID cid
, const Town
*t
)
3132 TownActions buttons
= TACT_NONE
;
3134 /* Spectators and unwanted have no options */
3135 if (cid
!= COMPANY_SPECTATOR
&& !(_settings_game
.economy
.bribe
&& t
->unwanted
[cid
])) {
3137 /* Things worth more than this are not shown */
3138 Money avail
= Company::Get(cid
)->money
+ _price
[PR_STATION_VALUE
] * 200;
3140 /* Check the action bits for validity and
3141 * if they are valid add them */
3142 for (uint i
= 0; i
!= lengthof(_town_action_costs
); i
++) {
3143 const TownActions cur
= (TownActions
)(1 << i
);
3145 /* Is the company not able to bribe ? */
3146 if (cur
== TACT_BRIBE
&& (!_settings_game
.economy
.bribe
|| t
->ratings
[cid
] >= RATING_BRIBE_MAXIMUM
)) continue;
3148 /* Is the company not able to buy exclusive rights ? */
3149 if (cur
== TACT_BUY_RIGHTS
&& !_settings_game
.economy
.exclusive_rights
) continue;
3151 /* Is the company not able to fund buildings ? */
3152 if (cur
== TACT_FUND_BUILDINGS
&& !_settings_game
.economy
.fund_buildings
) continue;
3154 /* Is the company not able to fund local road reconstruction? */
3155 if (cur
== TACT_ROAD_REBUILD
&& !_settings_game
.economy
.fund_roads
) continue;
3157 /* Is the company not able to build a statue ? */
3158 if (cur
== TACT_BUILD_STATUE
&& HasBit(t
->statues
, cid
)) continue;
3160 if (avail
>= _town_action_costs
[i
] * _price
[PR_TOWN_ACTION
] >> 8) {
3167 if (nump
!= nullptr) *nump
= num
;
3173 * This performs an action such as advertising, building a statue, funding buildings,
3174 * but also bribing the town-council
3175 * @param tile unused
3176 * @param flags type of operation
3177 * @param p1 town to do the action at
3178 * @param p2 action to perform, @see _town_action_proc for the list of available actions
3179 * @param text unused
3180 * @return the cost of this operation or an error
3182 CommandCost
CmdDoTownAction(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
3184 Town
*t
= Town::GetIfValid(p1
);
3185 if (t
== nullptr || p2
>= lengthof(_town_action_proc
)) return CommandError();
3187 if (!HasBit(GetMaskOfTownActions(nullptr, _current_company
, t
), p2
)) return CommandError();
3189 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_TOWN_ACTION
] * _town_action_costs
[p2
] >> 8);
3191 CommandCost ret
= _town_action_proc
[p2
](t
, flags
);
3192 if (ret
.Failed()) return ret
;
3194 if (flags
& DC_EXEC
) {
3195 SetWindowDirty(WC_TOWN_AUTHORITY
, p1
);
3201 static void UpdateTownRating(Town
*t
)
3203 /* Increase company ratings if they're low */
3205 FOR_ALL_COMPANIES(c
) {
3206 if (t
->ratings
[c
->index
] < RATING_GROWTH_MAXIMUM
) {
3207 t
->ratings
[c
->index
] = min((int)RATING_GROWTH_MAXIMUM
, t
->ratings
[c
->index
] + RATING_GROWTH_UP_STEP
);
3212 FOR_ALL_STATIONS(st
) {
3213 if (DistanceSquare(st
->xy
, t
->xy
) <= t
->cache
.squared_town_zone_radius
[0]) {
3214 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3215 if (Company::IsValidID(st
->owner
)) {
3216 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_UP_STEP
;
3217 t
->ratings
[st
->owner
] = min(new_rating
, INT16_MAX
); // do not let it overflow
3220 if (Company::IsValidID(st
->owner
)) {
3221 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_DOWN_STEP
;
3222 t
->ratings
[st
->owner
] = max(new_rating
, INT16_MIN
);
3228 /* clamp all ratings to valid values */
3229 for (uint i
= 0; i
< MAX_COMPANIES
; i
++) {
3230 t
->ratings
[i
] = Clamp(t
->ratings
[i
], RATING_MINIMUM
, RATING_MAXIMUM
);
3233 t
->UpdateVirtCoord();
3234 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3237 static void UpdateTownGrowRate(Town
*t
)
3239 ClrBit(t
->flags
, TOWN_IS_GROWING
);
3240 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3242 if (_settings_game
.economy
.town_growth_rate
== 0 && t
->fund_buildings_months
== 0) return;
3244 if (t
->fund_buildings_months
== 0) {
3245 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3246 for (int i
= TE_BEGIN
; i
< TE_END
; i
++) {
3247 switch (t
->goal
[i
]) {
3248 case TOWN_GROWTH_WINTER
:
3249 if (TileHeight(t
->xy
) >= GetSnowLine() && t
->received
[i
].old_act
== 0 && t
->cache
.population
> 90) return;
3251 case TOWN_GROWTH_DESERT
:
3252 if (GetTropicZone(t
->xy
) == TROPICZONE_DESERT
&& t
->received
[i
].old_act
== 0 && t
->cache
.population
> 60) return;
3255 if (t
->goal
[i
] > t
->received
[i
].old_act
) return;
3261 if (HasBit(t
->flags
, TOWN_CUSTOM_GROWTH
)) {
3262 if (t
->growth_rate
!= TOWN_GROWTH_RATE_NONE
) SetBit(t
->flags
, TOWN_IS_GROWING
);
3263 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3268 * Towns are processed every TOWN_GROWTH_TICKS ticks, and this is the
3269 * number of times towns are processed before a new building is built.
3271 static const uint16 _grow_count_values
[2][6] = {
3272 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3273 { 320, 420, 300, 220, 160, 100 } // Normal values
3279 FOR_ALL_STATIONS(st
) {
3280 if (DistanceSquare(st
->xy
, t
->xy
) <= t
->cache
.squared_town_zone_radius
[0]) {
3281 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3289 if (t
->fund_buildings_months
!= 0) {
3290 m
= _grow_count_values
[0][min(n
, 5)];
3292 m
= _grow_count_values
[1][min(n
, 5)];
3293 if (n
== 0 && !Chance16(1, 12)) return;
3296 /* Use the normal growth rate values if new buildings have been funded in
3297 * this town and the growth rate is set to none. */
3298 uint growth_multiplier
= _settings_game
.economy
.town_growth_rate
!= 0 ? _settings_game
.economy
.town_growth_rate
- 1 : 1;
3300 m
>>= growth_multiplier
;
3301 if (t
->larger_town
) m
/= 2;
3303 t
->growth_rate
= TownTicksToGameTicks(m
/ (t
->cache
.num_houses
/ 50 + 1));
3304 t
->grow_counter
= min(t
->growth_rate
, t
->grow_counter
);
3306 SetBit(t
->flags
, TOWN_IS_GROWING
);
3307 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3310 static void UpdateTownAmounts(Town
*t
)
3312 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) t
->supplied
[i
].NewMonth();
3313 for (int i
= TE_BEGIN
; i
< TE_END
; i
++) t
->received
[i
].NewMonth();
3314 if (t
->fund_buildings_months
!= 0) t
->fund_buildings_months
--;
3316 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3319 static void UpdateTownUnwanted(Town
*t
)
3323 FOR_ALL_COMPANIES(c
) {
3324 if (t
->unwanted
[c
->index
] > 0) t
->unwanted
[c
->index
]--;
3329 * Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
3330 * @param tile The tile where the station shall be constructed.
3331 * @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
3332 * @return Succeeded or failed command.
3334 CommandCost
CheckIfAuthorityAllowsNewStation(TileIndex tile
, DoCommandFlag flags
)
3336 return CommandCost();
3340 * Return the town closest to the given tile within \a threshold.
3341 * @param tile Starting point of the search.
3342 * @param threshold Biggest allowed distance to the town.
3343 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3345 * @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
3347 Town
*CalcClosestTownFromTile(TileIndex tile
, uint threshold
)
3350 uint best
= threshold
;
3351 Town
*best_town
= nullptr;
3354 uint dist
= DistanceManhattan(tile
, t
->xy
);
3365 * Return the town closest (in distance or ownership) to a given tile, within a given threshold.
3366 * @param tile Starting point of the search.
3367 * @param threshold Biggest allowed distance to the town.
3368 * @return Closest town to \a tile within \a threshold, or \c nullptr if there is no such town.
3370 * @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
3372 Town
*ClosestTownFromTile(TileIndex tile
, uint threshold
)
3374 switch (GetTileType(tile
)) {
3376 if (IsRoadDepot(tile
)) return CalcClosestTownFromTile(tile
, threshold
);
3378 if (!HasTownOwnedRoad(tile
)) {
3379 TownID tid
= GetTownIndex(tile
);
3381 if (tid
== (TownID
)INVALID_TOWN
) {
3382 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3383 if (_generating_world
) return CalcClosestTownFromTile(tile
, threshold
);
3384 assert(Town::GetNumItems() == 0);
3388 assert(Town::IsValidID(tid
));
3389 Town
*town
= Town::Get(tid
);
3391 if (DistanceManhattan(tile
, town
->xy
) >= threshold
) town
= nullptr;
3398 return Town::GetByTile(tile
);
3401 return CalcClosestTownFromTile(tile
, threshold
);
3405 static bool _town_rating_test
= false; ///< If \c true, town rating is in test-mode.
3406 static SmallMap
<const Town
*, int, 4> _town_test_ratings
; ///< Map of towns to modified ratings, while in town rating test-mode.
3409 * Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
3410 * The function is safe to use in nested calls.
3411 * @param mode Test mode switch (\c true means go to test-mode, \c false means leave test-mode).
3413 void SetTownRatingTestMode(bool mode
)
3415 static int ref_count
= 0; // Number of times test-mode is switched on.
3417 if (ref_count
== 0) {
3418 _town_test_ratings
.Clear();
3422 assert(ref_count
> 0);
3425 _town_rating_test
= !(ref_count
== 0);
3429 * Get the rating of a town for the #_current_company.
3430 * @param t Town to get the rating from.
3431 * @return Rating of the current company in the given town.
3433 static int GetRating(const Town
*t
)
3435 if (_town_rating_test
) {
3436 SmallMap
<const Town
*, int>::iterator it
= _town_test_ratings
.Find(t
);
3437 if (it
!= _town_test_ratings
.End()) {
3441 return t
->ratings
[_current_company
];
3445 * Changes town rating of the current company
3446 * @param t Town to affect
3447 * @param add Value to add
3448 * @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be achievable with this change.
3449 * @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
3451 void ChangeTownRating(Town
*t
, int add
, int max
, DoCommandFlag flags
)
3453 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3454 if (t
== nullptr || (flags
& DC_NO_MODIFY_TOWN_RATING
) ||
3455 !Company::IsValidID(_current_company
) ||
3456 (_cheats
.magic_bulldozer
.value
&& add
< 0)) {
3460 int rating
= GetRating(t
);
3464 if (rating
< max
) rating
= max
;
3469 if (rating
> max
) rating
= max
;
3472 if (_town_rating_test
) {
3473 _town_test_ratings
[t
] = rating
;
3475 SetBit(t
->have_ratings
, _current_company
);
3476 t
->ratings
[_current_company
] = rating
;
3477 t
->UpdateVirtCoord();
3478 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3483 * Does the town authority allow the (destructive) action of the current company?
3484 * @param flags Checking flags of the command.
3485 * @param t Town that must allow the company action.
3486 * @param type Type of action that is wanted.
3487 * @return A succeeded command if the action is allowed, a failed command if it is not allowed.
3489 CommandCost
CheckforTownRating(DoCommandFlag flags
, Town
*t
, TownRatingCheckType type
)
3491 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3492 if (t
== nullptr || !Company::IsValidID(_current_company
) ||
3493 _cheats
.magic_bulldozer
.value
|| (flags
& DC_NO_TEST_TOWN_RATING
)) {
3494 return CommandCost();
3497 /* minimum rating needed to be allowed to remove stuff */
3498 static const int needed_rating
[][TOWN_RATING_CHECK_TYPE_COUNT
] = {
3499 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3500 { RATING_ROAD_NEEDED_PERMISSIVE
, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
}, // Permissive
3501 { RATING_ROAD_NEEDED_NEUTRAL
, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
}, // Neutral
3502 { RATING_ROAD_NEEDED_HOSTILE
, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
}, // Hostile
3505 /* check if you're allowed to remove the road/bridge/tunnel
3506 * owned by a town no removal if rating is lower than ... depends now on
3507 * difficulty setting. Minimum town rating selected by difficulty level
3509 int needed
= needed_rating
[_settings_game
.difficulty
.town_council_tolerance
][type
];
3511 if (GetRating(t
) < needed
) {
3512 SetDParam(0, t
->index
);
3513 return CommandError(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
3516 return CommandCost();
3519 void TownsMonthlyLoop()
3524 if (t
->road_build_months
!= 0) t
->road_build_months
--;
3526 if (t
->exclusive_counter
!= 0) {
3527 if (--t
->exclusive_counter
== 0) t
->exclusivity
= INVALID_COMPANY
;
3530 UpdateTownAmounts(t
);
3531 UpdateTownRating(t
);
3532 UpdateTownGrowRate(t
);
3533 UpdateTownUnwanted(t
);
3534 UpdateTownCargoes(t
);
3537 UpdateTownCargoBitmap();
3540 void TownsYearlyLoop()
3542 /* Increment house ages */
3543 for (TileIndex t
= 0; t
< MapSize(); t
++) {
3544 if (!IsTileType(t
, MP_HOUSE
)) continue;
3545 IncrementHouseAge(t
);
3549 static CommandCost
TerraformTile_Town(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
3551 if (AutoslopeEnabled()) {
3552 HouseID house
= GetHouseType(tile
);
3553 GetHouseNorthPart(house
); // modifies house to the ID of the north tile
3554 const HouseSpec
*hs
= HouseSpec::Get(house
);
3556 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3557 if (((hs
->building_flags
& TILE_NOT_SLOPED
) == 0) && !IsSteepSlope(tileh_new
) &&
3558 (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
3559 bool allow_terraform
= true;
3561 /* Call the autosloping callback per tile, not for the whole building at once. */
3562 house
= GetHouseType(tile
);
3563 hs
= HouseSpec::Get(house
);
3564 if (HasBit(hs
->callback_mask
, CBM_HOUSE_AUTOSLOPE
)) {
3565 /* If the callback fails, allow autoslope. */
3566 uint16 res
= GetHouseCallback(CBID_HOUSE_AUTOSLOPE
, 0, 0, house
, Town::GetByTile(tile
), tile
);
3567 if (res
!= CALLBACK_FAILED
&& ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_AUTOSLOPE
, res
)) allow_terraform
= false;
3570 if (allow_terraform
) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3574 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
3577 /** Tile callback functions for a town */
3578 extern const TileTypeProcs _tile_type_town_procs
= {
3579 DrawTile_Town
, // draw_tile_proc
3580 GetSlopePixelZ_Town
, // get_slope_z_proc
3581 ClearTile_Town
, // clear_tile_proc
3582 AddAcceptedCargo_Town
, // add_accepted_cargo_proc
3583 GetTileDesc_Town
, // get_tile_desc_proc
3584 GetTileTrackStatus_Town
, // get_tile_track_status_proc
3585 nullptr, // click_tile_proc
3586 AnimateTile_Town
, // animate_tile_proc
3587 TileLoop_Town
, // tile_loop_proc
3588 ChangeTileOwner_Town
, // change_tile_owner_proc
3589 AddProducedCargo_Town
, // add_produced_cargo_proc
3590 nullptr, // vehicle_enter_tile_proc
3591 GetFoundation_Town
, // get_foundation_proc
3592 TerraformTile_Town
, // terraform_tile_proc
3596 HouseSpec _house_specs
[NUM_HOUSES
];
3600 memset(&_house_specs
, 0, sizeof(_house_specs
));
3601 memcpy(&_house_specs
, &_original_house_specs
, sizeof(_original_house_specs
));
3603 /* Reset any overrides that have been set. */
3604 _house_mngr
.ResetOverride();