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 "map/zoneheight.h"
32 #include "map/tunnelbridge.h"
33 #include "strings_func.h"
34 #include "window_func.h"
35 #include "string_func.h"
36 #include "newgrf_cargo.h"
37 #include "cheat_type.h"
38 #include "animated_tile_func.h"
39 #include "date_func.h"
40 #include "subsidy_func.h"
41 #include "core/pool_func.hpp"
43 #include "townname_func.h"
44 #include "core/random_func.hpp"
45 #include "core/backup_type.hpp"
46 #include "depot_base.h"
47 #include "map/object.h"
48 #include "object_base.h"
50 #include "game/game.hpp"
54 #include "table/strings.h"
55 #include "table/town_land.h"
58 uint32 _town_cargoes_accepted
; ///< Bitmap of all cargoes accepted by houses.
60 /* Initialize the town-pool */
61 TownPool
_town_pool("Town");
62 INSTANTIATE_POOL_METHODS(Town
)
69 if (CleaningPool()) return;
71 /* Delete town authority window
72 * and remove from list of sorted towns */
73 DeleteWindowById(WC_TOWN_VIEW
, this->index
);
75 /* Check no industry is related to us. */
77 FOR_ALL_INDUSTRIES(i
) assert(i
->town
!= this);
79 /* ... and no object is related to us. */
81 FOR_ALL_OBJECTS(o
) assert(o
->town
!= this);
83 /* Check no tile is related to us. */
84 for (TileIndex tile
= 0; tile
< MapSize(); ++tile
) {
85 if (IsHouseTile(tile
)) {
86 assert(GetTownIndex(tile
) != this->index
);
88 switch (GetTileType(tile
)) {
90 if (IsTunnelTile(tile
)) {
91 assert(!IsTileOwner(tile
, OWNER_TOWN
) || ClosestTownFromTile(tile
, UINT_MAX
) != this);
94 if (!IsLevelCrossingTile(tile
)) break;
97 assert(!HasTownOwnedRoad(tile
) || GetTownIndex(tile
) != this->index
);
106 /* Clear the persistent storage list. */
107 this->psa_list
.clear();
109 DeleteSubsidyWith(ST_TOWN
, this->index
);
110 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS
, this->index
);
111 CargoPacket::InvalidateAllFrom(ST_TOWN
, this->index
);
112 MarkWholeScreenDirty();
117 * Invalidating of the "nearest town cache" has to be done
118 * after removing item from the pool.
119 * @param index index of deleted item
121 void Town::PostDestructor(size_t index
)
123 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 0);
124 UpdateNearestTownForRoadTiles(false);
126 /* Give objects a new home! */
129 if (o
->town
== NULL
) o
->town
= CalcClosestTownFromTile(o
->location
.tile
, UINT_MAX
);
134 * Assigns town layout. If Random, generates one based on TileHash.
136 void Town::InitializeLayout(TownLayout layout
)
138 if (layout
!= TL_RANDOM
) {
139 this->layout
= layout
;
143 this->layout
= TileHash(TileX(this->xy
), TileY(this->xy
)) % (NUM_TLS
- 1);
147 * Return a random valid town.
148 * @return random town, NULL if there are no towns
150 /* static */ Town
*Town::GetRandom()
152 if (Town::GetNumItems() == 0) return NULL
;
153 int num
= RandomRange((uint16
)Town::GetNumItems());
154 size_t index
= MAX_UVALUE(size_t);
160 /* Make sure we have a valid town */
161 while (!Town::IsValidID(index
)) {
163 assert(index
< Town::GetPoolSize());
167 return Town::Get(index
);
171 * Get the cost for removing this house
172 * @return the cost (inflation corrected etc)
174 Money
HouseSpec::GetRemovalCost() const
176 return (_price
[PR_CLEAR_HOUSE
] * this->removal_cost
) >> 8;
180 static int _grow_town_result
;
182 /* Describe the possible states */
183 enum TownGrowthResult
{
185 GROWTH_SEARCH_STOPPED
= 0
186 // GROWTH_SEARCH_RUNNING >= 1
189 static bool BuildTownHouse(Town
*t
, TileIndex tile
);
190 static Town
*CreateRandomTown(uint attempts
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
);
192 static void TownDrawHouseLift(const TileInfo
*ti
)
194 AddChildSpriteScreen(SPR_LIFT
, PAL_NONE
, 14, 60 - GetLiftPosition(ti
->tile
));
197 typedef void TownDrawTileProc(const TileInfo
*ti
);
198 static TownDrawTileProc
* const _town_draw_tile_procs
[1] = {
203 * Return a random direction
205 * @return a random direction
207 static inline DiagDirection
RandomDiagDir()
209 return (DiagDirection
)(3 & Random());
213 * House Tile drawing handler.
214 * Part of the tile loop process
215 * @param ti TileInfo of the tile to draw
217 static void DrawTile_Town(TileInfo
*ti
)
219 HouseID house_id
= GetHouseType(ti
->tile
);
221 if (house_id
>= NEW_HOUSE_OFFSET
) {
222 /* Houses don't necessarily need new graphics. If they don't have a
223 * spritegroup associated with them, then the sprite for the substitute
224 * house id is drawn instead. */
225 if (HouseSpec::Get(house_id
)->grf_prop
.spritegroup
[0] != NULL
) {
226 DrawNewHouseTile(ti
, house_id
);
229 house_id
= HouseSpec::Get(house_id
)->grf_prop
.subst_id
;
233 /* Retrieve pointer to the draw town tile struct */
234 const DrawBuildingsTileStruct
*dcts
= &_town_draw_tile_data
[house_id
<< 4 | TileHash2Bit(ti
->x
, ti
->y
) << 2 | GetHouseBuildingStage(ti
->tile
)];
236 if (ti
->tileh
!= SLOPE_FLAT
) DrawFoundation(ti
, FOUNDATION_LEVELED
);
238 DrawGroundSprite(dcts
->ground
.sprite
, dcts
->ground
.pal
);
240 /* If houses are invisible, do not draw the upper part */
241 if (IsInvisibilitySet(TO_HOUSES
)) return;
243 /* Add a house on top of the ground? */
244 SpriteID image
= dcts
->building
.sprite
;
246 AddSortableSpriteToDraw(image
, dcts
->building
.pal
,
247 ti
->x
+ dcts
->subtile_x
,
248 ti
->y
+ dcts
->subtile_y
,
253 IsTransparencySet(TO_HOUSES
)
256 if (IsTransparencySet(TO_HOUSES
)) return;
260 int proc
= dcts
->draw_proc
- 1;
262 if (proc
>= 0) _town_draw_tile_procs
[proc
](ti
);
266 static int GetSlopePixelZ_Town(TileIndex tile
, uint x
, uint y
)
268 return GetTileMaxPixelZ(tile
);
271 /** Tile callback routine */
272 static Foundation
GetFoundation_Town(TileIndex tile
, Slope tileh
)
274 HouseID hid
= GetHouseType(tile
);
276 /* For NewGRF house tiles we might not be drawing a foundation. We need to
277 * account for this, as other structures should
278 * draw the wall of the foundation in this case.
280 if (hid
>= NEW_HOUSE_OFFSET
) {
281 const HouseSpec
*hs
= HouseSpec::Get(hid
);
282 if (hs
->grf_prop
.spritegroup
[0] != NULL
&& HasBit(hs
->callback_mask
, CBM_HOUSE_DRAW_FOUNDATIONS
)) {
283 uint32 callback_res
= GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS
, 0, 0, hid
, Town::GetByTile(tile
), tile
);
284 if (callback_res
!= CALLBACK_FAILED
&& !ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_DRAW_FOUNDATIONS
, callback_res
)) return FOUNDATION_NONE
;
287 return FlatteningFoundation(tileh
);
291 * Animate a tile for a town
292 * Only certain houses can be animated
293 * The newhouses animation supersedes regular ones
294 * @param tile TileIndex of the house to animate
296 static void AnimateTile_Town(TileIndex tile
)
298 if (GetHouseType(tile
) >= NEW_HOUSE_OFFSET
) {
299 AnimateNewHouseTile(tile
);
303 if (_tick_counter
& 3) return;
305 /* If the house is not one with a lift anymore, then stop this animating.
306 * Not exactly sure when this happens, but probably when a house changes.
307 * Before this was just a return...so it'd leak animated tiles..
308 * That bug seems to have been here since day 1?? */
309 if (!(HouseSpec::Get(GetHouseType(tile
))->building_flags
& BUILDING_IS_ANIMATED
)) {
310 DeleteAnimatedTile(tile
);
314 if (!LiftHasDestination(tile
)) {
317 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
318 * This is due to the fact that the first floor is, in the graphics,
319 * the height of 2 'normal' floors.
320 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
323 } while (i
== 1 || i
* 6 == GetLiftPosition(tile
));
325 SetLiftDestination(tile
, i
);
328 int pos
= GetLiftPosition(tile
);
329 int dest
= GetLiftDestination(tile
) * 6;
330 pos
+= (pos
< dest
) ? 1 : -1;
331 SetLiftPosition(tile
, pos
);
335 DeleteAnimatedTile(tile
);
338 MarkTileDirtyByTile(tile
);
342 * Determines if a town is close to a tile
343 * @param tile TileIndex of the tile to query
344 * @param dist maximum distance to be accepted
345 * @returns true if the tile correspond to the distance criteria
347 static bool IsCloseToTown(TileIndex tile
, uint dist
)
352 if (DistanceManhattan(tile
, t
->xy
) < dist
) return true;
358 * Resize the sign(label) of the town after changes in
359 * population (creation or growth or else)
361 void Town::UpdateVirtCoord()
363 Point pt
= RemapCoords2(TileX(this->xy
) * TILE_SIZE
, TileY(this->xy
) * TILE_SIZE
);
364 SetDParam(0, this->index
);
365 SetDParam(1, this->cache
.population
);
366 this->cache
.sign
.UpdatePosition(pt
.x
, pt
.y
- 24 * ZOOM_LVL_BASE
,
367 _settings_client
.gui
.population_in_label
? STR_VIEWPORT_TOWN_POP
: STR_VIEWPORT_TOWN
);
369 SetWindowDirty(WC_TOWN_VIEW
, this->index
);
372 /** Update the virtual coords needed to draw the town sign for all towns. */
373 void UpdateAllTownVirtCoords()
378 t
->UpdateVirtCoord();
383 * Change the towns population
384 * @param t Town which population has changed
385 * @param mod population change (can be positive or negative)
387 static void ChangePopulation(Town
*t
, int mod
)
389 t
->cache
.population
+= mod
;
390 InvalidateWindowData(WC_TOWN_VIEW
, t
->index
); // Cargo requirements may appear/vanish for small populations
391 t
->UpdateVirtCoord();
393 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 1);
397 * Determines the world population
398 * Basically, count population of all towns, one by one
399 * @return uint32 the calculated population of the world
401 uint32
GetWorldPopulation()
406 FOR_ALL_TOWNS(t
) pop
+= t
->cache
.population
;
411 * Helper function for house completion stages progression
412 * @param tile TileIndex of the house (or parts of it) to "grow"
414 static void MakeSingleHouseBigger(TileIndex tile
)
416 assert(IsHouseTile(tile
));
418 /* progress in construction stages */
419 IncHouseConstructionTick(tile
);
420 if (GetHouseConstructionTick(tile
) != 0) return;
422 AnimateNewHouseConstruction(tile
);
424 if (IsHouseCompleted(tile
)) {
425 /* Now that construction is complete, we can add the population of the
426 * building to the town. */
427 ChangePopulation(Town::GetByTile(tile
), HouseSpec::Get(GetHouseType(tile
))->population
);
430 MarkTileDirtyByTile(tile
);
434 * Make the house advance in its construction stages until completion
435 * @param tile TileIndex of house
437 static void MakeTownHouseBigger(TileIndex tile
)
439 uint flags
= HouseSpec::Get(GetHouseType(tile
))->building_flags
;
440 if (flags
& BUILDING_HAS_1_TILE
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 0, 0));
441 if (flags
& BUILDING_2_TILES_Y
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 0, 1));
442 if (flags
& BUILDING_2_TILES_X
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 1, 0));
443 if (flags
& BUILDING_HAS_4_TILES
) MakeSingleHouseBigger(TILE_ADDXY(tile
, 1, 1));
447 * Tile callback function.
449 * Periodic tic handler for houses and town
450 * @param tile been asked to do its stuff
452 static void TileLoop_Town(TileIndex tile
)
454 HouseID house_id
= GetHouseType(tile
);
456 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
457 * doesn't exist any more, so don't continue here. */
458 if (house_id
>= NEW_HOUSE_OFFSET
&& !NewHouseTileLoop(tile
)) return;
460 if (!IsHouseCompleted(tile
)) {
461 /* Construction is not completed. See if we can go further in construction*/
462 MakeTownHouseBigger(tile
);
466 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
468 /* If the lift has a destination, it is already an animated tile. */
469 if ((hs
->building_flags
& BUILDING_IS_ANIMATED
) &&
470 house_id
< NEW_HOUSE_OFFSET
&&
471 !LiftHasDestination(tile
) &&
473 AddAnimatedTile(tile
);
476 Town
*t
= Town::GetByTile(tile
);
479 StationFinder
stations(TileArea(tile
, 1, 1));
481 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
482 for (uint i
= 0; i
< 256; i
++) {
483 uint16 callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, r
, house_id
, t
, tile
);
485 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
487 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
488 if (cargo
== CT_INVALID
) continue;
490 uint amt
= GB(callback
, 0, 8);
491 if (amt
== 0) continue;
493 uint moved
= MoveGoodsToStation(cargo
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
495 const CargoSpec
*cs
= CargoSpec::Get(cargo
);
496 t
->supplied
[cs
->Index()].new_max
+= amt
;
497 t
->supplied
[cs
->Index()].new_act
+= moved
;
500 if (GB(r
, 0, 8) < hs
->population
) {
501 uint amt
= GB(r
, 0, 8) / 8 + 1;
503 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
504 t
->supplied
[CT_PASSENGERS
].new_max
+= amt
;
505 t
->supplied
[CT_PASSENGERS
].new_act
+= MoveGoodsToStation(CT_PASSENGERS
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
508 if (GB(r
, 8, 8) < hs
->mail_generation
) {
509 uint amt
= GB(r
, 8, 8) / 8 + 1;
511 if (EconomyIsInRecession()) amt
= (amt
+ 1) >> 1;
512 t
->supplied
[CT_MAIL
].new_max
+= amt
;
513 t
->supplied
[CT_MAIL
].new_act
+= MoveGoodsToStation(CT_MAIL
, amt
, ST_TOWN
, t
->index
, stations
.GetStations());
517 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
519 if ((hs
->building_flags
& BUILDING_HAS_1_TILE
) &&
520 HasBit(t
->flags
, TOWN_IS_GROWING
) &&
521 CanDeleteHouse(tile
) &&
522 GetHouseAge(tile
) >= hs
->minimum_life
&&
523 --t
->time_until_rebuild
== 0) {
524 t
->time_until_rebuild
= GB(r
, 16, 8) + 192;
526 ClearTownHouse(t
, tile
);
528 /* Rebuild with another house? */
529 if (GB(r
, 24, 8) >= 12) BuildTownHouse(t
, tile
);
532 cur_company
.Restore();
535 static CommandCost
ClearTile_Town(TileIndex tile
, DoCommandFlag flags
)
537 if (flags
& DC_AUTO
) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
538 if (!CanDeleteHouse(tile
)) return CMD_ERROR
;
540 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
542 CommandCost
cost(EXPENSES_CONSTRUCTION
);
543 cost
.AddCost(hs
->GetRemovalCost());
545 int rating
= hs
->remove_rating_decrease
;
546 Town
*t
= Town::GetByTile(tile
);
548 if (Company::IsValidID(_current_company
)) {
549 if (rating
> t
->ratings
[_current_company
] && !(flags
& DC_NO_TEST_TOWN_RATING
) && !_cheats
.magic_bulldozer
.value
) {
550 SetDParam(0, t
->index
);
551 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
555 ChangeTownRating(t
, -rating
, RATING_HOUSE_MINIMUM
, flags
);
556 if (flags
& DC_EXEC
) {
557 ClearTownHouse(t
, tile
);
563 static void AddProducedCargo_Town(TileIndex tile
, CargoArray
&produced
)
565 HouseID house_id
= GetHouseType(tile
);
566 const HouseSpec
*hs
= HouseSpec::Get(house_id
);
567 Town
*t
= Town::GetByTile(tile
);
569 if (HasBit(hs
->callback_mask
, CBM_HOUSE_PRODUCE_CARGO
)) {
570 for (uint i
= 0; i
< 256; i
++) {
571 uint16 callback
= GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO
, i
, 0, house_id
, t
, tile
);
573 if (callback
== CALLBACK_FAILED
|| callback
== CALLBACK_HOUSEPRODCARGO_END
) break;
575 CargoID cargo
= GetCargoTranslation(GB(callback
, 8, 7), hs
->grf_prop
.grffile
);
577 if (cargo
== CT_INVALID
) continue;
581 if (hs
->population
> 0) {
582 produced
[CT_PASSENGERS
]++;
584 if (hs
->mail_generation
> 0) {
590 static inline void AddAcceptedCargoSetMask(CargoID cargo
, uint amount
, CargoArray
&acceptance
, uint32
*always_accepted
)
592 if (cargo
== CT_INVALID
|| amount
== 0) return;
593 acceptance
[cargo
] += amount
;
594 SetBit(*always_accepted
, cargo
);
597 static void AddAcceptedCargo_Town(TileIndex tile
, CargoArray
&acceptance
, uint32
*always_accepted
)
599 const HouseSpec
*hs
= HouseSpec::Get(GetHouseType(tile
));
602 /* Set the initial accepted cargo types */
603 for (uint8 i
= 0; i
< lengthof(accepts
); i
++) {
604 accepts
[i
] = hs
->accepts_cargo
[i
];
607 /* Check for custom accepted cargo types */
608 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ACCEPT_CARGO
)) {
609 uint16 callback
= GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
610 if (callback
!= CALLBACK_FAILED
) {
611 /* Replace accepted cargo types with translated values from callback */
612 accepts
[0] = GetCargoTranslation(GB(callback
, 0, 5), hs
->grf_prop
.grffile
);
613 accepts
[1] = GetCargoTranslation(GB(callback
, 5, 5), hs
->grf_prop
.grffile
);
614 accepts
[2] = GetCargoTranslation(GB(callback
, 10, 5), hs
->grf_prop
.grffile
);
618 /* Check for custom cargo acceptance */
619 if (HasBit(hs
->callback_mask
, CBM_HOUSE_CARGO_ACCEPTANCE
)) {
620 uint16 callback
= GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE
, 0, 0, GetHouseType(tile
), Town::GetByTile(tile
), tile
);
621 if (callback
!= CALLBACK_FAILED
) {
622 AddAcceptedCargoSetMask(accepts
[0], GB(callback
, 0, 4), acceptance
, always_accepted
);
623 AddAcceptedCargoSetMask(accepts
[1], GB(callback
, 4, 4), acceptance
, always_accepted
);
624 if (_settings_game
.game_creation
.landscape
!= LT_TEMPERATE
&& HasBit(callback
, 12)) {
625 /* The 'S' bit indicates food instead of goods */
626 AddAcceptedCargoSetMask(CT_FOOD
, GB(callback
, 8, 4), acceptance
, always_accepted
);
628 AddAcceptedCargoSetMask(accepts
[2], GB(callback
, 8, 4), acceptance
, always_accepted
);
634 /* No custom acceptance, so fill in with the default values */
635 for (uint8 i
= 0; i
< lengthof(accepts
); i
++) {
636 AddAcceptedCargoSetMask(accepts
[i
], hs
->cargo_acceptance
[i
], acceptance
, always_accepted
);
640 static void GetTileDesc_Town(TileIndex tile
, TileDesc
*td
)
642 const HouseID house
= GetHouseType(tile
);
643 const HouseSpec
*hs
= HouseSpec::Get(house
);
644 bool house_completed
= IsHouseCompleted(tile
);
646 td
->str
= hs
->building_name
;
648 uint16 callback_res
= GetHouseCallback(CBID_HOUSE_CUSTOM_NAME
, house_completed
? 1 : 0, 0, house
, Town::GetByTile(tile
), tile
);
649 if (callback_res
!= CALLBACK_FAILED
&& callback_res
!= 0x400) {
650 if (callback_res
> 0x400) {
651 ErrorUnknownCallbackResult(hs
->grf_prop
.grffile
->grfid
, CBID_HOUSE_CUSTOM_NAME
, callback_res
);
653 StringID new_name
= GetGRFStringID(hs
->grf_prop
.grffile
->grfid
, 0xD000 + callback_res
);
654 if (new_name
!= STR_NULL
&& new_name
!= STR_UNDEFINED
) {
660 if (!house_completed
) {
661 SetDParamX(td
->dparam
, 0, td
->str
);
662 td
->str
= STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION
;
665 if (hs
->grf_prop
.grffile
!= NULL
) {
666 const GRFConfig
*gc
= GetGRFConfig(hs
->grf_prop
.grffile
->grfid
);
667 td
->grf
= gc
->GetName();
670 td
->owner
[0] = OWNER_TOWN
;
673 static void ChangeTileOwner_Town(TileIndex tile
, Owner old_owner
, Owner new_owner
)
678 /** Update the total cargo acceptance of the whole town.
679 * @param t The town to update.
681 void UpdateTownCargoTotal(Town
*t
)
683 t
->cargo_accepted_total
= 0;
685 const TileArea
&area
= t
->cargo_accepted
.GetArea();
686 TILE_AREA_LOOP(tile
, area
) {
687 if (TileX(tile
) % AcceptanceMatrix::GRID
== 0 && TileY(tile
) % AcceptanceMatrix::GRID
== 0) {
688 t
->cargo_accepted_total
|= t
->cargo_accepted
[tile
];
694 * Update accepted town cargoes around a specific tile.
695 * @param t The town to update.
696 * @param start Update the values around this tile.
697 * @param update_total Set to true if the total cargo acceptance should be updated.
699 static void UpdateTownCargoes(Town
*t
, TileIndex start
, bool update_total
= true)
701 CargoArray accepted
, produced
;
704 /* Gather acceptance for all houses in an area around the start tile.
705 * The area is composed of the square the tile is in, extended one square in all
706 * directions as the coverage area of a single station is bigger than just one square. */
707 TileArea area
= AcceptanceMatrix::GetAreaForTile(start
, 1);
708 TILE_AREA_LOOP(tile
, area
) {
709 if (!IsHouseTile(tile
) || GetTownIndex(tile
) != t
->index
) continue;
711 AddAcceptedCargo_Town(tile
, accepted
, &dummy
);
712 AddProducedCargo_Town(tile
, produced
);
715 /* Create bitmap of produced and accepted cargoes. */
717 for (uint cid
= 0; cid
< NUM_CARGO
; cid
++) {
718 if (accepted
[cid
] >= 8) SetBit(acc
, cid
);
719 if (produced
[cid
] > 0) SetBit(t
->cargo_produced
, cid
);
721 t
->cargo_accepted
[start
] = acc
;
723 if (update_total
) UpdateTownCargoTotal(t
);
726 /** Update cargo acceptance for the complete town.
727 * @param t The town to update.
729 void UpdateTownCargoes(Town
*t
)
731 t
->cargo_produced
= 0;
733 const TileArea
&area
= t
->cargo_accepted
.GetArea();
734 if (area
.tile
== INVALID_TILE
) return;
736 /* Update acceptance for each grid square. */
737 TILE_AREA_LOOP(tile
, area
) {
738 if (TileX(tile
) % AcceptanceMatrix::GRID
== 0 && TileY(tile
) % AcceptanceMatrix::GRID
== 0) {
739 UpdateTownCargoes(t
, tile
, false);
743 /* Update the total acceptance. */
744 UpdateTownCargoTotal(t
);
747 /** Updates the bitmap of all cargoes accepted by houses. */
748 void UpdateTownCargoBitmap()
751 _town_cargoes_accepted
= 0;
753 FOR_ALL_TOWNS(town
) {
754 _town_cargoes_accepted
|= town
->cargo_accepted_total
;
758 static bool GrowTown(Town
*t
);
760 static void TownTickHandler(Town
*t
)
762 if (HasBit(t
->flags
, TOWN_IS_GROWING
)) {
763 int i
= t
->grow_counter
- 1;
766 i
= t
->growth_rate
& (~TOWN_GROW_RATE_CUSTOM
);
777 if (_game_mode
== GM_EDITOR
) return;
781 /* Run town tick at regular intervals, but not all at once. */
782 if ((_tick_counter
+ t
->index
) % TOWN_GROWTH_TICKS
== 0) {
789 * Return the RoadBits of a tile
791 * @note There are many other functions doing things like that.
792 * @note Needs to be checked for needlessness.
793 * @param tile The tile we want to analyse
794 * @return The roadbits of the given tile
796 static RoadBits
GetTownRoadBits(TileIndex tile
)
798 if (IsRoadDepotTile(tile
) || IsStandardRoadStopTile(tile
)) return ROAD_NONE
;
800 return GetAnyRoadBits(tile
, ROADTYPE_ROAD
, true);
804 * Check for parallel road inside a given distance.
805 * Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
806 * is there a parallel road left or right of it within distance dist_multi?
808 * @param tile current tile
809 * @param dir target direction
810 * @param dist_multi distance multiplayer
811 * @return true if there is a parallel road
813 static bool IsNeighborRoadTile(TileIndex tile
, const DiagDirection dir
, uint dist_multi
)
815 if (!IsValidTile(tile
)) return false;
817 /* Lookup table for the used diff values */
818 const TileIndexDiff tid_lt
[3] = {
819 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90RIGHT
)),
820 TileOffsByDiagDir(ChangeDiagDir(dir
, DIAGDIRDIFF_90LEFT
)),
821 TileOffsByDiagDir(ReverseDiagDir(dir
)),
824 dist_multi
= (dist_multi
+ 1) * 4;
825 for (uint pos
= 4; pos
< dist_multi
; pos
++) {
826 /* Go (pos / 4) tiles to the left or the right */
827 TileIndexDiff cur
= tid_lt
[(pos
& 1) ? 0 : 1] * (pos
/ 4);
829 /* Use the current tile as origin, or go one tile backwards */
830 if (pos
& 2) cur
+= tid_lt
[2];
832 /* Test for roadbit parallel to dir and facing towards the middle axis */
833 if (IsValidTile(tile
+ cur
) &&
834 GetTownRoadBits(TILE_ADD(tile
, cur
)) & DiagDirToRoadBits((pos
& 2) ? dir
: ReverseDiagDir(dir
))) return true;
840 * Check if a Road is allowed on a given tile
842 * @param t The current town
843 * @param tile The target tile
844 * @param dir The direction in which we want to extend the town
845 * @return true if it is allowed else false
847 static bool IsRoadAllowedHere(Town
*t
, TileIndex tile
, DiagDirection dir
)
849 if (DistanceFromEdge(tile
) == 0) return false;
851 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
852 if (HasBridgeAbove(tile
) && GetBridgeAxis(tile
) == DiagDirToAxis(dir
)) return false;
854 /* Check if there already is a road at this point? */
855 if (GetTownRoadBits(tile
) == ROAD_NONE
) {
856 /* No, try if we are able to build a road piece there.
857 * If that fails clear the land, and if that fails exit.
858 * This is to make sure that we can build a road here later. */
859 if (DoCommand(tile
, ((dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? ROAD_Y
: ROAD_X
), 0, DC_AUTO
, CMD_BUILD_ROAD
).Failed() &&
860 DoCommand(tile
, 0, 0, DC_AUTO
, CMD_LANDSCAPE_CLEAR
).Failed()) {
865 Slope cur_slope
= _settings_game
.construction
.build_on_slopes
? GetFoundationSlope(tile
) : GetTileSlope(tile
);
866 bool ret
= !IsNeighborRoadTile(tile
, dir
, t
->layout
== TL_ORIGINAL
? 1 : 2);
867 if (cur_slope
== SLOPE_FLAT
) return ret
;
869 /* If the tile is not a slope in the right direction, then
870 * maybe terraform some. */
871 Slope desired_slope
= (dir
== DIAGDIR_NW
|| dir
== DIAGDIR_SE
) ? SLOPE_NW
: SLOPE_NE
;
872 if (desired_slope
!= cur_slope
&& ComplementSlope(desired_slope
) != cur_slope
) {
873 if (Chance16(1, 8)) {
874 CommandCost res
= CMD_ERROR
;
875 if (!_generating_world
&& Chance16(1, 10)) {
876 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
877 res
= DoCommand(tile
, Chance16(1, 16) ? cur_slope
: cur_slope
^ SLOPE_ELEVATED
, 0,
878 DC_EXEC
| DC_AUTO
| DC_NO_WATER
, CMD_TERRAFORM_LAND
);
880 if (res
.Failed() && Chance16(1, 3)) {
881 /* We can consider building on the slope, though. */
890 static bool TerraformTownTile(TileIndex tile
, int edges
, int dir
)
892 assert(tile
< MapSize());
894 CommandCost r
= DoCommand(tile
, edges
, dir
, DC_AUTO
| DC_NO_WATER
, CMD_TERRAFORM_LAND
);
895 if (r
.Failed() || r
.GetCost() >= (_price
[PR_TERRAFORM
] + 2) * 8) return false;
896 DoCommand(tile
, edges
, dir
, DC_AUTO
| DC_NO_WATER
| DC_EXEC
, CMD_TERRAFORM_LAND
);
900 static void LevelTownLand(TileIndex tile
)
902 assert(tile
< MapSize());
904 /* Don't terraform if land is plain or if there's a house there. */
905 if (IsHouseTile(tile
)) return;
906 Slope tileh
= GetTileSlope(tile
);
907 if (tileh
== SLOPE_FLAT
) return;
909 /* First try up, then down */
910 if (!TerraformTownTile(tile
, ~tileh
& SLOPE_ELEVATED
, 1)) {
911 TerraformTownTile(tile
, tileh
& SLOPE_ELEVATED
, 0);
916 * Generate the RoadBits of a grid tile
918 * @param t current town
919 * @param tile tile in reference to the town
920 * @param dir The direction to which we are growing ATM
921 * @return the RoadBit of the current tile regarding
922 * the selected town layout
924 static RoadBits
GetTownRoadGridElement(Town
*t
, TileIndex tile
, DiagDirection dir
)
926 /* align the grid to the downtown */
927 CoordDiff grid_pos
= TileCoordDiff(t
->xy
, tile
); // Vector from downtown to the tile
928 RoadBits rcmd
= ROAD_NONE
;
931 default: NOT_REACHED();
934 if ((grid_pos
.x
% 3) == 0) rcmd
|= ROAD_Y
;
935 if ((grid_pos
.y
% 3) == 0) rcmd
|= ROAD_X
;
939 if ((grid_pos
.x
% 4) == 0) rcmd
|= ROAD_Y
;
940 if ((grid_pos
.y
% 4) == 0) rcmd
|= ROAD_X
;
944 /* Optimise only X-junctions */
945 if (rcmd
!= ROAD_ALL
) return rcmd
;
947 RoadBits rb_template
;
949 switch (GetTileSlope(tile
)) {
950 default: rb_template
= ROAD_ALL
; break;
951 case SLOPE_W
: rb_template
= ROAD_NW
| ROAD_SW
; break;
952 case SLOPE_SW
: rb_template
= ROAD_Y
| ROAD_SW
; break;
953 case SLOPE_S
: rb_template
= ROAD_SW
| ROAD_SE
; break;
954 case SLOPE_SE
: rb_template
= ROAD_X
| ROAD_SE
; break;
955 case SLOPE_E
: rb_template
= ROAD_SE
| ROAD_NE
; break;
956 case SLOPE_NE
: rb_template
= ROAD_Y
| ROAD_NE
; break;
957 case SLOPE_N
: rb_template
= ROAD_NE
| ROAD_NW
; break;
958 case SLOPE_NW
: rb_template
= ROAD_X
| ROAD_NW
; break;
963 rb_template
= ROAD_NONE
;
967 /* Stop if the template is compatible to the growth dir */
968 if (DiagDirToRoadBits(ReverseDiagDir(dir
)) & rb_template
) return rb_template
;
969 /* If not generate a straight road in the direction of the growth */
970 return DiagDirToRoadBits(dir
) | DiagDirToRoadBits(ReverseDiagDir(dir
));
974 * Grows the town with an extra house.
975 * Check if there are enough neighbor house tiles
976 * next to the current tile. If there are enough
979 * @param t The current town
980 * @param tile The target tile for the extra house
981 * @return true if an extra house has been added
983 static bool GrowTownWithExtraHouse(Town
*t
, TileIndex tile
)
985 /* We can't look further than that. */
986 if (DistanceFromEdge(tile
) == 0) return false;
988 uint counter
= 0; // counts the house neighbor tiles
990 /* Check the tiles E,N,W and S of the current tile for houses */
991 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
< DIAGDIR_END
; dir
++) {
992 /* Count both void and house tiles for checking whether there
993 * are enough houses in the area. This to make it likely that
994 * houses get build up to the edge of the map. */
995 TileIndex tt
= TileAddByDiagDir(tile
, dir
);
996 if (IsHouseTile(tt
) || IsVoidTile(tt
)) {
1000 /* If there are enough neighbors stop here */
1002 if (BuildTownHouse(t
, tile
)) {
1003 _grow_town_result
= GROWTH_SUCCEED
;
1013 * Grows the town with a road piece.
1015 * @param t The current town
1016 * @param tile The current tile
1017 * @param rcmd The RoadBits we want to build on the tile
1018 * @return true if the RoadBits have been added else false
1020 static bool GrowTownWithRoad(const Town
*t
, TileIndex tile
, RoadBits rcmd
)
1022 if (DoCommand(tile
, rcmd
, t
->index
, DC_EXEC
| DC_AUTO
| DC_NO_WATER
, CMD_BUILD_ROAD
).Succeeded()) {
1023 _grow_town_result
= GROWTH_SUCCEED
;
1030 * Grows the town with a bridge.
1031 * At first we check if a bridge is reasonable.
1032 * If so we check if we are able to build it.
1034 * @param t The current town
1035 * @param tile The current tile
1036 * @param bridge_dir The valid direction in which to grow a bridge
1037 * @return true if a bridge has been build else false
1039 static bool GrowTownWithBridge(const Town
*t
, const TileIndex tile
, const DiagDirection bridge_dir
)
1041 assert(bridge_dir
< DIAGDIR_END
);
1043 const Slope slope
= GetTileSlope(tile
);
1045 /* Make sure the direction is compatible with the slope.
1046 * Well we check if the slope has an up bit set in the
1047 * reverse direction. */
1048 if (slope
!= SLOPE_FLAT
&& slope
& InclinedSlope(bridge_dir
)) return false;
1050 /* Assure that the bridge is connectable to the start side */
1051 if (!(GetTownRoadBits(TileAddByDiagDir(tile
, ReverseDiagDir(bridge_dir
))) & DiagDirToRoadBits(bridge_dir
))) return false;
1053 /* We are in the right direction */
1054 uint8 bridge_length
= 0; // This value stores the length of the possible bridge
1055 TileIndex bridge_tile
= tile
; // Used to store the other waterside
1057 const int delta
= TileOffsByDiagDir(bridge_dir
);
1059 if (slope
== SLOPE_FLAT
) {
1060 /* Bridges starting on flat tiles are only allowed when crossing rivers. */
1062 if (bridge_length
++ >= 4) {
1063 /* Allow to cross rivers, not big lakes. */
1066 bridge_tile
+= delta
;
1067 } while (IsValidTile(bridge_tile
) && IsPlainWaterTile(bridge_tile
) && !IsSea(bridge_tile
));
1070 if (bridge_length
++ >= 11) {
1071 /* Max 11 tile long bridges */
1074 bridge_tile
+= delta
;
1075 } while (IsValidTile(bridge_tile
) && IsPlainWaterTile(bridge_tile
));
1078 /* no water tiles in between? */
1079 if (bridge_length
== 1) return false;
1081 for (uint8 times
= 0; times
<= 22; times
++) {
1082 byte bridge_type
= RandomRange(MAX_BRIDGES
- 1);
1084 /* Can we actually build the bridge? */
1085 if (DoCommand(tile
, bridge_tile
, bridge_type
| ROADTYPES_ROAD
<< 8 | TRANSPORT_ROAD
<< 12 | t
->index
<< 16, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE
)), CMD_BUILD_BRIDGE
).Succeeded()) {
1086 DoCommand(tile
, bridge_tile
, bridge_type
| ROADTYPES_ROAD
<< 8 | TRANSPORT_ROAD
<< 12 | t
->index
<< 16, DC_EXEC
| CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE
)), CMD_BUILD_BRIDGE
);
1087 _grow_town_result
= GROWTH_SUCCEED
;
1091 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1096 * Grows the given town.
1097 * There are at the moment 3 possible way's for
1098 * the town expansion:
1099 * @li Generate a random tile and check if there is a road allowed
1101 * @li TL_BETTER_ROADS
1102 * @li Check if the town geometry allows a road and which one
1105 * @li Forbid roads, only build houses
1107 * @param tile_ptr The current tile
1108 * @param cur_rb The current tiles RoadBits
1109 * @param target_dir The target road dir
1110 * @param t1 The current town
1112 static void GrowTownInTile(TileIndex
*tile_ptr
, RoadBits cur_rb
, DiagDirection target_dir
, Town
*t1
)
1114 RoadBits rcmd
= ROAD_NONE
; // RoadBits for the road construction command
1115 TileIndex tile
= *tile_ptr
; // The main tile on which we base our growth
1117 assert(tile
< MapSize());
1119 if (cur_rb
== ROAD_NONE
) {
1120 /* Tile has no road. First reset the status counter
1121 * to say that this is the last iteration. */
1122 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1124 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return;
1125 if (!_settings_game
.economy
.allow_town_level_crossings
&& IsRailwayTile(tile
)) return;
1127 /* Remove hills etc */
1128 if (!_settings_game
.construction
.build_on_slopes
|| Chance16(1, 6)) LevelTownLand(tile
);
1130 /* Is a road allowed here? */
1131 switch (t1
->layout
) {
1132 default: NOT_REACHED();
1136 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1137 if (rcmd
== ROAD_NONE
) return;
1140 case TL_BETTER_ROADS
:
1142 if (!IsRoadAllowedHere(t1
, tile
, target_dir
)) return;
1144 DiagDirection source_dir
= ReverseDiagDir(target_dir
);
1146 if (Chance16(1, 4)) {
1147 /* Randomize a new target dir */
1148 do target_dir
= RandomDiagDir(); while (target_dir
== source_dir
);
1151 if (!IsRoadAllowedHere(t1
, TileAddByDiagDir(tile
, target_dir
), target_dir
)) {
1152 /* A road is not allowed to continue the randomized road,
1153 * return if the road we're trying to build is curved. */
1154 if (target_dir
!= ReverseDiagDir(source_dir
)) return;
1156 /* Return if neither side of the new road is a house */
1157 if (!IsHouseTile(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90RIGHT
))) &&
1158 !IsHouseTile(TileAddByDiagDir(tile
, ChangeDiagDir(target_dir
, DIAGDIRDIFF_90LEFT
)))) {
1162 /* That means that the road is only allowed if there is a house
1163 * at any side of the new road. */
1166 rcmd
= DiagDirToRoadBits(target_dir
) | DiagDirToRoadBits(source_dir
);
1170 } else if (target_dir
< DIAGDIR_END
&& !(cur_rb
& DiagDirToRoadBits(ReverseDiagDir(target_dir
)))) {
1171 /* Continue building on a partial road.
1172 * Should be always OK, so we only generate
1173 * the fitting RoadBits */
1174 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1176 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return;
1178 switch (t1
->layout
) {
1179 default: NOT_REACHED();
1183 rcmd
= GetTownRoadGridElement(t1
, tile
, target_dir
);
1186 case TL_BETTER_ROADS
:
1188 rcmd
= DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1192 bool allow_house
= true; // Value which decides if we want to construct a house
1194 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1195 * it is the starting tile. Half the time, we stay on this side then.*/
1196 if (IsRoadBridgeTile(tile
) || maptile_is_road_tunnel(tile
)) {
1197 if (target_dir
!= DIAGDIR_END
|| Chance16(1, 2)) {
1198 *tile_ptr
= GetOtherTunnelBridgeEnd(tile
);
1203 /* Possibly extend the road in a direction.
1204 * Randomize a direction and if it has a road, bail out. */
1205 target_dir
= RandomDiagDir();
1206 if (cur_rb
& DiagDirToRoadBits(target_dir
)) return;
1208 /* This is the tile we will reach if we extend to this direction. */
1209 TileIndex house_tile
= TileAddByDiagDir(tile
, target_dir
); // position of a possible house
1211 /* Don't walk into water. */
1212 if (HasTileWaterGround(house_tile
)) return;
1214 if (!IsValidTile(house_tile
)) return;
1216 if (_settings_game
.economy
.allow_town_roads
|| _generating_world
) {
1217 switch (t1
->layout
) {
1218 default: NOT_REACHED();
1220 case TL_3X3_GRID
: // Use 2x2 grid afterwards!
1221 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1225 rcmd
= GetTownRoadGridElement(t1
, house_tile
, target_dir
);
1226 allow_house
= (rcmd
== ROAD_NONE
);
1229 case TL_BETTER_ROADS
: // Use original afterwards!
1230 GrowTownWithExtraHouse(t1
, TileAddByDiagDir(house_tile
, target_dir
));
1234 /* Allow a house at the edge. 60% chance or
1235 * always ok if no road allowed. */
1236 rcmd
= DiagDirToRoadBits(target_dir
);
1237 allow_house
= (!IsRoadAllowedHere(t1
, house_tile
, target_dir
) || Chance16(6, 10));
1243 /* Build a house, but not if there already is a house there. */
1244 if (!IsHouseTile(house_tile
)) {
1245 /* Level the land if possible */
1246 if (Chance16(1, 6)) LevelTownLand(house_tile
);
1248 /* And build a house.
1249 * Set result to -1 if we managed to build it. */
1250 if (BuildTownHouse(t1
, house_tile
)) {
1251 _grow_town_result
= GROWTH_SUCCEED
;
1257 _grow_town_result
= GROWTH_SEARCH_STOPPED
;
1260 /* Return if a water tile */
1261 if (HasTileWaterGround(tile
)) return;
1263 /* Make the roads look nicer */
1264 rcmd
= CleanUpRoadBits(tile
, rcmd
);
1265 if (rcmd
== ROAD_NONE
) return;
1267 /* Only use the target direction for bridges to ensure they're connected.
1268 * The target_dir is as computed previously according to town layout, so
1269 * it will match it perfectly. */
1270 if (GrowTownWithBridge(t1
, tile
, target_dir
)) return;
1272 GrowTownWithRoad(t1
, tile
, rcmd
);
1276 * Returns "growth" if a house was built, or no if the build failed.
1277 * @param t town to inquiry
1278 * @param tile to inquiry
1279 * @return something other than zero(0)if town expansion was possible
1281 static int GrowTownAtRoad(Town
*t
, TileIndex tile
)
1284 * @see GrowTownInTile Check the else if
1286 DiagDirection target_dir
= DIAGDIR_END
; // The direction in which we want to extend the town
1288 assert(tile
< MapSize());
1290 /* Number of times to search.
1291 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1292 * them a little handicap. */
1293 switch (t
->layout
) {
1294 case TL_BETTER_ROADS
:
1295 _grow_town_result
= 10 + t
->cache
.num_houses
* 2 / 9;
1300 _grow_town_result
= 10 + t
->cache
.num_houses
* 1 / 9;
1304 _grow_town_result
= 10 + t
->cache
.num_houses
* 4 / 9;
1309 RoadBits cur_rb
= GetTownRoadBits(tile
); // The RoadBits of the current tile
1311 /* Try to grow the town from this point */
1312 GrowTownInTile(&tile
, cur_rb
, target_dir
, t
);
1314 /* Exclude the source position from the bitmask
1315 * and return if no more road blocks available */
1316 if (IsValidDiagDirection(target_dir
)) cur_rb
&= ~DiagDirToRoadBits(ReverseDiagDir(target_dir
));
1317 if (cur_rb
== ROAD_NONE
) {
1318 return _grow_town_result
;
1321 if (IsTunnelTile(tile
) || IsRoadBridgeTile(tile
)) {
1322 /* Only build in the direction away from the tunnel or bridge. */
1323 target_dir
= ReverseDiagDir(GetTunnelBridgeDirection(tile
));
1325 /* Select a random bit from the blockmask, walk a step
1326 * and continue the search from there. */
1327 do target_dir
= RandomDiagDir(); while (!(cur_rb
& DiagDirToRoadBits(target_dir
)));
1329 tile
= TileAddByDiagDir(tile
, target_dir
);
1331 if ((IsRoadTile(tile
) || IsLevelCrossingTile(tile
)) && HasTileRoadType(tile
, ROADTYPE_ROAD
)) {
1332 /* Don't allow building over roads of other cities */
1333 if (IsRoadOwner(tile
, ROADTYPE_ROAD
, OWNER_TOWN
) && Town::GetByTile(tile
) != t
) {
1334 _grow_town_result
= GROWTH_SUCCEED
;
1335 } else if (IsRoadOwner(tile
, ROADTYPE_ROAD
, OWNER_NONE
) && _game_mode
== GM_EDITOR
) {
1336 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1337 * owner :) (happy happy happy road now) */
1338 SetRoadOwner(tile
, ROADTYPE_ROAD
, OWNER_TOWN
);
1339 SetTownIndex(tile
, t
->index
);
1343 /* Max number of times is checked. */
1344 } while (--_grow_town_result
>= 0);
1346 return (_grow_town_result
== -2);
1350 * Generate a random road block.
1351 * The probability of a straight road
1352 * is somewhat higher than a curved.
1354 * @return A RoadBits value with 2 bits set
1356 static RoadBits
GenRandomRoadBits()
1358 uint32 r
= Random();
1359 uint a
= GB(r
, 0, 2);
1360 uint b
= GB(r
, 8, 2);
1362 return (RoadBits
)((ROAD_NW
<< a
) + (ROAD_NW
<< b
));
1367 * @param t town to grow
1368 * @return true iff a house was built
1370 static bool GrowTown(Town
*t
)
1372 static const CoordDiff _town_coord_mod
[] = {
1388 /* Current "company" is a town */
1389 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
1391 TileIndex tile
= t
->xy
; // The tile we are working with ATM
1393 /* Find a road that we can base the construction on. */
1394 const CoordDiff
*ptr
;
1395 for (ptr
= _town_coord_mod
; ptr
!= endof(_town_coord_mod
); ++ptr
) {
1396 if (GetTownRoadBits(tile
) != ROAD_NONE
) {
1397 int r
= GrowTownAtRoad(t
, tile
);
1398 cur_company
.Restore();
1401 tile
= TILE_ADD(tile
, ToTileIndexDiff(*ptr
));
1404 /* No road available, try to build a random road block by
1405 * clearing some land and then building a road there. */
1406 if (_settings_game
.economy
.allow_town_roads
|| _generating_world
) {
1408 for (ptr
= _town_coord_mod
; ptr
!= endof(_town_coord_mod
); ++ptr
) {
1409 /* Only work with plain land that not already has a house */
1410 if (!IsHouseTile(tile
) && IsTileFlat(tile
)) {
1411 if (DoCommand(tile
, 0, 0, DC_AUTO
| DC_NO_WATER
, CMD_LANDSCAPE_CLEAR
).Succeeded()) {
1412 DoCommand(tile
, GenRandomRoadBits(), t
->index
, DC_EXEC
| DC_AUTO
, CMD_BUILD_ROAD
);
1413 cur_company
.Restore();
1417 tile
= TILE_ADD(tile
, ToTileIndexDiff(*ptr
));
1421 cur_company
.Restore();
1425 void UpdateTownRadius(Town
*t
)
1427 static const uint32 _town_squared_town_zone_radius_data
[23][5] = {
1428 { 4, 0, 0, 0, 0}, // 0
1433 { 64, 0, 4, 0, 0}, // 20
1438 { 81, 0, 16, 0, 4}, // 40
1440 { 81, 36, 25, 0, 9},
1441 { 81, 36, 25, 16, 9},
1442 { 81, 49, 0, 25, 9},
1443 { 81, 64, 0, 25, 9}, // 60
1444 { 81, 64, 0, 36, 9},
1445 { 81, 64, 0, 36, 16},
1446 {100, 81, 0, 49, 16},
1447 {100, 81, 0, 49, 25},
1448 {121, 81, 0, 49, 25}, // 80
1449 {121, 81, 0, 49, 25},
1450 {121, 81, 0, 49, 36}, // 88
1453 if (t
->cache
.num_houses
< 92) {
1454 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
));
1456 int mass
= t
->cache
.num_houses
/ 8;
1457 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1458 * The offsets are to make sure the radii do not decrease in size when going from the table
1459 * to the calculated value.*/
1460 t
->cache
.squared_town_zone_radius
[0] = mass
* 15 - 40;
1461 t
->cache
.squared_town_zone_radius
[1] = mass
* 9 - 15;
1462 t
->cache
.squared_town_zone_radius
[2] = 0;
1463 t
->cache
.squared_town_zone_radius
[3] = mass
* 5 - 5;
1464 t
->cache
.squared_town_zone_radius
[4] = mass
* 3 + 5;
1468 void UpdateTownMaxPass(Town
*t
)
1470 t
->supplied
[CT_PASSENGERS
].old_max
= t
->cache
.population
>> 3;
1471 t
->supplied
[CT_MAIL
].old_max
= t
->cache
.population
>> 4;
1475 * Does the actual town creation.
1478 * @param tile Where to put it
1479 * @param townnameparts The town name
1480 * @param size Parameter for size determination
1481 * @param city whether to build a city or town
1482 * @param layout the (road) layout of the town
1483 * @param manual was the town placed manually?
1485 static void DoCreateTown(Town
*t
, TileIndex tile
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
, bool manual
)
1488 t
->cache
.num_houses
= 0;
1489 t
->time_until_rebuild
= 10;
1490 UpdateTownRadius(t
);
1492 t
->cache
.population
= 0;
1493 t
->grow_counter
= 0;
1494 t
->growth_rate
= 250;
1496 /* Set the default cargo requirement for town growth */
1497 switch (_settings_game
.game_creation
.landscape
) {
1499 if (FindFirstCargoWithTownEffect(TE_FOOD
) != NULL
) t
->goal
[TE_FOOD
] = TOWN_GROWTH_WINTER
;
1503 if (FindFirstCargoWithTownEffect(TE_FOOD
) != NULL
) t
->goal
[TE_FOOD
] = TOWN_GROWTH_DESERT
;
1504 if (FindFirstCargoWithTownEffect(TE_WATER
) != NULL
) t
->goal
[TE_WATER
] = TOWN_GROWTH_DESERT
;
1508 t
->fund_buildings_months
= 0;
1510 for (uint i
= 0; i
!= MAX_COMPANIES
; i
++) t
->ratings
[i
] = RATING_INITIAL
;
1512 t
->have_ratings
= 0;
1513 t
->exclusivity
= INVALID_COMPANY
;
1514 t
->exclusive_counter
= 0;
1517 extern int _nb_orig_names
;
1518 if (_settings_game
.game_creation
.town_name
< _nb_orig_names
) {
1519 /* Original town name */
1520 t
->townnamegrfid
= 0;
1521 t
->townnametype
= SPECSTR_TOWNNAME_START
+ _settings_game
.game_creation
.town_name
;
1523 /* Newgrf town name */
1524 t
->townnamegrfid
= GetGRFTownNameId(_settings_game
.game_creation
.town_name
- _nb_orig_names
);
1525 t
->townnametype
= GetGRFTownNameType(_settings_game
.game_creation
.town_name
- _nb_orig_names
);
1527 t
->townnameparts
= townnameparts
;
1529 t
->UpdateVirtCoord();
1530 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 0);
1532 t
->InitializeLayout(layout
);
1534 t
->larger_town
= city
;
1536 int x
= (int)size
* 16 + 3;
1537 if (size
== TSZ_RANDOM
) x
= (Random() & 0xF) + 8;
1538 /* Don't create huge cities when founding town in-game */
1539 if (city
&& (!manual
|| _game_mode
== GM_EDITOR
)) x
*= _settings_game
.economy
.initial_city_size
;
1541 t
->cache
.num_houses
+= x
;
1542 UpdateTownRadius(t
);
1549 t
->cache
.num_houses
-= x
;
1550 UpdateTownRadius(t
);
1551 UpdateTownMaxPass(t
);
1552 UpdateAirportsNoise();
1556 * Checks if it's possible to place a town at given tile
1557 * @param tile tile to check
1558 * @return error value or zero cost
1560 static CommandCost
TownCanBePlacedHere(TileIndex tile
)
1562 /* Check if too close to the edge of map */
1563 if (DistanceFromEdge(tile
) < 12) {
1564 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB
);
1567 /* Check distance to all other towns. */
1568 if (IsCloseToTown(tile
, 20)) {
1569 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN
);
1572 /* Can only build on clear flat areas, possibly with trees. */
1573 if (!IsGroundTile(tile
) || !IsTileFlat(tile
)) {
1574 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
1577 return CommandCost(EXPENSES_OTHER
);
1581 * Verifies this custom name is unique. Only custom names are checked.
1582 * @param name name to check
1583 * @return is this name unique?
1585 static bool IsUniqueTownName(const char *name
)
1590 if (t
->name
!= NULL
&& strcmp(t
->name
, name
) == 0) return false;
1597 * Create a new town.
1598 * @param tile coordinates where town is built
1599 * @param flags type of operation
1600 * @param p1 0..1 size of the town (@see TownSize)
1601 * 2 true iff it should be a city
1602 * 3..5 town road layout (@see TownLayout)
1603 * 6 use random location (randomize \c tile )
1604 * @param p2 town name parts
1605 * @param text Custom name for the town. If empty, the town name parts will be used.
1606 * @return the cost of this operation or an error
1608 CommandCost
CmdFoundTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1610 TownSize size
= Extract
<TownSize
, 0, 2>(p1
);
1611 bool city
= HasBit(p1
, 2);
1612 TownLayout layout
= Extract
<TownLayout
, 3, 3>(p1
);
1613 TownNameParams
par(_settings_game
.game_creation
.town_name
);
1614 bool random
= HasBit(p1
, 6);
1615 uint32 townnameparts
= p2
;
1617 if (size
>= TSZ_END
) return CMD_ERROR
;
1618 if (layout
>= NUM_TLS
) return CMD_ERROR
;
1620 /* Some things are allowed only in the scenario editor and for game scripts. */
1621 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) {
1622 if (_settings_game
.economy
.found_town
== TF_FORBIDDEN
) return CMD_ERROR
;
1623 if (size
== TSZ_LARGE
) return CMD_ERROR
;
1624 if (random
) return CMD_ERROR
;
1625 if (_settings_game
.economy
.found_town
!= TF_CUSTOM_LAYOUT
&& layout
!= _settings_game
.economy
.town_layout
) {
1628 } else if (_current_company
== OWNER_DEITY
&& random
) {
1629 /* Random parameter is not allowed for Game Scripts. */
1633 if (StrEmpty(text
)) {
1634 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1635 if (!VerifyTownName(townnameparts
, &par
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1637 /* If name is not empty, it has to be unique custom name */
1638 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return CMD_ERROR
;
1639 if (!IsUniqueTownName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
1642 /* Allocate town struct */
1643 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS
);
1646 CommandCost ret
= TownCanBePlacedHere(tile
);
1647 if (ret
.Failed()) return ret
;
1650 static const byte price_mult
[][TSZ_RANDOM
+ 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1651 /* multidimensional arrays have to have defined length of non-first dimension */
1652 assert_compile(lengthof(price_mult
[0]) == 4);
1654 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_BUILD_TOWN
]);
1655 byte mult
= price_mult
[city
][size
];
1657 cost
.MultiplyCost(mult
);
1659 /* Create the town */
1660 if (flags
& DC_EXEC
) {
1661 if (cost
.GetCost() > GetAvailableMoneyForCommand()) {
1662 _additional_cash_required
= cost
.GetCost();
1663 return CommandCost(EXPENSES_OTHER
);
1666 Backup
<bool> old_generating_world(_generating_world
, true, FILE_LINE
);
1667 UpdateNearestTownForRoadTiles(true);
1670 t
= CreateRandomTown(20, townnameparts
, size
, city
, layout
);
1672 cost
= CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN
);
1674 _new_town_id
= t
->index
;
1678 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, true);
1680 UpdateNearestTownForRoadTiles(false);
1681 old_generating_world
.Restore();
1683 if (t
!= NULL
&& !StrEmpty(text
)) {
1684 t
->name
= strdup(text
);
1685 t
->UpdateVirtCoord();
1688 if (_game_mode
!= GM_EDITOR
) {
1689 /* 't' can't be NULL since 'random' is false outside scenedit */
1691 char company_name
[MAX_LENGTH_COMPANY_NAME_CHARS
* MAX_CHAR_LENGTH
];
1692 SetDParam(0, _current_company
);
1693 GetString(company_name
, STR_COMPANY_NAME
, lastof(company_name
));
1695 char *cn
= strdup(company_name
);
1696 SetDParamStr(0, cn
);
1697 SetDParam(1, t
->index
);
1699 AddTileNewsItem(STR_NEWS_NEW_TOWN
, NT_INDUSTRY_OPEN
, tile
, cn
);
1700 AI::BroadcastNewEvent(new ScriptEventTownFounded(t
->index
));
1701 Game::NewEvent(new ScriptEventTownFounded(t
->index
));
1708 * Towns must all be placed on the same grid or when they eventually
1709 * interpenetrate their road networks will not mesh nicely; this
1710 * function adjusts a tile so that it aligns properly.
1712 * @param tile the tile to start at
1713 * @param layout which town layout algo is in effect
1714 * @return the adjusted tile
1716 static TileIndex
AlignTileToGrid(TileIndex tile
, TownLayout layout
)
1719 case TL_2X2_GRID
: return TileXY(TileX(tile
) - TileX(tile
) % 3, TileY(tile
) - TileY(tile
) % 3);
1720 case TL_3X3_GRID
: return TileXY(TileX(tile
) & ~3, TileY(tile
) & ~3);
1721 default: return tile
;
1726 * Towns must all be placed on the same grid or when they eventually
1727 * interpenetrate their road networks will not mesh nicely; this
1728 * function tells you if a tile is properly aligned.
1730 * @param tile the tile to start at
1731 * @param layout which town layout algo is in effect
1732 * @return true if the tile is in the correct location
1734 static bool IsTileAlignedToGrid(TileIndex tile
, TownLayout layout
)
1737 case TL_2X2_GRID
: return TileX(tile
) % 3 == 0 && TileY(tile
) % 3 == 0;
1738 case TL_3X3_GRID
: return TileX(tile
) % 4 == 0 && TileY(tile
) % 4 == 0;
1739 default: return true;
1744 * Used as the user_data for FindFurthestFromWater
1747 TileIndex tile
; ///< holds the tile that was found
1748 uint max_dist
; ///< holds the distance that tile is from the water
1749 TownLayout layout
; ///< tells us what kind of town we're building
1753 * CircularTileSearch callback; finds the tile furthest from any
1754 * water. slightly bit tricky, since it has to do a search of its own
1755 * in order to find the distance to the water from each square in the
1758 * Also, this never returns true, because it needs to take into
1759 * account all locations being searched before it knows which is the
1762 * @param tile Start looking from this tile
1763 * @param user_data Storage area for data that must last across calls;
1764 * must be a pointer to struct SpotData
1766 * @return always false
1768 static bool FindFurthestFromWater(TileIndex tile
, void *user_data
)
1770 SpotData
*sp
= (SpotData
*)user_data
;
1771 uint dist
= GetClosestWaterDistance(tile
, true);
1773 if (IsGroundTile(tile
) &&
1775 IsTileAlignedToGrid(tile
, sp
->layout
) &&
1776 dist
> sp
->max_dist
) {
1778 sp
->max_dist
= dist
;
1785 * CircularTileSearch callback; finds the nearest land tile
1787 * @param tile Start looking from this tile
1788 * @param user_data not used
1790 static bool FindNearestEmptyLand(TileIndex tile
, void *user_data
)
1792 return IsGroundTile(tile
);
1796 * Given a spot on the map (presumed to be a water tile), find a good
1797 * coastal spot to build a city. We don't want to build too close to
1798 * the edge if we can help it (since that retards city growth) hence
1799 * the search within a search within a search. O(n*m^2), where n is
1800 * how far to search for land, and m is how far inland to look for a
1803 * @param tile Start looking from this spot.
1804 * @param layout the road layout to search for
1805 * @return tile that was found
1807 static TileIndex
FindNearestGoodCoastalTownSpot(TileIndex tile
, TownLayout layout
)
1809 SpotData sp
= { INVALID_TILE
, 0, layout
};
1811 TileIndex coast
= tile
;
1812 if (CircularTileSearch(&coast
, 40, FindNearestEmptyLand
, NULL
)) {
1813 CircularTileSearch(&coast
, 10, FindFurthestFromWater
, &sp
);
1817 /* if we get here just give up */
1818 return INVALID_TILE
;
1821 static Town
*CreateRandomTown(uint attempts
, uint32 townnameparts
, TownSize size
, bool city
, TownLayout layout
)
1823 assert(_game_mode
== GM_EDITOR
|| _generating_world
); // These are the preconditions for CMD_DELETE_TOWN
1825 if (!Town::CanAllocateItem()) return NULL
;
1828 /* Generate a tile index not too close from the edge */
1829 TileIndex tile
= AlignTileToGrid(RandomTile(), layout
);
1831 /* if we tried to place the town on water, slide it over onto
1832 * the nearest likely-looking spot */
1833 if (IsWaterTile(tile
)) {
1834 tile
= FindNearestGoodCoastalTownSpot(tile
, layout
);
1835 if (tile
== INVALID_TILE
) continue;
1838 /* Make sure town can be placed here */
1839 if (TownCanBePlacedHere(tile
).Failed()) continue;
1841 /* Allocate a town struct */
1842 Town
*t
= new Town(tile
);
1844 DoCreateTown(t
, tile
, townnameparts
, size
, city
, layout
, false);
1846 /* if the population is still 0 at the point, then the
1847 * placement is so bad it couldn't grow at all */
1848 if (t
->cache
.population
> 0) return t
;
1850 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_TOWN
, FILE_LINE
);
1851 CommandCost rc
= DoCommand(t
->xy
, t
->index
, 0, DC_EXEC
, CMD_DELETE_TOWN
);
1852 cur_company
.Restore();
1853 assert(rc
.Succeeded());
1855 /* We already know that we can allocate a single town when
1856 * entering this function. However, we create and delete
1857 * a town which "resets" the allocation checks. As such we
1858 * need to check again when assertions are enabled. */
1859 assert(Town::CanAllocateItem());
1860 } while (--attempts
!= 0);
1865 static const byte _num_initial_towns
[4] = {5, 11, 23, 46}; // very low, low, normal, high
1868 * This function will generate a certain amount of towns, with a certain layout
1869 * It can be called from the scenario editor (i.e.: generate Random Towns)
1870 * as well as from world creation.
1871 * @param layout which towns will be set to, when created
1872 * @return true if towns have been successfully created
1874 bool GenerateTowns(TownLayout layout
)
1876 uint current_number
= 0;
1877 uint difficulty
= (_game_mode
!= GM_EDITOR
) ? _settings_game
.difficulty
.number_towns
: 0;
1878 uint total
= (difficulty
== (uint
)CUSTOM_TOWN_NUMBER_DIFFICULTY
) ? _settings_game
.game_creation
.custom_town_number
: ScaleByMapSize(_num_initial_towns
[difficulty
] + (Random() & 7));
1879 uint32 townnameparts
;
1881 SetGeneratingWorldProgress(GWP_TOWN
, total
);
1883 /* First attempt will be made at creating the suggested number of towns.
1884 * Note that this is really a suggested value, not a required one.
1885 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
1887 bool city
= (_settings_game
.economy
.larger_towns
!= 0 && Chance16(1, _settings_game
.economy
.larger_towns
));
1888 IncreaseGeneratingWorldProgress(GWP_TOWN
);
1889 /* Get a unique name for the town. */
1890 if (!GenerateTownName(&townnameparts
)) continue;
1891 /* try 20 times to create a random-sized town for the first loop. */
1892 if (CreateRandomTown(20, townnameparts
, TSZ_RANDOM
, city
, layout
) != NULL
) current_number
++; // If creation was successful, raise a flag.
1895 if (current_number
!= 0) return true;
1897 /* If current_number is still zero at this point, it means that not a single town has been created.
1898 * So give it a last try, but now more aggressive */
1899 if (GenerateTownName(&townnameparts
) &&
1900 CreateRandomTown(10000, townnameparts
, TSZ_RANDOM
, _settings_game
.economy
.larger_towns
!= 0, layout
) != NULL
) {
1904 /* If there are no towns at all and we are generating new game, bail out */
1905 if (Town::GetNumItems() == 0 && _game_mode
!= GM_EDITOR
) {
1906 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN
, INVALID_STRING_ID
, WL_CRITICAL
);
1909 return false; // we are still without a town? we failed, simply
1914 * Returns the bit corresponding to the town zone of the specified tile
1915 * @param t Town on which town zone is to be found
1916 * @param tile TileIndex where town zone needs to be found
1917 * @return the bit position of the given zone, as defined in HouseZones
1919 HouseZonesBits
GetTownRadiusGroup(const Town
*t
, TileIndex tile
)
1921 uint dist
= DistanceSquare(tile
, t
->xy
);
1923 if (t
->fund_buildings_months
&& dist
<= 25) return HZB_TOWN_CENTRE
;
1925 HouseZonesBits smallest
= HZB_TOWN_EDGE
;
1926 for (HouseZonesBits i
= HZB_BEGIN
; i
< HZB_END
; i
++) {
1927 if (dist
< t
->cache
.squared_town_zone_radius
[i
]) smallest
= i
;
1934 * Clears tile and builds a house or house part.
1935 * @param tile tile index
1936 * @param t The town to clear the house for
1937 * @param counter of construction step
1938 * @param stage of construction (used for drawing)
1939 * @param type of house. Index into house specs array
1940 * @param random_bits required for newgrf houses
1941 * @pre house can be built here
1943 static inline void ClearMakeHouseTile(TileIndex tile
, Town
*t
, byte counter
, byte stage
, HouseID type
, byte random_bits
)
1945 CommandCost cc
= DoCommand(tile
, 0, 0, DC_EXEC
| DC_AUTO
| DC_NO_WATER
, CMD_LANDSCAPE_CLEAR
);
1947 assert(cc
.Succeeded());
1949 assert(IsGroundTile(tile
));
1951 IncreaseBuildingCount(t
, type
);
1952 MakeHouseTile(tile
, t
->index
, counter
, stage
, type
, random_bits
, HouseSpec::Get(type
)->processing_time
);
1953 if (HouseSpec::Get(type
)->building_flags
& BUILDING_IS_ANIMATED
) AddAnimatedTile(tile
);
1955 MarkTileDirtyByTile(tile
);
1960 * Write house information into the map. For houses > 1 tile, all tiles are marked.
1961 * @param t tile index
1962 * @param town The town related to this house
1963 * @param counter of construction step
1964 * @param stage of construction (used for drawing)
1965 * @param type of house. Index into house specs array
1966 * @param random_bits required for newgrf houses
1967 * @pre house can be built here
1969 static void MakeTownHouse(TileIndex t
, Town
*town
, byte counter
, byte stage
, HouseID type
, byte random_bits
)
1971 BuildingFlags size
= HouseSpec::Get(type
)->building_flags
;
1973 ClearMakeHouseTile(t
, town
, counter
, stage
, type
, random_bits
);
1974 if (size
& BUILDING_2_TILES_Y
) ClearMakeHouseTile(t
+ TileDiffXY(0, 1), town
, counter
, stage
, ++type
, random_bits
);
1975 if (size
& BUILDING_2_TILES_X
) ClearMakeHouseTile(t
+ TileDiffXY(1, 0), town
, counter
, stage
, ++type
, random_bits
);
1976 if (size
& BUILDING_HAS_4_TILES
) ClearMakeHouseTile(t
+ TileDiffXY(1, 1), town
, counter
, stage
, ++type
, random_bits
);
1981 * Checks if a house can be built here. Important is slope, bridge above
1982 * and ability to clear the land.
1983 * @param tile tile to check
1984 * @param town town that is checking
1985 * @param noslope are slopes (foundations) allowed?
1986 * @return true iff house can be built here
1988 static inline bool CanBuildHouseHere(TileIndex tile
, TownID town
, bool noslope
)
1990 /* cannot build on these slopes... */
1991 Slope slope
= GetTileSlope(tile
);
1992 if ((noslope
&& slope
!= SLOPE_FLAT
) || IsSteepSlope(slope
)) return false;
1994 /* building under a bridge? */
1995 if (HasBridgeAbove(tile
)) return false;
1997 /* do not try to build over house owned by another town */
1998 if (IsHouseTile(tile
) && GetTownIndex(tile
) != town
) return false;
2000 /* can we clear the land? */
2001 return DoCommand(tile
, 0, 0, DC_AUTO
| DC_NO_WATER
, CMD_LANDSCAPE_CLEAR
).Succeeded();
2006 * Checks if a house can be built at this tile, must have the same max z as parameter.
2007 * @param tile tile to check
2008 * @param town town that is checking
2009 * @param z max z of this tile so more parts of a house are at the same height (with foundation)
2010 * @param noslope are slopes (foundations) allowed?
2011 * @return true iff house can be built here
2012 * @see CanBuildHouseHere()
2014 static inline bool CheckBuildHouseSameZ(TileIndex tile
, TownID town
, int z
, bool noslope
)
2016 if (!CanBuildHouseHere(tile
, town
, noslope
)) return false;
2018 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2019 if (GetTileMaxZ(tile
) != z
) return false;
2026 * Checks if a house of size 2x2 can be built at this tile
2027 * @param tile tile, N corner
2028 * @param town town that is checking
2029 * @param z maximum tile z so all tile have the same max z
2030 * @param noslope are slopes (foundations) allowed?
2031 * @return true iff house can be built
2032 * @see CheckBuildHouseSameZ()
2034 static bool CheckFree2x2Area(TileIndex tile
, TownID town
, int z
, bool noslope
)
2036 /* we need to check this tile too because we can be at different tile now */
2037 if (!CheckBuildHouseSameZ(tile
, town
, z
, noslope
)) return false;
2039 for (DiagDirection d
= DIAGDIR_SE
; d
< DIAGDIR_END
; d
++) {
2040 tile
+= TileOffsByDiagDir(d
);
2041 if (!CheckBuildHouseSameZ(tile
, town
, z
, noslope
)) return false;
2049 * Checks if current town layout allows building here
2051 * @param tile tile to check
2052 * @return true iff town layout allows building here
2055 static inline bool TownLayoutAllowsHouseHere(Town
*t
, TileIndex tile
)
2057 /* Allow towns everywhere when we don't build roads */
2058 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return true;
2060 CoordDiff grid_pos
= TileCoordDiff(t
->xy
, tile
);
2062 switch (t
->layout
) {
2064 if ((grid_pos
.x
% 3) == 0 || (grid_pos
.y
% 3) == 0) return false;
2068 if ((grid_pos
.x
% 4) == 0 || (grid_pos
.y
% 4) == 0) return false;
2080 * Checks if current town layout allows 2x2 building here
2082 * @param tile tile to check
2083 * @return true iff town layout allows 2x2 building here
2086 static inline bool TownLayoutAllows2x2HouseHere(Town
*t
, TileIndex tile
)
2088 /* Allow towns everywhere when we don't build roads */
2089 if (!_settings_game
.economy
.allow_town_roads
&& !_generating_world
) return true;
2091 /* Compute relative position of tile. (Positive offsets are towards north) */
2092 CoordDiff grid_pos
= TileCoordDiff(t
->xy
, tile
);
2094 switch (t
->layout
) {
2098 if ((grid_pos
.x
!= 2 && grid_pos
.x
!= -1) ||
2099 (grid_pos
.y
!= 2 && grid_pos
.y
!= -1)) return false;
2103 if ((grid_pos
.x
& 3) < 2 || (grid_pos
.y
& 3) < 2) return false;
2115 * Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout
2116 * Also, tests both building positions that occupy this tile
2117 * @param tile tile where the building should be built
2119 * @param maxz all tiles should have the same height
2120 * @param noslope are slopes forbidden?
2121 * @param second diagdir from first tile to second tile
2123 static bool CheckTownBuild2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
, DiagDirection second
)
2125 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2127 TileIndex tile2
= *tile
+ TileOffsByDiagDir(second
);
2128 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, t
->index
, maxz
, noslope
)) return true;
2130 tile2
= *tile
+ TileOffsByDiagDir(ReverseDiagDir(second
));
2131 if (TownLayoutAllowsHouseHere(t
, tile2
) && CheckBuildHouseSameZ(tile2
, t
->index
, maxz
, noslope
)) {
2141 * Checks if 2x2 building is allowed here, also takes into account current town layout
2142 * Also, tests all four building positions that occupy this tile
2143 * @param tile tile where the building should be built
2145 * @param maxz all tiles should have the same height
2146 * @param noslope are slopes forbidden?
2148 static bool CheckTownBuild2x2House(TileIndex
*tile
, Town
*t
, int maxz
, bool noslope
)
2150 TileIndex tile2
= *tile
;
2152 for (DiagDirection d
= DIAGDIR_SE
;; d
++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2153 if (TownLayoutAllows2x2HouseHere(t
, tile2
) && CheckFree2x2Area(tile2
, t
->index
, maxz
, noslope
)) {
2157 if (d
== DIAGDIR_END
) break;
2158 tile2
+= TileOffsByDiagDir(ReverseDiagDir(d
)); // go clockwise
2166 * Tries to build a house at this tile
2167 * @param t town the house will belong to
2168 * @param tile where the house will be built
2169 * @return false iff no house can be built at this tile
2171 static bool BuildTownHouse(Town
*t
, TileIndex tile
)
2173 /* forbidden building here by town layout */
2174 if (!TownLayoutAllowsHouseHere(t
, tile
)) return false;
2176 /* no house allowed at all, bail out */
2177 if (!CanBuildHouseHere(tile
, t
->index
, false)) return false;
2179 Slope slope
= GetTileSlope(tile
);
2180 int maxz
= GetTileMaxZ(tile
);
2182 /* Get the town zone type of the current tile, as well as the climate.
2183 * This will allow to easily compare with the specs of the new house to build */
2184 HouseZonesBits rad
= GetTownRadiusGroup(t
, tile
);
2187 int land
= _settings_game
.game_creation
.landscape
;
2188 if (land
== LT_ARCTIC
&& maxz
> HighestSnowLine()) land
= -1;
2190 uint bitmask
= (1 << rad
) + (1 << (land
+ 12));
2192 /* bits 0-4 are used
2193 * bits 11-15 are used
2194 * bits 5-10 are not used. */
2195 HouseID houses
[NUM_HOUSES
];
2197 uint probs
[NUM_HOUSES
];
2198 uint probability_max
= 0;
2200 /* Generate a list of all possible houses that can be built. */
2201 for (uint i
= 0; i
< NUM_HOUSES
; i
++) {
2202 const HouseSpec
*hs
= HouseSpec::Get(i
);
2204 /* Verify that the candidate house spec matches the current tile status */
2205 if ((~hs
->building_availability
& bitmask
) != 0 || !hs
->enabled
|| hs
->grf_prop
.override
!= INVALID_HOUSE_ID
) continue;
2207 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2208 if (hs
->class_id
!= HOUSE_NO_CLASS
) {
2209 /* id_count is always <= class_count, so it doesn't need to be checked */
2210 if (t
->cache
.building_counts
.class_count
[hs
->class_id
] == UINT16_MAX
) continue;
2212 /* If the house has no class, check id_count instead */
2213 if (t
->cache
.building_counts
.id_count
[i
] == UINT16_MAX
) continue;
2216 /* Without NewHouses, all houses have probability '1' */
2217 uint cur_prob
= (_loaded_newgrf_features
.has_newhouses
? hs
->probability
: 1);
2218 probability_max
+= cur_prob
;
2219 probs
[num
] = cur_prob
;
2220 houses
[num
++] = (HouseID
)i
;
2223 TileIndex baseTile
= tile
;
2225 while (probability_max
> 0) {
2226 /* Building a multitile building can change the location of tile.
2227 * The building would still be built partially on that tile, but
2228 * its northern tile would be elsewhere. However, if the callback
2229 * fails we would be basing further work from the changed tile.
2230 * So a next 1x1 tile building could be built on the wrong tile. */
2233 uint r
= RandomRange(probability_max
);
2235 for (i
= 0; i
< num
; i
++) {
2236 if (probs
[i
] > r
) break;
2240 HouseID house
= houses
[i
];
2241 probability_max
-= probs
[i
];
2243 /* remove tested house from the set */
2245 houses
[i
] = houses
[num
];
2246 probs
[i
] = probs
[num
];
2248 const HouseSpec
*hs
= HouseSpec::Get(house
);
2250 if (_loaded_newgrf_features
.has_newhouses
&& !_generating_world
&&
2251 _game_mode
!= GM_EDITOR
&& (hs
->extra_flags
& BUILDING_IS_HISTORICAL
) != 0) {
2255 if (_cur_year
< hs
->min_year
|| _cur_year
> hs
->max_year
) continue;
2257 /* Special houses that there can be only one of. */
2260 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2261 SetBit(oneof
, TOWN_HAS_CHURCH
);
2262 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2263 SetBit(oneof
, TOWN_HAS_STADIUM
);
2266 if (t
->flags
& oneof
) continue;
2268 /* Make sure there is no slope? */
2269 bool noslope
= (hs
->building_flags
& TILE_NOT_SLOPED
) != 0;
2270 if (noslope
&& slope
!= SLOPE_FLAT
) continue;
2272 if (hs
->building_flags
& TILE_SIZE_2x2
) {
2273 if (!CheckTownBuild2x2House(&tile
, t
, maxz
, noslope
)) continue;
2274 } else if (hs
->building_flags
& TILE_SIZE_2x1
) {
2275 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SW
)) continue;
2276 } else if (hs
->building_flags
& TILE_SIZE_1x2
) {
2277 if (!CheckTownBuild2House(&tile
, t
, maxz
, noslope
, DIAGDIR_SE
)) continue;
2279 /* 1x1 house checks are already done */
2282 byte random_bits
= Random();
2284 if (HasBit(hs
->callback_mask
, CBM_HOUSE_ALLOW_CONSTRUCTION
)) {
2285 uint16 callback_res
= GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION
, 0, 0, house
, t
, tile
, true, random_bits
);
2286 if (callback_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_ALLOW_CONSTRUCTION
, callback_res
)) continue;
2289 /* build the house */
2290 t
->cache
.num_houses
++;
2292 /* Special houses that there can be only one of. */
2295 byte construction_counter
= 0;
2296 byte construction_stage
= 0;
2298 if (_generating_world
|| _game_mode
== GM_EDITOR
) {
2299 uint32 r
= Random();
2301 construction_stage
= TOWN_HOUSE_COMPLETED
;
2302 if (Chance16(1, 7)) construction_stage
= GB(r
, 0, 2);
2304 if (construction_stage
== TOWN_HOUSE_COMPLETED
) {
2305 ChangePopulation(t
, hs
->population
);
2307 construction_counter
= GB(r
, 2, 2);
2311 MakeTownHouse(tile
, t
, construction_counter
, construction_stage
, house
, random_bits
);
2312 UpdateTownRadius(t
);
2313 UpdateTownCargoes(t
, tile
);
2322 * Update data structures when a house is removed
2323 * @param tile Tile of the house
2324 * @param t Town owning the house
2325 * @param house House type
2327 static void DoClearTownHouseHelper(TileIndex tile
, Town
*t
, HouseID house
)
2329 assert(IsHouseTile(tile
));
2330 DecreaseBuildingCount(t
, house
);
2331 DoClearSquare(tile
);
2332 DeleteAnimatedTile(tile
);
2334 DeleteNewGRFInspectWindow(GSF_HOUSES
, tile
);
2338 * Determines if a given HouseID is part of a multitile house.
2339 * The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
2341 * @param house Is changed to the HouseID of the north tile of the same house
2342 * @return TileDiff from the tile of the given HouseID to the north tile
2344 TileIndexDiff
GetHouseNorthPart(HouseID
&house
)
2346 if (house
>= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2347 if (HouseSpec::Get(house
- 1)->building_flags
& TILE_SIZE_2x1
) {
2349 return TileDiffXY(-1, 0);
2350 } else if (HouseSpec::Get(house
- 1)->building_flags
& BUILDING_2_TILES_Y
) {
2352 return TileDiffXY(0, -1);
2353 } else if (HouseSpec::Get(house
- 2)->building_flags
& BUILDING_HAS_4_TILES
) {
2355 return TileDiffXY(-1, 0);
2356 } else if (HouseSpec::Get(house
- 3)->building_flags
& BUILDING_HAS_4_TILES
) {
2358 return TileDiffXY(-1, -1);
2364 void ClearTownHouse(Town
*t
, TileIndex tile
)
2366 assert(IsHouseTile(tile
));
2368 HouseID house
= GetHouseType(tile
);
2370 /* need to align the tile to point to the upper left corner of the house */
2371 tile
+= GetHouseNorthPart(house
); // modifies house to the ID of the north tile
2373 const HouseSpec
*hs
= HouseSpec::Get(house
);
2375 /* Remove population from the town if the house is finished. */
2376 if (IsHouseCompleted(tile
)) {
2377 ChangePopulation(t
, -hs
->population
);
2380 t
->cache
.num_houses
--;
2382 /* Clear flags for houses that only may exist once/town. */
2383 if (hs
->building_flags
& BUILDING_IS_CHURCH
) {
2384 ClrBit(t
->flags
, TOWN_HAS_CHURCH
);
2385 } else if (hs
->building_flags
& BUILDING_IS_STADIUM
) {
2386 ClrBit(t
->flags
, TOWN_HAS_STADIUM
);
2389 /* Do the actual clearing of tiles */
2390 uint eflags
= hs
->building_flags
;
2391 DoClearTownHouseHelper(tile
, t
, house
);
2392 if (eflags
& BUILDING_2_TILES_Y
) DoClearTownHouseHelper(tile
+ TileDiffXY(0, 1), t
, ++house
);
2393 if (eflags
& BUILDING_2_TILES_X
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 0), t
, ++house
);
2394 if (eflags
& BUILDING_HAS_4_TILES
) DoClearTownHouseHelper(tile
+ TileDiffXY(1, 1), t
, ++house
);
2396 UpdateTownRadius(t
);
2398 /* Update cargo acceptance. */
2399 UpdateTownCargoes(t
, tile
);
2403 * Rename a town (server-only).
2404 * @param tile unused
2405 * @param flags type of operation
2406 * @param p1 town ID to rename
2408 * @param text the new name or an empty string when resetting to the default
2409 * @return the cost of this operation or an error
2411 CommandCost
CmdRenameTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2413 Town
*t
= Town::GetIfValid(p1
);
2414 if (t
== NULL
) return CMD_ERROR
;
2416 bool reset
= StrEmpty(text
);
2419 if (Utf8StringLength(text
) >= MAX_LENGTH_TOWN_NAME_CHARS
) return CMD_ERROR
;
2420 if (!IsUniqueTownName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
2423 if (flags
& DC_EXEC
) {
2425 t
->name
= reset
? NULL
: strdup(text
);
2427 t
->UpdateVirtCoord();
2428 InvalidateWindowData(WC_TOWN_DIRECTORY
, 0, 1);
2429 UpdateAllStationVirtCoords();
2431 return CommandCost();
2435 * Determines the first cargo with a certain town effect
2436 * @param effect Town effect of interest
2437 * @return first active cargo slot with that effect
2439 const CargoSpec
*FindFirstCargoWithTownEffect(TownEffect effect
)
2441 const CargoSpec
*cs
;
2442 FOR_ALL_CARGOSPECS(cs
) {
2443 if (cs
->town_effect
== effect
) return cs
;
2448 static void UpdateTownGrowRate(Town
*t
);
2451 * Change the cargo goal of a town.
2452 * @param tile Unused.
2453 * @param flags Type of operation.
2454 * @param p1 various bitstuffed elements
2455 * - p1 = (bit 0 - 15) - Town ID to cargo game of.
2456 * - p1 = (bit 16 - 23) - TownEffect to change the game of.
2457 * @param p2 The new goal value.
2458 * @param text Unused.
2459 * @return Empty cost or an error.
2461 CommandCost
CmdTownCargoGoal(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2463 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2465 TownEffect te
= (TownEffect
)GB(p1
, 16, 8);
2466 if (te
< TE_BEGIN
|| te
>= TE_END
) return CMD_ERROR
;
2468 uint16 index
= GB(p1
, 0, 16);
2469 Town
*t
= Town::GetIfValid(index
);
2470 if (t
== NULL
) return CMD_ERROR
;
2472 /* Validate if there is a cargo which is the requested TownEffect */
2473 const CargoSpec
*cargo
= FindFirstCargoWithTownEffect(te
);
2474 if (cargo
== NULL
) return CMD_ERROR
;
2476 if (flags
& DC_EXEC
) {
2478 UpdateTownGrowRate(t
);
2479 InvalidateWindowData(WC_TOWN_VIEW
, index
);
2482 return CommandCost();
2486 * Set a custom text in the Town window.
2487 * @param tile Unused.
2488 * @param flags Type of operation.
2489 * @param p1 Town ID to change the text of.
2491 * @param text The new text (empty to remove the text).
2492 * @return Empty cost or an error.
2494 CommandCost
CmdTownSetText(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2496 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2497 Town
*t
= Town::GetIfValid(p1
);
2498 if (t
== NULL
) return CMD_ERROR
;
2500 if (flags
& DC_EXEC
) {
2502 t
->text
= StrEmpty(text
) ? NULL
: strdup(text
);
2503 InvalidateWindowData(WC_TOWN_VIEW
, p1
);
2506 return CommandCost();
2510 * Change the growth rate of the town.
2511 * @param tile Unused.
2512 * @param flags Type of operation.
2513 * @param p1 Town ID to cargo game of.
2514 * @param p2 Amount of days between growth, or TOWN_GROW_RATE_CUSTOM_NONE, or 0 to reset custom growth rate.
2515 * @param text Unused.
2516 * @return Empty cost or an error.
2518 CommandCost
CmdTownGrowthRate(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2520 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2521 if ((p2
& TOWN_GROW_RATE_CUSTOM
) != 0 && p2
!= TOWN_GROW_RATE_CUSTOM_NONE
) return CMD_ERROR
;
2522 if (GB(p2
, 16, 16) != 0) return CMD_ERROR
;
2524 Town
*t
= Town::GetIfValid(p1
);
2525 if (t
== NULL
) return CMD_ERROR
;
2527 if (flags
& DC_EXEC
) {
2529 /* Clear TOWN_GROW_RATE_CUSTOM, UpdateTownGrowRate will determine a proper value */
2532 uint old_rate
= t
->growth_rate
& ~TOWN_GROW_RATE_CUSTOM
;
2533 if (t
->grow_counter
>= old_rate
) {
2534 /* This also catches old_rate == 0 */
2535 t
->grow_counter
= p2
;
2537 /* Scale grow_counter, so half finished houses stay half finished */
2538 t
->grow_counter
= t
->grow_counter
* p2
/ old_rate
;
2540 t
->growth_rate
= p2
| TOWN_GROW_RATE_CUSTOM
;
2542 UpdateTownGrowRate(t
);
2543 InvalidateWindowData(WC_TOWN_VIEW
, p1
);
2546 return CommandCost();
2550 * Expand a town (scenario editor only).
2551 * @param tile Unused.
2552 * @param flags Type of operation.
2553 * @param p1 Town ID to expand.
2554 * @param p2 Amount to grow, or 0 to grow a random size up to the current amount of houses.
2555 * @param text Unused.
2556 * @return Empty cost or an error.
2558 CommandCost
CmdExpandTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2560 if (_game_mode
!= GM_EDITOR
&& _current_company
!= OWNER_DEITY
) return CMD_ERROR
;
2561 Town
*t
= Town::GetIfValid(p1
);
2562 if (t
== NULL
) return CMD_ERROR
;
2564 if (flags
& DC_EXEC
) {
2565 /* The more houses, the faster we grow */
2567 uint amount
= RandomRange(ClampToU16(t
->cache
.num_houses
/ 10)) + 3;
2568 t
->cache
.num_houses
+= amount
;
2569 UpdateTownRadius(t
);
2571 uint n
= amount
* 10;
2572 do GrowTown(t
); while (--n
);
2574 t
->cache
.num_houses
-= amount
;
2576 for (; p2
> 0; p2
--) {
2577 /* Try several times to grow, as we are really suppose to grow */
2578 for (uint i
= 0; i
< 25; i
++) if (GrowTown(t
)) break;
2581 UpdateTownRadius(t
);
2583 UpdateTownMaxPass(t
);
2586 return CommandCost();
2590 * Delete a town (scenario editor or worldgen only).
2591 * @param tile Unused.
2592 * @param flags Type of operation.
2593 * @param p1 Town ID to delete.
2595 * @param text Unused.
2596 * @return Empty cost or an error.
2598 CommandCost
CmdDeleteTown(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2600 if (_game_mode
!= GM_EDITOR
&& !_generating_world
) return CMD_ERROR
;
2601 Town
*t
= Town::GetIfValid(p1
);
2602 if (t
== NULL
) return CMD_ERROR
;
2604 /* Stations refer to towns. */
2606 FOR_ALL_STATIONS(st
) {
2607 if (st
->town
== t
) {
2608 /* Non-oil rig stations are always a problem. */
2609 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->airport
.type
!= AT_OILRIG
) return CMD_ERROR
;
2610 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2611 CommandCost ret
= DoCommand(st
->airport
.tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2612 if (ret
.Failed()) return ret
;
2616 /* Depots refer to towns. */
2619 if (d
->town
== t
) return CMD_ERROR
;
2622 /* Check all tiles for town ownership. */
2623 for (TileIndex tile
= 0; tile
< MapSize(); ++tile
) {
2624 bool try_clear
= false;
2625 if (IsHouseTile(tile
)) {
2626 try_clear
= GetTownIndex(tile
) == t
->index
;
2627 } else if (IsIndustryTile(tile
)) {
2628 try_clear
= Industry::GetByTile(tile
)->town
== t
;
2630 switch (GetTileType(tile
)) {
2632 if (IsTunnelTile(tile
)) {
2633 try_clear
= IsTileOwner(tile
, OWNER_TOWN
) && ClosestTownFromTile(tile
, UINT_MAX
) == t
;
2636 if (!IsLevelCrossingTile(tile
)) break;
2639 try_clear
= HasTownOwnedRoad(tile
) && GetTownIndex(tile
) == t
->index
;
2643 if (Town::GetNumItems() == 1) {
2644 /* No towns will be left, remove it! */
2647 Object
*o
= Object::GetByTile(tile
);
2649 if (o
->type
== OBJECT_STATUE
) {
2650 /* Statue... always remove. */
2653 /* Tell to find a new town. */
2654 if (flags
& DC_EXEC
) o
->town
= NULL
;
2665 CommandCost ret
= DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2666 if (ret
.Failed()) return ret
;
2670 /* The town destructor will delete the other things related to the town. */
2671 if (flags
& DC_EXEC
) delete t
;
2673 return CommandCost();
2677 * Factor in the cost of each town action.
2680 const byte _town_action_costs
[TACT_COUNT
] = {
2681 2, 4, 9, 35, 48, 53, 117, 175
2684 static CommandCost
TownActionAdvertiseSmall(Town
*t
, DoCommandFlag flags
)
2686 if (flags
& DC_EXEC
) {
2687 ModifyStationRatingAround(t
->xy
, _current_company
, 0x40, 10);
2689 return CommandCost();
2692 static CommandCost
TownActionAdvertiseMedium(Town
*t
, DoCommandFlag flags
)
2694 if (flags
& DC_EXEC
) {
2695 ModifyStationRatingAround(t
->xy
, _current_company
, 0x70, 15);
2697 return CommandCost();
2700 static CommandCost
TownActionAdvertiseLarge(Town
*t
, DoCommandFlag flags
)
2702 if (flags
& DC_EXEC
) {
2703 ModifyStationRatingAround(t
->xy
, _current_company
, 0xA0, 20);
2705 return CommandCost();
2708 static CommandCost
TownActionRoadRebuild(Town
*t
, DoCommandFlag flags
)
2710 /* Check if the company is allowed to fund new roads. */
2711 if (!_settings_game
.economy
.fund_roads
) return CMD_ERROR
;
2713 if (flags
& DC_EXEC
) {
2714 t
->road_build_months
= 6;
2716 char company_name
[MAX_LENGTH_COMPANY_NAME_CHARS
* MAX_CHAR_LENGTH
];
2717 SetDParam(0, _current_company
);
2718 GetString(company_name
, STR_COMPANY_NAME
, lastof(company_name
));
2720 char *cn
= strdup(company_name
);
2721 SetDParam(0, t
->index
);
2722 SetDParamStr(1, cn
);
2724 AddNewsItem(STR_NEWS_ROAD_REBUILDING
, NT_GENERAL
, NF_NORMAL
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
, cn
);
2725 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
2726 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
2728 return CommandCost();
2732 * Check whether the land can be cleared.
2733 * @param tile Tile to check.
2734 * @return The tile can be cleared.
2736 static bool TryClearTile(TileIndex tile
)
2738 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
2739 CommandCost r
= DoCommand(tile
, 0, 0, DC_NONE
, CMD_LANDSCAPE_CLEAR
);
2740 cur_company
.Restore();
2741 return r
.Succeeded();
2744 /** Structure for storing data while searching the best place to build a statue. */
2745 struct StatueBuildSearchData
{
2746 TileIndex best_position
; ///< Best position found so far.
2747 int tile_count
; ///< Number of tiles tried.
2749 StatueBuildSearchData(TileIndex best_pos
, int count
) : best_position(best_pos
), tile_count(count
) { }
2753 * Search callback function for #TownActionBuildStatue.
2754 * @param tile Tile on which to perform the search.
2755 * @param user_data Reference to the statue search data.
2756 * @return Result of the test.
2758 static bool SearchTileForStatue(TileIndex tile
, void *user_data
)
2760 static const int STATUE_NUMBER_INNER_TILES
= 25; // Number of tiles int the center of the city, where we try to protect houses.
2762 StatueBuildSearchData
*statue_data
= (StatueBuildSearchData
*)user_data
;
2763 statue_data
->tile_count
++;
2765 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2766 if (IsSteepSlope(GetTileSlope(tile
))) return false;
2767 /* Don't build statues under bridges. */
2768 if (HasBridgeAbove(tile
)) return false;
2770 /* A clear-able open space is always preferred. */
2771 if (IsGroundTile(tile
) && TryClearTile(tile
)) {
2772 statue_data
->best_position
= tile
;
2776 bool house
= IsHouseTile(tile
);
2778 /* Searching inside the inner circle. */
2779 if (statue_data
->tile_count
<= STATUE_NUMBER_INNER_TILES
) {
2780 /* Save first house in inner circle. */
2781 if (house
&& statue_data
->best_position
== INVALID_TILE
&& TryClearTile(tile
)) {
2782 statue_data
->best_position
= tile
;
2785 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2786 return statue_data
->tile_count
== STATUE_NUMBER_INNER_TILES
&& statue_data
->best_position
!= INVALID_TILE
;
2789 /* Searching outside the circle, just pick the first possible spot. */
2790 statue_data
->best_position
= tile
; // Is optimistic, the condition below must also hold.
2791 return house
&& TryClearTile(tile
);
2795 * Perform a 9x9 tiles circular search from the center of the town
2796 * in order to find a free tile to place a statue
2797 * @param t town to search in
2798 * @param flags Used to check if the statue must be built or not.
2799 * @return Empty cost or an error.
2801 static CommandCost
TownActionBuildStatue(Town
*t
, DoCommandFlag flags
)
2803 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS
);
2805 TileIndex tile
= t
->xy
;
2806 StatueBuildSearchData
statue_data(INVALID_TILE
, 0);
2807 if (!CircularTileSearch(&tile
, 9, SearchTileForStatue
, &statue_data
)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE
);
2809 if (flags
& DC_EXEC
) {
2810 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
2811 DoCommand(statue_data
.best_position
, 0, 0, DC_EXEC
, CMD_LANDSCAPE_CLEAR
);
2812 cur_company
.Restore();
2813 BuildObject(OBJECT_STATUE
, statue_data
.best_position
, _current_company
, t
);
2814 SetBit(t
->statues
, _current_company
); // Once found and built, "inform" the Town.
2815 MarkTileDirtyByTile(statue_data
.best_position
);
2817 return CommandCost();
2820 static CommandCost
TownActionFundBuildings(Town
*t
, DoCommandFlag flags
)
2822 /* Check if it's allowed to buy the rights */
2823 if (!_settings_game
.economy
.fund_buildings
) return CMD_ERROR
;
2825 if (flags
& DC_EXEC
) {
2826 /* Build next tick */
2827 t
->grow_counter
= 1;
2828 /* And grow for 3 months */
2829 t
->fund_buildings_months
= 3;
2831 /* Enable growth (also checking GameScript's opinion) */
2832 UpdateTownGrowRate(t
);
2834 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
2836 return CommandCost();
2839 static CommandCost
TownActionBuyRights(Town
*t
, DoCommandFlag flags
)
2841 /* Check if it's allowed to buy the rights */
2842 if (!_settings_game
.economy
.exclusive_rights
) return CMD_ERROR
;
2844 if (flags
& DC_EXEC
) {
2845 t
->exclusive_counter
= 12;
2846 t
->exclusivity
= _current_company
;
2848 ModifyStationRatingAround(t
->xy
, _current_company
, 130, 17);
2850 SetWindowClassesDirty(WC_STATION_VIEW
);
2852 /* Spawn news message */
2853 CompanyNewsInformation
*cni
= MallocT
<CompanyNewsInformation
>(1);
2854 cni
->FillData(Company::Get(_current_company
));
2855 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE
);
2856 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION
);
2857 SetDParam(2, t
->index
);
2858 SetDParamStr(3, cni
->company_name
);
2859 AddNewsItem(STR_MESSAGE_NEWS_FORMAT
, NT_GENERAL
, NF_COMPANY
, NR_TOWN
, t
->index
, NR_NONE
, UINT32_MAX
, cni
);
2860 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
2861 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID
)(Owner
)_current_company
, t
->index
));
2863 return CommandCost();
2866 static CommandCost
TownActionBribe(Town
*t
, DoCommandFlag flags
)
2868 if (flags
& DC_EXEC
) {
2869 if (Chance16(1, 14)) {
2870 /* set as unwanted for 6 months */
2871 t
->unwanted
[_current_company
] = 6;
2873 /* set all close by station ratings to 0 */
2875 FOR_ALL_STATIONS(st
) {
2876 if (st
->town
== t
&& st
->owner
== _current_company
) {
2877 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) st
->goods
[i
].rating
= 0;
2881 /* only show error message to the executing player. All errors are handled command.c
2882 * but this is special, because it can only 'fail' on a DC_EXEC */
2883 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED
, INVALID_STRING_ID
, WL_INFO
);
2885 /* decrease by a lot!
2886 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
2887 * be independent of any cheat settings
2889 if (t
->ratings
[_current_company
] > RATING_BRIBE_DOWN_TO
) {
2890 t
->ratings
[_current_company
] = RATING_BRIBE_DOWN_TO
;
2891 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
2894 ChangeTownRating(t
, RATING_BRIBE_UP_STEP
, RATING_BRIBE_MAXIMUM
, DC_EXEC
);
2897 return CommandCost();
2900 typedef CommandCost
TownActionProc(Town
*t
, DoCommandFlag flags
);
2901 static TownActionProc
* const _town_action_proc
[] = {
2902 TownActionAdvertiseSmall
,
2903 TownActionAdvertiseMedium
,
2904 TownActionAdvertiseLarge
,
2905 TownActionRoadRebuild
,
2906 TownActionBuildStatue
,
2907 TownActionFundBuildings
,
2908 TownActionBuyRights
,
2913 * Get a list of available actions to do at a town.
2914 * @param nump if not NULL add put the number of available actions in it
2915 * @param cid the company that is querying the town
2916 * @param t the town that is queried
2917 * @return bitmasked value of enabled actions
2919 uint
GetMaskOfTownActions(int *nump
, CompanyID cid
, const Town
*t
)
2922 TownActions buttons
= TACT_NONE
;
2924 /* Spectators and unwanted have no options */
2925 if (cid
!= COMPANY_SPECTATOR
&& !(_settings_game
.economy
.bribe
&& t
->unwanted
[cid
])) {
2927 /* Things worth more than this are not shown */
2928 Money avail
= Company::Get(cid
)->money
+ _price
[PR_STATION_VALUE
] * 200;
2930 /* Check the action bits for validity and
2931 * if they are valid add them */
2932 for (uint i
= 0; i
!= lengthof(_town_action_costs
); i
++) {
2933 const TownActions cur
= (TownActions
)(1 << i
);
2935 /* Is the company not able to bribe ? */
2936 if (cur
== TACT_BRIBE
&& (!_settings_game
.economy
.bribe
|| t
->ratings
[cid
] >= RATING_BRIBE_MAXIMUM
)) continue;
2938 /* Is the company not able to buy exclusive rights ? */
2939 if (cur
== TACT_BUY_RIGHTS
&& !_settings_game
.economy
.exclusive_rights
) continue;
2941 /* Is the company not able to fund buildings ? */
2942 if (cur
== TACT_FUND_BUILDINGS
&& !_settings_game
.economy
.fund_buildings
) continue;
2944 /* Is the company not able to fund local road reconstruction? */
2945 if (cur
== TACT_ROAD_REBUILD
&& !_settings_game
.economy
.fund_roads
) continue;
2947 /* Is the company not able to build a statue ? */
2948 if (cur
== TACT_BUILD_STATUE
&& HasBit(t
->statues
, cid
)) continue;
2950 if (avail
>= _town_action_costs
[i
] * _price
[PR_TOWN_ACTION
] >> 8) {
2957 if (nump
!= NULL
) *nump
= num
;
2963 * This performs an action such as advertising, building a statue, funding buildings,
2964 * but also bribing the town-council
2965 * @param tile unused
2966 * @param flags type of operation
2967 * @param p1 town to do the action at
2968 * @param p2 action to perform, @see _town_action_proc for the list of available actions
2969 * @param text unused
2970 * @return the cost of this operation or an error
2972 CommandCost
CmdDoTownAction(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2974 Town
*t
= Town::GetIfValid(p1
);
2975 if (t
== NULL
|| p2
>= lengthof(_town_action_proc
)) return CMD_ERROR
;
2977 if (!HasBit(GetMaskOfTownActions(NULL
, _current_company
, t
), p2
)) return CMD_ERROR
;
2979 CommandCost
cost(EXPENSES_OTHER
, _price
[PR_TOWN_ACTION
] * _town_action_costs
[p2
] >> 8);
2981 CommandCost ret
= _town_action_proc
[p2
](t
, flags
);
2982 if (ret
.Failed()) return ret
;
2984 if (flags
& DC_EXEC
) {
2985 SetWindowDirty(WC_TOWN_AUTHORITY
, p1
);
2991 static void UpdateTownRating(Town
*t
)
2993 /* Increase company ratings if they're low */
2995 FOR_ALL_COMPANIES(c
) {
2996 if (t
->ratings
[c
->index
] < RATING_GROWTH_MAXIMUM
) {
2997 t
->ratings
[c
->index
] = min((int)RATING_GROWTH_MAXIMUM
, t
->ratings
[c
->index
] + RATING_GROWTH_UP_STEP
);
3002 FOR_ALL_STATIONS(st
) {
3003 if (DistanceSquare(st
->xy
, t
->xy
) <= t
->cache
.squared_town_zone_radius
[0]) {
3004 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3005 if (Company::IsValidID(st
->owner
)) {
3006 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_UP_STEP
;
3007 t
->ratings
[st
->owner
] = min(new_rating
, INT16_MAX
); // do not let it overflow
3010 if (Company::IsValidID(st
->owner
)) {
3011 int new_rating
= t
->ratings
[st
->owner
] + RATING_STATION_DOWN_STEP
;
3012 t
->ratings
[st
->owner
] = max(new_rating
, INT16_MIN
);
3018 /* clamp all ratings to valid values */
3019 for (uint i
= 0; i
< MAX_COMPANIES
; i
++) {
3020 t
->ratings
[i
] = Clamp(t
->ratings
[i
], RATING_MINIMUM
, RATING_MAXIMUM
);
3023 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3026 static void UpdateTownGrowRate(Town
*t
)
3028 ClrBit(t
->flags
, TOWN_IS_GROWING
);
3029 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3031 if (_settings_game
.economy
.town_growth_rate
== 0 && t
->fund_buildings_months
== 0) return;
3033 if (t
->fund_buildings_months
== 0) {
3034 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3035 for (int i
= TE_BEGIN
; i
< TE_END
; i
++) {
3036 switch (t
->goal
[i
]) {
3037 case TOWN_GROWTH_WINTER
:
3038 if (TileHeight(t
->xy
) >= GetSnowLine() && t
->received
[i
].old_act
== 0 && t
->cache
.population
> 90) return;
3040 case TOWN_GROWTH_DESERT
:
3041 if (GetTropicZone(t
->xy
) == TROPICZONE_DESERT
&& t
->received
[i
].old_act
== 0 && t
->cache
.population
> 60) return;
3044 if (t
->goal
[i
] > t
->received
[i
].old_act
) return;
3050 if ((t
->growth_rate
& TOWN_GROW_RATE_CUSTOM
) != 0) {
3051 if (t
->growth_rate
!= TOWN_GROW_RATE_CUSTOM_NONE
) SetBit(t
->flags
, TOWN_IS_GROWING
);
3052 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3057 * Towns are processed every TOWN_GROWTH_TICKS ticks, and this is the
3058 * number of times towns are processed before a new building is built.
3060 static const uint16 _grow_count_values
[2][6] = {
3061 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3062 { 320, 420, 300, 220, 160, 100 } // Normal values
3068 FOR_ALL_STATIONS(st
) {
3069 if (DistanceSquare(st
->xy
, t
->xy
) <= t
->cache
.squared_town_zone_radius
[0]) {
3070 if (st
->time_since_load
<= 20 || st
->time_since_unload
<= 20) {
3078 if (t
->fund_buildings_months
!= 0) {
3079 m
= _grow_count_values
[0][min(n
, 5)];
3081 m
= _grow_count_values
[1][min(n
, 5)];
3082 if (n
== 0 && !Chance16(1, 12)) return;
3085 /* Use the normal growth rate values if new buildings have been funded in
3086 * this town and the growth rate is set to none. */
3087 uint growth_multiplier
= _settings_game
.economy
.town_growth_rate
!= 0 ? _settings_game
.economy
.town_growth_rate
- 1 : 1;
3089 m
>>= growth_multiplier
;
3090 if (t
->larger_town
) m
/= 2;
3092 t
->growth_rate
= m
/ (t
->cache
.num_houses
/ 50 + 1);
3093 if (m
<= t
->grow_counter
) {
3094 t
->grow_counter
= m
;
3097 SetBit(t
->flags
, TOWN_IS_GROWING
);
3098 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3101 static void UpdateTownAmounts(Town
*t
)
3103 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) t
->supplied
[i
].NewMonth();
3104 for (int i
= TE_BEGIN
; i
< TE_END
; i
++) t
->received
[i
].NewMonth();
3105 if (t
->fund_buildings_months
!= 0) t
->fund_buildings_months
--;
3107 SetWindowDirty(WC_TOWN_VIEW
, t
->index
);
3110 static void UpdateTownUnwanted(Town
*t
)
3114 FOR_ALL_COMPANIES(c
) {
3115 if (t
->unwanted
[c
->index
] > 0) t
->unwanted
[c
->index
]--;
3120 * Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
3121 * @param tile The tile where the station shall be constructed.
3122 * @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
3123 * @return Succeeded or failed command.
3125 CommandCost
CheckIfAuthorityAllowsNewStation(TileIndex tile
, DoCommandFlag flags
)
3127 if (!Company::IsValidID(_current_company
) || (flags
& DC_NO_TEST_TOWN_RATING
)) return CommandCost();
3129 Town
*t
= ClosestTownFromTile(tile
, _settings_game
.economy
.dist_local_authority
);
3130 if (t
== NULL
) return CommandCost();
3132 if (t
->ratings
[_current_company
] > RATING_VERYPOOR
) return CommandCost();
3134 SetDParam(0, t
->index
);
3135 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
3139 * Return the town closest to the given tile within \a threshold.
3140 * @param tile Starting point of the search.
3141 * @param threshold Biggest allowed distance to the town.
3142 * @return Closest town to \a tile within \a threshold, or \c NULL if there is no such town.
3144 * @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
3146 Town
*CalcClosestTownFromTile(TileIndex tile
, uint threshold
)
3149 uint best
= threshold
;
3150 Town
*best_town
= NULL
;
3153 uint dist
= DistanceManhattan(tile
, t
->xy
);
3164 * Return the town closest (in distance or ownership) to a given tile, within a given threshold.
3165 * @param tile Starting point of the search.
3166 * @param threshold Biggest allowed distance to the town.
3167 * @return Closest town to \a tile within \a threshold, or \c NULL if there is no such town.
3169 * @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
3171 Town
*ClosestTownFromTile(TileIndex tile
, uint threshold
)
3173 if (IsHouseTile(tile
)) {
3174 return Town::GetByTile(tile
);
3175 } else if (IsRoadTile(tile
) || IsLevelCrossingTile(tile
)) {
3176 if (HasTownOwnedRoad(tile
)) return Town::GetByTile(tile
);
3178 TownID tid
= GetTownIndex(tile
);
3180 if (tid
== (TownID
)INVALID_TOWN
) {
3181 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3182 if (_generating_world
) return CalcClosestTownFromTile(tile
, threshold
);
3183 assert(Town::GetNumItems() == 0);
3187 assert(Town::IsValidID(tid
));
3188 Town
*town
= Town::Get(tid
);
3190 if (DistanceManhattan(tile
, town
->xy
) >= threshold
) town
= NULL
;
3195 return CalcClosestTownFromTile(tile
, threshold
);
3198 static bool _town_rating_test
= false; ///< If \c true, town rating is in test-mode.
3199 static SmallMap
<const Town
*, int, 4> _town_test_ratings
; ///< Map of towns to modified ratings, while in town rating test-mode.
3202 * Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
3203 * The function is safe to use in nested calls.
3204 * @param mode Test mode switch (\c true means go to test-mode, \c false means leave test-mode).
3206 void SetTownRatingTestMode(bool mode
)
3208 static int ref_count
= 0; // Number of times test-mode is switched on.
3210 if (ref_count
== 0) {
3211 _town_test_ratings
.Clear();
3215 assert(ref_count
> 0);
3218 _town_rating_test
= !(ref_count
== 0);
3222 * Get the rating of a town for the #_current_company.
3223 * @param t Town to get the rating from.
3224 * @return Rating of the current company in the given town.
3226 static int GetRating(const Town
*t
)
3228 if (_town_rating_test
) {
3229 SmallMap
<const Town
*, int>::iterator it
= _town_test_ratings
.Find(t
);
3230 if (it
!= _town_test_ratings
.End()) {
3234 return t
->ratings
[_current_company
];
3238 * Changes town rating of the current company
3239 * @param t Town to affect
3240 * @param add Value to add
3241 * @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be achievable with this change.
3242 * @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
3244 void ChangeTownRating(Town
*t
, int add
, int max
, DoCommandFlag flags
)
3246 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3247 if (t
== NULL
|| (flags
& DC_NO_MODIFY_TOWN_RATING
) ||
3248 !Company::IsValidID(_current_company
) ||
3249 (_cheats
.magic_bulldozer
.value
&& add
< 0)) {
3253 int rating
= GetRating(t
);
3257 if (rating
< max
) rating
= max
;
3262 if (rating
> max
) rating
= max
;
3265 if (_town_rating_test
) {
3266 _town_test_ratings
[t
] = rating
;
3268 SetBit(t
->have_ratings
, _current_company
);
3269 t
->ratings
[_current_company
] = rating
;
3270 SetWindowDirty(WC_TOWN_AUTHORITY
, t
->index
);
3275 * Does the town authority allow the (destructive) action of the current company?
3276 * @param flags Checking flags of the command.
3277 * @param t Town that must allow the company action.
3278 * @param type Type of action that is wanted.
3279 * @return A succeeded command if the action is allowed, a failed command if it is not allowed.
3281 CommandCost
CheckforTownRating(DoCommandFlag flags
, Town
*t
, TownRatingCheckType type
)
3283 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3284 if (t
== NULL
|| !Company::IsValidID(_current_company
) ||
3285 _cheats
.magic_bulldozer
.value
|| (flags
& DC_NO_TEST_TOWN_RATING
)) {
3286 return CommandCost();
3289 /* minimum rating needed to be allowed to remove stuff */
3290 static const int needed_rating
[][TOWN_RATING_CHECK_TYPE_COUNT
] = {
3291 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3292 { RATING_ROAD_NEEDED_PERMISSIVE
, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
}, // Permissive
3293 { RATING_ROAD_NEEDED_NEUTRAL
, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
}, // Neutral
3294 { RATING_ROAD_NEEDED_HOSTILE
, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
}, // Hostile
3297 /* check if you're allowed to remove the road/bridge/tunnel
3298 * owned by a town no removal if rating is lower than ... depends now on
3299 * difficulty setting. Minimum town rating selected by difficulty level
3301 int needed
= needed_rating
[_settings_game
.difficulty
.town_council_tolerance
][type
];
3303 if (GetRating(t
) < needed
) {
3304 SetDParam(0, t
->index
);
3305 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS
);
3308 return CommandCost();
3311 void TownsMonthlyLoop()
3316 if (t
->road_build_months
!= 0) t
->road_build_months
--;
3318 if (t
->exclusive_counter
!= 0) {
3319 if (--t
->exclusive_counter
== 0) t
->exclusivity
= INVALID_COMPANY
;
3322 UpdateTownAmounts(t
);
3323 UpdateTownRating(t
);
3324 UpdateTownGrowRate(t
);
3325 UpdateTownUnwanted(t
);
3326 UpdateTownCargoes(t
);
3329 UpdateTownCargoBitmap();
3332 void TownsYearlyLoop()
3334 /* Increment house ages */
3335 for (TileIndex t
= 0; t
< MapSize(); t
++) {
3336 if (!IsHouseTile(t
)) continue;
3337 IncrementHouseAge(t
);
3341 static CommandCost
TerraformTile_Town(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
3343 if (AutoslopeEnabled()) {
3344 HouseID house
= GetHouseType(tile
);
3345 GetHouseNorthPart(house
); // modifies house to the ID of the north tile
3346 const HouseSpec
*hs
= HouseSpec::Get(house
);
3348 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3349 if (((hs
->building_flags
& TILE_NOT_SLOPED
) == 0) && !IsSteepSlope(tileh_new
) &&
3350 (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
))) {
3351 bool allow_terraform
= true;
3353 /* Call the autosloping callback per tile, not for the whole building at once. */
3354 house
= GetHouseType(tile
);
3355 hs
= HouseSpec::Get(house
);
3356 if (HasBit(hs
->callback_mask
, CBM_HOUSE_AUTOSLOPE
)) {
3357 /* If the callback fails, allow autoslope. */
3358 uint16 res
= GetHouseCallback(CBID_HOUSE_AUTOSLOPE
, 0, 0, house
, Town::GetByTile(tile
), tile
);
3359 if (res
!= CALLBACK_FAILED
&& ConvertBooleanCallback(hs
->grf_prop
.grffile
, CBID_HOUSE_AUTOSLOPE
, res
)) allow_terraform
= false;
3362 if (allow_terraform
) return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3366 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
3369 /** Tile callback functions for a town */
3370 extern const TileTypeProcs _tile_type_town_procs
= {
3371 DrawTile_Town
, // draw_tile_proc
3372 GetSlopePixelZ_Town
, // get_slope_z_proc
3373 ClearTile_Town
, // clear_tile_proc
3374 AddAcceptedCargo_Town
, // add_accepted_cargo_proc
3375 GetTileDesc_Town
, // get_tile_desc_proc
3376 NULL
, // get_tile_railway_status_proc
3377 NULL
, // get_tile_road_status_proc
3378 NULL
, // get_tile_waterway_status_proc
3379 NULL
, // click_tile_proc
3380 AnimateTile_Town
, // animate_tile_proc
3381 TileLoop_Town
, // tile_loop_proc
3382 ChangeTileOwner_Town
, // change_tile_owner_proc
3383 AddProducedCargo_Town
, // add_produced_cargo_proc
3384 GetFoundation_Town
, // get_foundation_proc
3385 TerraformTile_Town
, // terraform_tile_proc
3389 HouseSpec _house_specs
[NUM_HOUSES
];
3393 memset(&_house_specs
, 0, sizeof(_house_specs
));
3394 memcpy(&_house_specs
, &_original_house_specs
, sizeof(_original_house_specs
));
3396 /* Reset any overrides that have been set. */
3397 _house_mngr
.ResetOverride();