Chunnel: Adjust z position of vehicles in chunnels to go "under" the water.
[openttd-joker.git] / src / town_cmd.cpp
blob82eefbc7d9a30135a76be7cdcf58afb8781e2ff3
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file town_cmd.cpp Handling of town tiles. */
12 #include "stdafx.h"
13 #include "road_internal.h" /* Cleaning up road bits */
14 #include "road_cmd.h"
15 #include "landscape.h"
16 #include "viewport_func.h"
17 #include "cmd_helper.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "company_base.h"
22 #include "news_func.h"
23 #include "error.h"
24 #include "object.h"
25 #include "genworld.h"
26 #include "newgrf_debug.h"
27 #include "newgrf_house.h"
28 #include "newgrf_text.h"
29 #include "autoslope.h"
30 #include "tunnelbridge_map.h"
31 #include "strings_func.h"
32 #include "window_func.h"
33 #include "string_func.h"
34 #include "newgrf_cargo.h"
35 #include "cheat_type.h"
36 #include "animated_tile_func.h"
37 #include "date_func.h"
38 #include "subsidy_func.h"
39 #include "core/pool_func.hpp"
40 #include "town.h"
41 #include "townname_func.h"
42 #include "core/random_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "depot_base.h"
45 #include "object_map.h"
46 #include "object_base.h"
47 #include "ai/ai.hpp"
48 #include "game/game.hpp"
50 #include "table/strings.h"
51 #include "table/town_land.h"
53 #include "safeguards.h"
55 TownID _new_town_id;
56 uint32 _town_cargoes_accepted; ///< Bitmap of all cargoes accepted by houses.
58 /* Initialize the town-pool */
59 TownPool _town_pool("Town");
60 INSTANTIATE_POOL_METHODS(Town)
62 Town::~Town()
64 free(this->name);
65 free(this->text);
67 if (CleaningPool()) return;
69 /* Delete town authority window
70 * and remove from list of sorted towns */
71 DeleteWindowById(WC_TOWN_VIEW, this->index);
73 /* Check no industry is related to us. */
74 const Industry *i;
75 FOR_ALL_INDUSTRIES(i) assert(i->town != this);
77 /* ... and no object is related to us. */
78 const Object *o;
79 FOR_ALL_OBJECTS(o) assert(o->town != this);
81 /* Check no tile is related to us. */
82 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
83 switch (GetTileType(tile)) {
84 case MP_HOUSE:
85 assert(GetTownIndex(tile) != this->index);
86 break;
88 case MP_ROAD:
89 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
90 break;
92 case MP_TUNNELBRIDGE:
93 assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
94 break;
96 default:
97 break;
101 /* Clear the persistent storage list. */
102 this->psa_list.clear();
104 DeleteSubsidyWith(ST_TOWN, this->index);
105 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
106 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
107 MarkWholeScreenDirty();
112 * Invalidating of the "nearest town cache" has to be done
113 * after removing item from the pool.
114 * @param index index of deleted item
116 void Town::PostDestructor(size_t index)
118 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
119 UpdateNearestTownForRoadTiles(false);
121 /* Give objects a new home! */
122 Object *o;
123 FOR_ALL_OBJECTS(o) {
124 if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
129 * Assigns town layout. If Random, generates one based on TileHash.
131 void Town::InitializeLayout(TownLayout layout)
133 if (layout != TL_RANDOM) {
134 this->layout = layout;
135 return;
138 this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
142 * Return a random valid town.
143 * @return random town, NULL if there are no towns
145 /* static */ Town *Town::GetRandom()
147 if (Town::GetNumItems() == 0) return NULL;
148 int num = RandomRange((uint16)Town::GetNumItems());
149 size_t index = MAX_UVALUE(size_t);
151 while (num >= 0) {
152 num--;
153 index++;
155 /* Make sure we have a valid town */
156 while (!Town::IsValidID(index)) {
157 index++;
158 assert(index < Town::GetPoolSize());
162 return Town::Get(index);
166 * Updates the town label of the town after changes in rating. The colour scheme is:
167 * Red: Appalling and Very poor ratings.
168 * Orange: Poor and mediocre ratings.
169 * Yellow: Good rating.
170 * White: Very good rating (standard).
171 * Green: Excellent and outstanding ratings.
173 void Town::UpdateLabel()
175 if (!(_game_mode == GM_EDITOR) && (_local_company < MAX_COMPANIES)) {
176 int r = this->ratings[_local_company];
177 (this->town_label = 0, r <= RATING_VERYPOOR) || // Appalling and Very Poor
178 (this->town_label++, r <= RATING_MEDIOCRE) || // Poor and Mediocre
179 (this->town_label++, r <= RATING_GOOD) || // Good
180 (this->town_label++, r <= RATING_VERYGOOD) || // Very Good
181 (this->town_label++, true); // Excellent and Outstanding
186 * Get the cost for removing this house
187 * @return the cost (inflation corrected etc)
189 Money HouseSpec::GetRemovalCost() const
191 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
194 /* Local */
195 static int _grow_town_result;
197 /* Describe the possible states */
198 enum TownGrowthResult {
199 GROWTH_SUCCEED = -1,
200 GROWTH_SEARCH_STOPPED = 0
201 // GROWTH_SEARCH_RUNNING >= 1
204 static bool BuildTownHouse(Town *t, TileIndex tile);
205 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
207 static void TownDrawHouseLift(const TileInfo *ti)
209 AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
212 typedef void TownDrawTileProc(const TileInfo *ti);
213 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
214 TownDrawHouseLift
218 * Return a random direction
220 * @return a random direction
222 static inline DiagDirection RandomDiagDir()
224 return (DiagDirection)(3 & Random());
228 * House Tile drawing handler.
229 * Part of the tile loop process
230 * @param ti TileInfo of the tile to draw
232 static void DrawTile_Town(TileInfo *ti)
234 HouseID house_id = GetHouseType(ti->tile);
236 if (house_id >= NEW_HOUSE_OFFSET) {
237 /* Houses don't necessarily need new graphics. If they don't have a
238 * spritegroup associated with them, then the sprite for the substitute
239 * house id is drawn instead. */
240 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
241 DrawNewHouseTile(ti, house_id);
242 return;
243 } else {
244 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
248 /* Retrieve pointer to the draw town tile struct */
249 const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
251 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
253 DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
255 DrawOverlay(ti, MP_HOUSE);
257 /* If houses are invisible, do not draw the upper part */
258 if (IsInvisibilitySet(TO_HOUSES)) return;
260 /* Add a house on top of the ground? */
261 SpriteID image = dcts->building.sprite;
262 if (image != 0) {
263 AddSortableSpriteToDraw(image, dcts->building.pal,
264 ti->x + dcts->subtile_x,
265 ti->y + dcts->subtile_y,
266 dcts->width,
267 dcts->height,
268 dcts->dz,
269 ti->z,
270 IsTransparencySet(TO_HOUSES)
273 if (IsTransparencySet(TO_HOUSES)) return;
277 int proc = dcts->draw_proc - 1;
279 if (proc >= 0) _town_draw_tile_procs[proc](ti);
283 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
285 return GetTileMaxPixelZ(tile);
288 /** Tile callback routine */
289 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
291 HouseID hid = GetHouseType(tile);
293 /* For NewGRF house tiles we might not be drawing a foundation. We need to
294 * account for this, as other structures should
295 * draw the wall of the foundation in this case.
297 if (hid >= NEW_HOUSE_OFFSET) {
298 const HouseSpec *hs = HouseSpec::Get(hid);
299 if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
300 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
301 if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
304 return FlatteningFoundation(tileh);
308 * Animate a tile for a town
309 * Only certain houses can be animated
310 * The newhouses animation supersedes regular ones
311 * @param tile TileIndex of the house to animate
313 static void AnimateTile_Town(TileIndex tile)
315 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
316 AnimateNewHouseTile(tile);
317 return;
320 if (_tick_counter & 3) return;
322 /* If the house is not one with a lift anymore, then stop this animating.
323 * Not exactly sure when this happens, but probably when a house changes.
324 * Before this was just a return...so it'd leak animated tiles..
325 * That bug seems to have been here since day 1?? */
326 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
327 DeleteAnimatedTile(tile);
328 return;
331 if (!LiftHasDestination(tile)) {
332 uint i;
334 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
335 * This is due to the fact that the first floor is, in the graphics,
336 * the height of 2 'normal' floors.
337 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
338 do {
339 i = RandomRange(7);
340 } while (i == 1 || i * 6 == GetLiftPosition(tile));
342 SetLiftDestination(tile, i);
345 int pos = GetLiftPosition(tile);
346 int dest = GetLiftDestination(tile) * 6;
347 pos += (pos < dest) ? 1 : -1;
348 SetLiftPosition(tile, pos);
350 if (pos == dest) {
351 HaltLift(tile);
352 DeleteAnimatedTile(tile);
355 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
359 * Determines if a town is close to a tile
360 * @param tile TileIndex of the tile to query
361 * @param dist maximum distance to be accepted
362 * @returns true if the tile correspond to the distance criteria
364 static bool IsCloseToTown(TileIndex tile, uint dist)
366 /* On a large map with many towns, it may be faster to check the surroundings of the tile.
367 * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
368 if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
369 const int tx = TileX(tile);
370 const int ty = TileY(tile);
371 TileArea tile_area = TileArea(
372 TileXY(max(0, tx - (int) dist), max(0, ty - (int) dist)),
373 TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
375 TILE_AREA_LOOP(atile, tile_area) {
376 if (GetTileType(atile) == MP_HOUSE) {
377 Town *t = Town::GetByTile(atile);
378 if (DistanceManhattan(tile, t->xy) < dist) return true;
381 return false;
384 const Town *t;
386 FOR_ALL_TOWNS(t) {
387 if (DistanceManhattan(tile, t->xy) < dist) return true;
389 return false;
393 * Resize the sign(label) of the town after changes in
394 * population (creation or growth or else)
396 void Town::UpdateVirtCoord()
398 this->UpdateLabel();
399 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
400 SetDParam(0, this->index);
401 SetDParam(1, this->cache.population);
402 this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE, this->Label());
404 SetWindowDirty(WC_TOWN_VIEW, this->index);
407 /** Update the virtual coords needed to draw the town sign for all towns. */
408 void UpdateAllTownVirtCoords()
410 Town *t;
412 FOR_ALL_TOWNS(t) {
413 t->UpdateVirtCoord();
418 * Change the towns population
419 * @param t Town which population has changed
420 * @param mod population change (can be positive or negative)
422 static void ChangePopulation(Town *t, int mod)
424 t->cache.population += mod;
425 InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
426 t->UpdateVirtCoord();
428 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
432 * Determines the world population
433 * Basically, count population of all towns, one by one
434 * @return uint32 the calculated population of the world
436 uint32 GetWorldPopulation()
438 uint32 pop = 0;
439 const Town *t;
441 FOR_ALL_TOWNS(t) pop += t->cache.population;
442 return pop;
446 * Helper function for house completion stages progression
447 * @param tile TileIndex of the house (or parts of it) to "grow"
449 static void MakeSingleHouseBigger(TileIndex tile)
451 assert(IsTileType(tile, MP_HOUSE));
453 /* progress in construction stages */
454 IncHouseConstructionTick(tile);
455 if (GetHouseConstructionTick(tile) != 0) return;
457 AnimateNewHouseConstruction(tile);
459 if (IsHouseCompleted(tile)) {
460 /* Now that construction is complete, we can add the population of the
461 * building to the town. */
462 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
463 ResetHouseAge(tile);
465 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
469 * Make the house advance in its construction stages until completion
470 * @param tile TileIndex of house
472 static void MakeTownHouseBigger(TileIndex tile)
474 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
475 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
476 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
477 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
478 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
482 * Generate cargo for a town (house).
484 * The amount of cargo should be and will be greater than zero.
486 * @param t current town
487 * @param ct type of cargo to generate, usually CT_PASSENGERS or CT_MAIL
488 * @param amount how many units of cargo
489 * @param stations available stations for this house
490 * @param economy_adjust true if amount should be reduced during recession
492 static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool economy_adjust)
494 // custom cargo generation factor
495 int cf = _settings_game.economy.town_cargo_factor;
497 // when the economy flunctuates, everyone wants to stay at home
498 if (economy_adjust && EconomyIsInRecession()) {
499 amount = (amount + 1) >> 1;
502 // apply custom factor?
503 if (cf < 0) {
504 // approx (amount / 2^cf)
505 // adjust with a constant offset of {(2 ^ cf) - 1} (i.e. add cf * 1-bits) before dividing to ensure that it doesn't become zero
506 // this skews the curve a little so that isn't entirely exponential, but will still decrease
507 amount = (amount + ((1 << -cf) - 1)) >> -cf;
510 else if (cf > 0) {
511 // approx (amount * 2^cf)
512 // XXX: overflow?
513 amount = amount << cf;
516 // with the adjustments above, this should never happen
517 assert(amount > 0);
519 // calculate for town stats
520 switch (ct) {
521 case CT_PASSENGERS:
522 case CT_MAIL:
523 t->supplied[ct].new_max += amount;
524 t->supplied[ct].new_act += MoveGoodsToStation(ct, amount, ST_TOWN, t->index, stations.GetStations());
525 break;
527 default: {
528 const CargoSpec *cs = CargoSpec::Get(ct);
529 t->supplied[cs->Index()].new_max += amount;
530 t->supplied[cs->Index()].new_act += MoveGoodsToStation(ct, amount, ST_TOWN, t->index, stations.GetStations());
531 break;
537 * Tile callback function.
539 * Periodic tic handler for houses and town
540 * @param tile been asked to do its stuff
542 static void TileLoop_Town(TileIndex tile)
544 HouseID house_id = GetHouseType(tile);
546 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
547 * doesn't exist any more, so don't continue here. */
548 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
550 if (!IsHouseCompleted(tile)) {
551 /* Construction is not completed. See if we can go further in construction*/
552 MakeTownHouseBigger(tile);
553 return;
556 const HouseSpec *hs = HouseSpec::Get(house_id);
558 /* If the lift has a destination, it is already an animated tile. */
559 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
560 house_id < NEW_HOUSE_OFFSET &&
561 !LiftHasDestination(tile) &&
562 Chance16(1, 2)) {
563 AddAnimatedTile(tile);
566 Town *t = Town::GetByTile(tile);
567 uint32 r = Random();
569 StationFinder stations(TileArea(tile, 1, 1));
571 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
572 for (uint i = 0; i < 256; i++) {
573 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
575 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
577 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
578 if (cargo == CT_INVALID) continue;
580 uint amt = GB(callback, 0, 8);
581 if (amt == 0) continue;
583 // XXX: no economy flunctuation for GRF cargos?
584 TownGenerateCargo(t, cargo, amt, stations, false);
586 } else {
587 if (GB(r, 0, 8) < hs->population) {
588 uint amt = GB(r, 16, 3) + 1;
590 TownGenerateCargo(t, CT_PASSENGERS, amt, stations, true);
593 if (GB(r, 8, 8) < hs->mail_generation) {
594 uint amt = GB(r, 24, 3) + 1;
596 TownGenerateCargo(t, CT_MAIL, amt, stations, true);
600 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
602 const int32 ticks_per_tile_loop = 256;
604 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
605 HasBit(t->flags, TOWN_IS_GROWING) &&
606 CanDeleteHouse(tile) &&
607 GetHouseAge(tile) >= hs->minimum_life &&
608 t->time_until_rebuild <= (_date - (hs->minimum_life * DAYS_IN_YEAR))) {
610 int32 tile_loops_until_rebuild = GB(r, 16, 8) + 192;
611 t->time_until_rebuild = _date + ((tile_loops_until_rebuild * ticks_per_tile_loop) / DEFAULT_DAY_TICKS);
613 ClearTownHouse(t, tile);
615 /* Rebuild with another house? */
616 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
619 cur_company.Restore();
622 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
624 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
625 if (!CanDeleteHouse(tile)) return CMD_ERROR;
627 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
629 CommandCost cost(EXPENSES_CONSTRUCTION);
630 cost.AddCost(hs->GetRemovalCost());
632 int rating = hs->remove_rating_decrease;
633 Town *t = Town::GetByTile(tile);
635 if (Company::IsValidID(_current_company)) {
636 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
637 SetDParam(0, t->index);
638 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
642 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
643 if (flags & DC_EXEC) {
644 ClearTownHouse(t, tile);
647 return cost;
650 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
652 HouseID house_id = GetHouseType(tile);
653 const HouseSpec *hs = HouseSpec::Get(house_id);
654 Town *t = Town::GetByTile(tile);
656 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
657 for (uint i = 0; i < 256; i++) {
658 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
660 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
662 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
664 if (cargo == CT_INVALID) continue;
665 produced[cargo]++;
667 } else {
668 if (hs->population > 0) {
669 produced[CT_PASSENGERS]++;
671 if (hs->mail_generation > 0) {
672 produced[CT_MAIL]++;
677 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
679 if (cargo == CT_INVALID || amount == 0) return;
680 acceptance[cargo] += amount;
681 SetBit(*always_accepted, cargo);
684 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
686 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
687 CargoID accepts[3];
689 /* Set the initial accepted cargo types */
690 for (uint8 i = 0; i < lengthof(accepts); i++) {
691 accepts[i] = hs->accepts_cargo[i];
694 /* Check for custom accepted cargo types */
695 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
696 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
697 if (callback != CALLBACK_FAILED) {
698 /* Replace accepted cargo types with translated values from callback */
699 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
700 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
701 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
705 /* Check for custom cargo acceptance */
706 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
707 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
708 if (callback != CALLBACK_FAILED) {
709 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
710 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
711 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
712 /* The 'S' bit indicates food instead of goods */
713 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
714 } else {
715 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
717 return;
721 /* No custom acceptance, so fill in with the default values */
722 for (uint8 i = 0; i < lengthof(accepts); i++) {
723 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
727 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
729 const HouseID house = GetHouseType(tile);
730 const HouseSpec *hs = HouseSpec::Get(house);
731 bool house_completed = IsHouseCompleted(tile);
733 td->str = hs->building_name;
735 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
736 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
737 if (callback_res > 0x400) {
738 ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
739 } else {
740 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
741 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
742 td->str = new_name;
747 if (!house_completed) {
748 SetDParamX(td->dparam, 0, td->str);
749 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
752 if (hs->grf_prop.grffile != NULL) {
753 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
754 td->grf = gc->GetName();
757 td->owner[0] = OWNER_TOWN;
760 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
762 /* not used */
763 return 0;
766 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
768 /* not used */
771 /** Update the total cargo acceptance of the whole town.
772 * @param t The town to update.
774 void UpdateTownCargoTotal(Town *t)
776 t->cargo_accepted_total = 0;
778 const TileArea &area = t->cargo_accepted.GetArea();
779 TILE_AREA_LOOP(tile, area) {
780 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
781 t->cargo_accepted_total |= t->cargo_accepted[tile];
787 * Update accepted town cargoes around a specific tile.
788 * @param t The town to update.
789 * @param start Update the values around this tile.
790 * @param update_total Set to true if the total cargo acceptance should be updated.
792 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
794 CargoArray accepted, produced;
795 uint32 dummy;
797 /* Gather acceptance for all houses in an area around the start tile.
798 * The area is composed of the square the tile is in, extended one square in all
799 * directions as the coverage area of a single station is bigger than just one square. */
800 TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
801 TILE_AREA_LOOP(tile, area) {
802 if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
804 AddAcceptedCargo_Town(tile, accepted, &dummy);
805 AddProducedCargo_Town(tile, produced);
808 /* Create bitmap of produced and accepted cargoes. */
809 uint32 acc = 0;
810 for (uint cid = 0; cid < NUM_CARGO; cid++) {
811 if (accepted[cid] >= 8) SetBit(acc, cid);
812 if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
814 t->cargo_accepted[start] = acc;
816 if (update_total) UpdateTownCargoTotal(t);
819 /** Update cargo acceptance for the complete town.
820 * @param t The town to update.
822 void UpdateTownCargoes(Town *t)
824 t->cargo_produced = 0;
826 const TileArea &area = t->cargo_accepted.GetArea();
827 if (area.tile == INVALID_TILE) return;
829 /* Update acceptance for each grid square. */
830 TILE_AREA_LOOP(tile, area) {
831 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
832 UpdateTownCargoes(t, tile, false);
836 /* Update the total acceptance. */
837 UpdateTownCargoTotal(t);
840 /** Updates the bitmap of all cargoes accepted by houses. */
841 void UpdateTownCargoBitmap()
843 Town *town;
844 _town_cargoes_accepted = 0;
846 FOR_ALL_TOWNS(town) {
847 _town_cargoes_accepted |= town->cargo_accepted_total;
851 static bool GrowTown(Town *t);
853 static void TownTickHandler(Town *t)
855 if (HasBit(t->flags, TOWN_IS_GROWING)) {
856 int i = t->grow_counter - 1;
857 if (i < 0) {
858 if (GrowTown(t)) {
859 i = t->growth_rate & (~TOWN_GROW_RATE_CUSTOM);
860 } else {
861 i = 0;
864 t->grow_counter = i;
868 void OnTick_Town()
870 if (_game_mode == GM_EDITOR) return;
872 Town *t;
873 FOR_ALL_TOWNS(t) {
874 /* Run town tick at regular intervals, but not all at once. */
875 if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0) {
876 TownTickHandler(t);
882 * Return the RoadBits of a tile
884 * @note There are many other functions doing things like that.
885 * @note Needs to be checked for needlessness.
886 * @param tile The tile we want to analyse
887 * @return The roadbits of the given tile
889 static RoadBits GetTownRoadBits(TileIndex tile)
891 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
893 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
897 * Check for parallel road inside a given distance.
898 * Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
899 * is there a parallel road left or right of it within distance dist_multi?
901 * @param tile current tile
902 * @param dir target direction
903 * @param dist_multi distance multiplayer
904 * @return true if there is a parallel road
906 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
908 if (!IsValidTile(tile)) return false;
910 /* Lookup table for the used diff values */
911 const TileIndexDiff tid_lt[3] = {
912 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
913 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
914 TileOffsByDiagDir(ReverseDiagDir(dir)),
917 dist_multi = (dist_multi + 1) * 4;
918 for (uint pos = 4; pos < dist_multi; pos++) {
919 /* Go (pos / 4) tiles to the left or the right */
920 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
922 /* Use the current tile as origin, or go one tile backwards */
923 if (pos & 2) cur += tid_lt[2];
925 /* Test for roadbit parallel to dir and facing towards the middle axis */
926 if (IsValidTile(tile + cur) &&
927 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
929 return false;
933 * Check if a Road is allowed on a given tile
935 * @param t The current town
936 * @param tile The target tile
937 * @param dir The direction in which we want to extend the town
938 * @return true if it is allowed else false
940 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
942 if (DistanceFromEdge(tile) == 0) return false;
944 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
945 if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
947 /* Check if there already is a road at this point? */
948 if (GetTownRoadBits(tile) == ROAD_NONE) {
949 /* No, try if we are able to build a road piece there.
950 * If that fails clear the land, and if that fails exit.
951 * This is to make sure that we can build a road here later. */
952 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
953 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
954 return false;
958 Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
959 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
960 if (cur_slope == SLOPE_FLAT) return ret;
962 /* If the tile is not a slope in the right direction, then
963 * maybe terraform some. */
964 Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
965 if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
966 if (Chance16(1, 8)) {
967 CommandCost res = CMD_ERROR;
968 if (!_generating_world && Chance16(1, 10)) {
969 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
970 res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
971 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
973 if (res.Failed() && Chance16(1, 3)) {
974 /* We can consider building on the slope, though. */
975 return ret;
978 return false;
980 return ret;
983 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
985 assert(tile < MapSize());
987 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
988 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
989 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
990 return true;
993 static void LevelTownLand(TileIndex tile)
995 assert(tile < MapSize());
997 /* Don't terraform if land is plain or if there's a house there. */
998 if (IsTileType(tile, MP_HOUSE)) return;
999 Slope tileh = GetTileSlope(tile);
1000 if (tileh == SLOPE_FLAT) return;
1002 /* First try up, then down */
1003 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
1004 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
1009 * Generate the RoadBits of a grid tile
1011 * @param t current town
1012 * @param tile tile in reference to the town
1013 * @param dir The direction to which we are growing ATM
1014 * @return the RoadBit of the current tile regarding
1015 * the selected town layout
1017 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
1019 /* align the grid to the downtown */
1020 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1021 RoadBits rcmd = ROAD_NONE;
1023 switch (t->layout) {
1024 default: NOT_REACHED();
1026 case TL_2X2_GRID:
1027 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
1028 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
1029 break;
1031 case TL_3X3_GRID:
1032 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
1033 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
1034 break;
1037 /* Optimise only X-junctions */
1038 if (rcmd != ROAD_ALL) return rcmd;
1040 RoadBits rb_template;
1042 switch (GetTileSlope(tile)) {
1043 default: rb_template = ROAD_ALL; break;
1044 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
1045 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
1046 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
1047 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
1048 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1049 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1050 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1051 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1052 case SLOPE_STEEP_W:
1053 case SLOPE_STEEP_S:
1054 case SLOPE_STEEP_E:
1055 case SLOPE_STEEP_N:
1056 rb_template = ROAD_NONE;
1057 break;
1060 /* Stop if the template is compatible to the growth dir */
1061 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1062 /* If not generate a straight road in the direction of the growth */
1063 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
1067 * Grows the town with an extra house.
1068 * Check if there are enough neighbor house tiles
1069 * next to the current tile. If there are enough
1070 * add another house.
1072 * @param t The current town
1073 * @param tile The target tile for the extra house
1074 * @return true if an extra house has been added
1076 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
1078 /* We can't look further than that. */
1079 if (DistanceFromEdge(tile) == 0) return false;
1081 uint counter = 0; // counts the house neighbor tiles
1083 /* Check the tiles E,N,W and S of the current tile for houses */
1084 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1085 /* Count both void and house tiles for checking whether there
1086 * are enough houses in the area. This to make it likely that
1087 * houses get build up to the edge of the map. */
1088 switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1089 case MP_HOUSE:
1090 case MP_VOID:
1091 counter++;
1092 break;
1094 default:
1095 break;
1098 /* If there are enough neighbors stop here */
1099 if (counter >= 3) {
1100 if (BuildTownHouse(t, tile)) {
1101 _grow_town_result = GROWTH_SUCCEED;
1102 return true;
1104 return false;
1107 return false;
1111 * Grows the town with a road piece.
1113 * @param t The current town
1114 * @param tile The current tile
1115 * @param rcmd The RoadBits we want to build on the tile
1116 * @return true if the RoadBits have been added else false
1118 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1120 if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1121 _grow_town_result = GROWTH_SUCCEED;
1122 return true;
1124 return false;
1128 * Grows the town with a bridge.
1129 * At first we check if a bridge is reasonable.
1130 * If so we check if we are able to build it.
1132 * @param t The current town
1133 * @param tile The current tile
1134 * @param bridge_dir The valid direction in which to grow a bridge
1135 * @return true if a bridge has been build else false
1137 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1139 assert(bridge_dir < DIAGDIR_END);
1141 const Slope slope = GetTileSlope(tile);
1143 /* Make sure the direction is compatible with the slope.
1144 * Well we check if the slope has an up bit set in the
1145 * reverse direction. */
1146 if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1148 /* Assure that the bridge is connectable to the start side */
1149 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1151 /* We are in the right direction */
1152 uint8 bridge_length = 0; // This value stores the length of the possible bridge
1153 TileIndex bridge_tile = tile; // Used to store the other waterside
1155 const int delta = TileOffsByDiagDir(bridge_dir);
1157 if (slope == SLOPE_FLAT) {
1158 /* Bridges starting on flat tiles are only allowed when crossing rivers or rails. */
1159 do {
1160 if (bridge_length++ >= 5) {
1161 /* Allow to cross rivers, not big lakes, nor large amounts of rails. */
1162 return false;
1164 bridge_tile += delta;
1165 } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile)));
1166 } else {
1167 do {
1168 if (bridge_length++ >= 11) {
1169 /* Max 11 tile long bridges */
1170 return false;
1172 bridge_tile += delta;
1173 } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile)));
1176 /* no water tiles in between? */
1177 if (bridge_length == 1) return false;
1179 for (uint8 times = 0; times <= 22; times++) {
1180 byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1182 /* Can we actually build the bridge? */
1183 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1184 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1185 _grow_town_result = GROWTH_SUCCEED;
1186 return true;
1189 /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1190 return false;
1194 * Grows the given town.
1195 * There are at the moment 3 possible way's for
1196 * the town expansion:
1197 * @li Generate a random tile and check if there is a road allowed
1198 * @li TL_ORIGINAL
1199 * @li TL_BETTER_ROADS
1200 * @li Check if the town geometry allows a road and which one
1201 * @li TL_2X2_GRID
1202 * @li TL_3X3_GRID
1203 * @li Forbid roads, only build houses
1205 * @param tile_ptr The current tile
1206 * @param cur_rb The current tiles RoadBits
1207 * @param target_dir The target road dir
1208 * @param t1 The current town
1210 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1212 RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1213 TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1215 assert(tile < MapSize());
1217 if (cur_rb == ROAD_NONE) {
1218 /* Tile has no road. First reset the status counter
1219 * to say that this is the last iteration. */
1220 _grow_town_result = GROWTH_SEARCH_STOPPED;
1222 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1223 if (!_settings_game.economy.allow_town_level_crossings && IsTileType(tile, MP_RAILWAY)) return;
1225 /* Remove hills etc */
1226 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1228 /* Is a road allowed here? */
1229 switch (t1->layout) {
1230 default: NOT_REACHED();
1232 case TL_3X3_GRID:
1233 case TL_2X2_GRID:
1234 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1235 if (rcmd == ROAD_NONE) return;
1236 break;
1238 case TL_BETTER_ROADS:
1239 case TL_ORIGINAL:
1240 if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1242 DiagDirection source_dir = ReverseDiagDir(target_dir);
1244 if (Chance16(1, 4)) {
1245 /* Randomize a new target dir */
1246 do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1249 if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1250 /* A road is not allowed to continue the randomized road,
1251 * return if the road we're trying to build is curved. */
1252 if (target_dir != ReverseDiagDir(source_dir)) return;
1254 /* Return if neither side of the new road is a house */
1255 if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
1256 !IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
1257 return;
1260 /* That means that the road is only allowed if there is a house
1261 * at any side of the new road. */
1264 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1265 break;
1268 } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1269 /* Continue building on a partial road.
1270 * Should be always OK, so we only generate
1271 * the fitting RoadBits */
1272 _grow_town_result = GROWTH_SEARCH_STOPPED;
1274 if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
1276 switch (t1->layout) {
1277 default: NOT_REACHED();
1279 case TL_3X3_GRID:
1280 case TL_2X2_GRID:
1281 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1282 break;
1284 case TL_BETTER_ROADS:
1285 case TL_ORIGINAL:
1286 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1287 break;
1289 } else {
1290 bool allow_house = true; // Value which decides if we want to construct a house
1292 /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1293 * it is the starting tile. Half the time, we stay on this side then.*/
1294 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1295 if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1296 *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1298 return;
1301 /* Possibly extend the road in a direction.
1302 * Randomize a direction and if it has a road, bail out. */
1303 target_dir = RandomDiagDir();
1304 if (cur_rb & DiagDirToRoadBits(target_dir)) return;
1306 /* This is the tile we will reach if we extend to this direction. */
1307 TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
1309 /* Don't walk into water. */
1310 if (HasTileWaterGround(house_tile)) return;
1312 if (!IsValidTile(house_tile)) return;
1314 if (_settings_game.economy.allow_town_roads || _generating_world) {
1315 switch (t1->layout) {
1316 default: NOT_REACHED();
1318 case TL_3X3_GRID: // Use 2x2 grid afterwards!
1319 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1320 FALLTHROUGH;
1322 case TL_2X2_GRID:
1323 rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1324 allow_house = (rcmd & DiagDirToRoadBits(target_dir)) == ROAD_NONE;
1325 break;
1327 case TL_BETTER_ROADS: // Use original afterwards!
1328 GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1329 FALLTHROUGH;
1331 case TL_ORIGINAL:
1332 /* Allow a house at the edge. 60% chance or
1333 * always ok if no road allowed. */
1334 rcmd = DiagDirToRoadBits(target_dir);
1335 allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1336 break;
1340 if (allow_house) {
1341 /* Build a house, but not if there already is a house there. */
1342 if (!IsTileType(house_tile, MP_HOUSE)) {
1343 /* Level the land if possible */
1344 if (Chance16(1, 6)) LevelTownLand(house_tile);
1346 /* And build a house.
1347 * Set result to -1 if we managed to build it. */
1348 if (BuildTownHouse(t1, house_tile)) {
1349 _grow_town_result = GROWTH_SUCCEED;
1352 return;
1355 _grow_town_result = GROWTH_SEARCH_STOPPED;
1358 /* Return if a water tile */
1359 if (HasTileWaterGround(tile)) return;
1361 /* Make the roads look nicer */
1362 rcmd = CleanUpRoadBits(tile, rcmd);
1363 if (rcmd == ROAD_NONE) return;
1365 /* Only use the target direction for bridges to ensure they're connected.
1366 * The target_dir is as computed previously according to town layout, so
1367 * it will match it perfectly. */
1368 if (GrowTownWithBridge(t1, tile, target_dir)) return;
1370 GrowTownWithRoad(t1, tile, rcmd);
1374 * Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
1375 * This only checks trivial but often cases.
1376 * @param tile Start tile for road.
1377 * @param dir Direction for road to follow or build.
1378 * @return true If road is or can be connected in the specified direction.
1380 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1382 TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1383 if (!IsValidTile(target_tile)) return false;
1384 if (HasTileWaterGround(target_tile)) return false;
1386 RoadBits target_rb = GetTownRoadBits(target_tile);
1387 if (_settings_game.economy.allow_town_roads || _generating_world) {
1388 /* Check whether a road connection exists or can be build. */
1389 switch (GetTileType(target_tile)) {
1390 case MP_ROAD:
1391 return target_rb != ROAD_NONE;
1393 case MP_STATION:
1394 return IsDriveThroughStopTile(target_tile);
1396 case MP_TUNNELBRIDGE:
1397 return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1399 case MP_HOUSE:
1400 case MP_INDUSTRY:
1401 case MP_OBJECT:
1402 return false;
1404 default:
1405 /* Checked for void and water earlier */
1406 return true;
1408 } else {
1409 /* Check whether a road connection already exists,
1410 * and it leads somewhere else. */
1411 RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1412 return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1417 * Returns "growth" if a house was built, or no if the build failed.
1418 * @param t town to inquiry
1419 * @param tile to inquiry
1420 * @return true if town expansion was possible
1422 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1424 /* Special case.
1425 * @see GrowTownInTile Check the else if
1427 DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1429 assert(tile < MapSize());
1431 /* Number of times to search.
1432 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1433 * them a little handicap. */
1434 switch (t->layout) {
1435 case TL_BETTER_ROADS:
1436 _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1437 break;
1439 case TL_3X3_GRID:
1440 case TL_2X2_GRID:
1441 _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1442 break;
1444 default:
1445 _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1446 break;
1449 do {
1450 RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1452 /* Try to grow the town from this point */
1453 GrowTownInTile(&tile, cur_rb, target_dir, t);
1454 if (_grow_town_result == GROWTH_SUCCEED) return true;
1456 /* Exclude the source position from the bitmask
1457 * and return if no more road blocks available */
1458 if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1459 if (cur_rb == ROAD_NONE) return false;
1461 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1462 /* Only build in the direction away from the tunnel or bridge. */
1463 target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1464 } else {
1465 /* Select a random bit from the blockmask, walk a step
1466 * and continue the search from there. */
1467 do {
1468 if (cur_rb == ROAD_NONE) return false;
1469 RoadBits target_bits;
1470 do {
1471 target_dir = RandomDiagDir();
1472 target_bits = DiagDirToRoadBits(target_dir);
1473 } while (!(cur_rb & target_bits));
1474 cur_rb &= ~target_bits;
1475 } while (!CanFollowRoad(tile, target_dir));
1477 tile = TileAddByDiagDir(tile, target_dir);
1479 if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
1480 /* Don't allow building over roads of other cities */
1481 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1482 return false;
1483 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1484 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1485 * owner :) (happy happy happy road now) */
1486 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
1487 SetTownIndex(tile, t->index);
1491 /* Max number of times is checked. */
1492 } while (--_grow_town_result >= 0);
1494 return false;
1498 * Generate a random road block.
1499 * The probability of a straight road
1500 * is somewhat higher than a curved.
1502 * @return A RoadBits value with 2 bits set
1504 static RoadBits GenRandomRoadBits()
1506 uint32 r = Random();
1507 uint a = GB(r, 0, 2);
1508 uint b = GB(r, 8, 2);
1509 if (a == b) b ^= 2;
1510 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1514 * Grow the town
1515 * @param t town to grow
1516 * @return true iff something (house, road, bridge, ...) was built
1518 static bool GrowTown(Town *t)
1520 static const TileIndexDiffC _town_coord_mod[] = {
1521 {-1, 0},
1522 { 1, 1},
1523 { 1, -1},
1524 {-1, -1},
1525 {-1, 0},
1526 { 0, 2},
1527 { 2, 0},
1528 { 0, -2},
1529 {-1, -1},
1530 {-2, 2},
1531 { 2, 2},
1532 { 2, -2},
1533 { 0, 0}
1536 /* Current "company" is a town */
1537 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1539 TileIndex tile = t->xy; // The tile we are working with ATM
1541 /* Find a road that we can base the construction on. */
1542 const TileIndexDiffC *ptr;
1543 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1544 if (GetTownRoadBits(tile) != ROAD_NONE) {
1545 bool success = GrowTownAtRoad(t, tile);
1546 cur_company.Restore();
1547 return success;
1549 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1552 /* No road available, try to build a random road block by
1553 * clearing some land and then building a road there. */
1554 if (_settings_game.economy.allow_town_roads || _generating_world) {
1555 tile = t->xy;
1556 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1557 /* Only work with plain land that not already has a house */
1558 if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1559 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1560 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1561 cur_company.Restore();
1562 return true;
1565 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1569 cur_company.Restore();
1570 return false;
1573 void UpdateTownRadius(Town *t)
1575 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1576 { 4, 0, 0, 0, 0}, // 0
1577 { 16, 0, 0, 0, 0},
1578 { 25, 0, 0, 0, 0},
1579 { 36, 0, 0, 0, 0},
1580 { 49, 0, 4, 0, 0},
1581 { 64, 0, 4, 0, 0}, // 20
1582 { 64, 0, 9, 0, 1},
1583 { 64, 0, 9, 0, 4},
1584 { 64, 0, 16, 0, 4},
1585 { 81, 0, 16, 0, 4},
1586 { 81, 0, 16, 0, 4}, // 40
1587 { 81, 0, 25, 0, 9},
1588 { 81, 36, 25, 0, 9},
1589 { 81, 36, 25, 16, 9},
1590 { 81, 49, 0, 25, 9},
1591 { 81, 64, 0, 25, 9}, // 60
1592 { 81, 64, 0, 36, 9},
1593 { 81, 64, 0, 36, 16},
1594 {100, 81, 0, 49, 16},
1595 {100, 81, 0, 49, 25},
1596 {121, 81, 0, 49, 25}, // 80
1597 {121, 81, 0, 49, 25},
1598 {121, 81, 0, 49, 36}, // 88
1601 if (t->cache.num_houses < 92) {
1602 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));
1603 } else {
1604 int mass = t->cache.num_houses / 8;
1605 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1606 * The offsets are to make sure the radii do not decrease in size when going from the table
1607 * to the calculated value.*/
1608 t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1609 t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1610 t->cache.squared_town_zone_radius[2] = 0;
1611 t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1612 t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1616 void UpdateTownMaxPass(Town *t)
1618 t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1619 t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1623 * Does the actual town creation.
1625 * @param t The town
1626 * @param tile Where to put it
1627 * @param townnameparts The town name
1628 * @param size Parameter for size determination
1629 * @param city whether to build a city or town
1630 * @param layout the (road) layout of the town
1631 * @param manual was the town placed manually?
1633 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1635 const int32 tile_loops_until_rebuild = 10;
1636 const int32 ticks_per_tile_loop = 256;
1638 t->xy = tile;
1639 t->cache.num_houses = 0;
1640 t->time_until_rebuild = _date + ((tile_loops_until_rebuild * ticks_per_tile_loop) / DEFAULT_DAY_TICKS);
1641 UpdateTownRadius(t);
1642 t->flags = 0;
1643 t->cache.population = 0;
1644 t->grow_counter = 0;
1645 t->growth_rate = 250;
1647 /* Set the default cargo requirement for town growth */
1648 switch (_settings_game.game_creation.landscape) {
1649 case LT_ARCTIC:
1650 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
1651 break;
1653 case LT_TROPIC:
1654 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
1655 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
1656 break;
1659 t->fund_buildings_months = 0;
1661 for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1663 t->have_ratings = 0;
1664 t->exclusivity = INVALID_COMPANY;
1665 t->exclusive_counter = 0;
1666 t->statues = 0;
1668 extern int _nb_orig_names;
1669 if (_settings_game.game_creation.town_name < _nb_orig_names) {
1670 /* Original town name */
1671 t->townnamegrfid = 0;
1672 t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1673 } else {
1674 /* Newgrf town name */
1675 t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1676 t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1678 t->townnameparts = townnameparts;
1680 t->UpdateVirtCoord();
1681 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
1683 t->InitializeLayout(layout);
1685 t->larger_town = city;
1687 int x = (int)size * 16 + 3;
1688 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1689 /* Don't create huge cities when founding town in-game */
1690 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1692 t->cache.num_houses += x;
1693 UpdateTownRadius(t);
1695 int i = x * 4;
1696 do {
1697 GrowTown(t);
1698 } while (--i);
1700 t->cache.num_houses -= x;
1701 UpdateTownRadius(t);
1702 UpdateTownMaxPass(t);
1703 UpdateAirportsNoise();
1707 * Checks if it's possible to place a town at given tile
1708 * @param tile tile to check
1709 * @return error value or zero cost
1711 static CommandCost TownCanBePlacedHere(TileIndex tile)
1713 /* Check if too close to the edge of map */
1714 if (DistanceFromEdge(tile) < 12) {
1715 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1718 /* Check distance to all other towns. */
1719 if (IsCloseToTown(tile, _settings_game.economy.town_min_distance)) {
1720 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1723 /* Check max height level. */
1724 if (GetTileZ(tile) > _settings_game.economy.max_town_heightlevel) {
1725 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1728 /* Cannot build above the tree line. */
1729 if (_settings_game.construction.trees_around_snow_line_enabled && (GetTileZ(tile) >= HighestSnowLine() + (_settings_game.construction.trees_around_snow_line_range / 2))) {
1730 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1733 /* Can only build on clear flat areas, possibly with trees. */
1734 if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1735 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1738 return CommandCost(EXPENSES_OTHER);
1742 * Verifies this custom name is unique. Only custom names are checked.
1743 * @param name name to check
1744 * @return is this name unique?
1746 static bool IsUniqueTownName(const char *name)
1748 const Town *t;
1750 FOR_ALL_TOWNS(t) {
1751 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
1754 return true;
1758 * Create a new town.
1759 * @param tile coordinates where town is built
1760 * @param flags type of operation
1761 * @param p1 0..1 size of the town (@see TownSize)
1762 * 2 true iff it should be a city
1763 * 3..5 town road layout (@see TownLayout)
1764 * 6 use random location (randomize \c tile )
1765 * @param p2 town name parts
1766 * @param text Custom name for the town. If empty, the town name parts will be used.
1767 * @return the cost of this operation or an error
1769 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1771 TownSize size = Extract<TownSize, 0, 2>(p1);
1772 bool city = HasBit(p1, 2);
1773 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1774 TownNameParams par(_settings_game.game_creation.town_name);
1775 bool random = HasBit(p1, 6);
1776 uint32 townnameparts = p2;
1778 if (size >= TSZ_END) return CMD_ERROR;
1779 if (layout >= NUM_TLS) return CMD_ERROR;
1781 /* Some things are allowed only in the scenario editor and for game scripts. */
1782 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1783 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
1784 if (size == TSZ_LARGE) return CMD_ERROR;
1785 if (random) return CMD_ERROR;
1786 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
1787 return CMD_ERROR;
1789 } else if (_current_company == OWNER_DEITY && random) {
1790 /* Random parameter is not allowed for Game Scripts. */
1791 return CMD_ERROR;
1794 if (StrEmpty(text)) {
1795 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1796 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1797 } else {
1798 /* If name is not empty, it has to be unique custom name */
1799 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
1800 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1803 /* Allocate town struct */
1804 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1806 if (!random) {
1807 CommandCost ret = TownCanBePlacedHere(tile);
1808 if (ret.Failed()) return ret;
1811 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1812 /* multidimensional arrays have to have defined length of non-first dimension */
1813 assert_compile(lengthof(price_mult[0]) == 4);
1815 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1816 byte mult = price_mult[city][size];
1818 cost.MultiplyCost(mult);
1820 /* Create the town */
1821 if (flags & DC_EXEC) {
1822 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1823 _additional_cash_required = cost.GetCost();
1824 return CommandCost(EXPENSES_OTHER);
1827 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1828 UpdateNearestTownForRoadTiles(true);
1829 Town *t;
1830 if (random) {
1831 t = CreateRandomTown(20, townnameparts, size, city, layout);
1832 if (t == NULL) {
1833 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1834 } else {
1835 _new_town_id = t->index;
1837 } else {
1838 t = new Town(tile);
1839 DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1841 UpdateNearestTownForRoadTiles(false);
1842 old_generating_world.Restore();
1844 if (t != NULL && !StrEmpty(text)) {
1845 t->name = stredup(text);
1846 t->UpdateVirtCoord();
1849 if (_game_mode != GM_EDITOR) {
1850 /* 't' can't be NULL since 'random' is false outside scenedit */
1851 assert(!random);
1852 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1853 SetDParam(0, _current_company);
1854 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1856 char *cn = stredup(company_name);
1857 SetDParamStr(0, cn);
1858 SetDParam(1, t->index);
1860 AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1861 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1862 Game::NewEvent(new ScriptEventTownFounded(t->index));
1865 return cost;
1869 * Towns must all be placed on the same grid or when they eventually
1870 * interpenetrate their road networks will not mesh nicely; this
1871 * function adjusts a tile so that it aligns properly.
1873 * @param tile the tile to start at
1874 * @param layout which town layout algo is in effect
1875 * @return the adjusted tile
1877 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
1879 switch (layout) {
1880 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1881 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1882 default: return tile;
1887 * Towns must all be placed on the same grid or when they eventually
1888 * interpenetrate their road networks will not mesh nicely; this
1889 * function tells you if a tile is properly aligned.
1891 * @param tile the tile to start at
1892 * @param layout which town layout algo is in effect
1893 * @return true if the tile is in the correct location
1895 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
1897 switch (layout) {
1898 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
1899 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
1900 default: return true;
1905 * Used as the user_data for FindFurthestFromWater
1907 struct SpotData {
1908 TileIndex tile; ///< holds the tile that was found
1909 uint max_dist; ///< holds the distance that tile is from the water
1910 TownLayout layout; ///< tells us what kind of town we're building
1914 * CircularTileSearch callback; finds the tile furthest from any
1915 * water. slightly bit tricky, since it has to do a search of its own
1916 * in order to find the distance to the water from each square in the
1917 * radius.
1919 * Also, this never returns true, because it needs to take into
1920 * account all locations being searched before it knows which is the
1921 * furthest.
1923 * @param tile Start looking from this tile
1924 * @param user_data Storage area for data that must last across calls;
1925 * must be a pointer to struct SpotData
1927 * @return always false
1929 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
1931 SpotData *sp = (SpotData*)user_data;
1932 uint dist = GetClosestWaterDistance(tile, true);
1934 if (IsTileType(tile, MP_CLEAR) &&
1935 IsTileFlat(tile) &&
1936 IsTileAlignedToGrid(tile, sp->layout) &&
1937 dist > sp->max_dist) {
1938 sp->tile = tile;
1939 sp->max_dist = dist;
1942 return false;
1946 * CircularTileSearch callback; finds the nearest land tile
1948 * @param tile Start looking from this tile
1949 * @param user_data not used
1951 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
1953 return IsTileType(tile, MP_CLEAR);
1957 * Given a spot on the map (presumed to be a water tile), find a good
1958 * coastal spot to build a city. We don't want to build too close to
1959 * the edge if we can help it (since that retards city growth) hence
1960 * the search within a search within a search. O(n*m^2), where n is
1961 * how far to search for land, and m is how far inland to look for a
1962 * flat spot.
1964 * @param tile Start looking from this spot.
1965 * @param layout the road layout to search for
1966 * @return tile that was found
1968 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
1970 SpotData sp = { INVALID_TILE, 0, layout };
1972 TileIndex coast = tile;
1973 if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
1974 CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
1975 return sp.tile;
1978 /* if we get here just give up */
1979 return INVALID_TILE;
1982 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
1984 assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
1986 if (!Town::CanAllocateItem()) return NULL;
1988 do {
1989 /* Generate a tile index not too close from the edge */
1990 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
1992 /* if we tried to place the town on water, slide it over onto
1993 * the nearest likely-looking spot */
1994 if (IsTileType(tile, MP_WATER)) {
1995 tile = FindNearestGoodCoastalTownSpot(tile, layout);
1996 if (tile == INVALID_TILE) continue;
1999 /* Make sure town can be placed here */
2000 if (TownCanBePlacedHere(tile).Failed()) continue;
2002 /* Allocate a town struct */
2003 Town *t = new Town(tile);
2005 DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2007 /* if the population is still 0 at the point, then the
2008 * placement is so bad it couldn't grow at all */
2009 if (t->cache.population > 0) return t;
2011 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2012 CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
2013 cur_company.Restore();
2014 assert(rc.Succeeded());
2016 /* We already know that we can allocate a single town when
2017 * entering this function. However, we create and delete
2018 * a town which "resets" the allocation checks. As such we
2019 * need to check again when assertions are enabled. */
2020 assert(Town::CanAllocateItem());
2021 } while (--attempts != 0);
2023 return NULL;
2026 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2029 * This function will generate a certain amount of towns, with a certain layout
2030 * It can be called from the scenario editor (i.e.: generate Random Towns)
2031 * as well as from world creation.
2032 * @param layout which towns will be set to, when created
2033 * @return true if towns have been successfully created
2035 bool GenerateTowns(TownLayout layout)
2037 uint current_number = 0;
2038 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
2039 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
2040 total = min(TownPool::MAX_SIZE, total);
2041 uint32 townnameparts;
2042 TownNames town_names;
2044 SetGeneratingWorldProgress(GWP_TOWN, total);
2046 /* First attempt will be made at creating the suggested number of towns.
2047 * Note that this is really a suggested value, not a required one.
2048 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2049 do {
2050 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
2051 IncreaseGeneratingWorldProgress(GWP_TOWN);
2052 /* Get a unique name for the town. */
2053 if (!GenerateTownName(&townnameparts, &town_names)) continue;
2054 /* try 20 times to create a random-sized town for the first loop. */
2055 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
2056 } while (--total);
2058 town_names.clear();
2060 if (current_number != 0) return true;
2062 /* If current_number is still zero at this point, it means that not a single town has been created.
2063 * So give it a last try, but now more aggressive */
2064 if (GenerateTownName(&townnameparts) &&
2065 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
2066 return true;
2069 /* If there are no towns at all and we are generating new game, bail out */
2070 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2071 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2074 return false; // we are still without a town? we failed, simply
2079 * Returns the bit corresponding to the town zone of the specified tile
2080 * @param t Town on which town zone is to be found
2081 * @param tile TileIndex where town zone needs to be found
2082 * @return the bit position of the given zone, as defined in HouseZones
2084 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2086 uint dist = DistanceSquare(tile, t->xy);
2088 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2090 HouseZonesBits smallest = HZB_TOWN_EDGE;
2091 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2092 if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2095 return smallest;
2099 * Clears tile and builds a house or house part.
2100 * @param tile tile index
2101 * @param t The town to clear the house for
2102 * @param counter of construction step
2103 * @param stage of construction (used for drawing)
2104 * @param type of house. Index into house specs array
2105 * @param random_bits required for newgrf houses
2106 * @pre house can be built here
2108 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2110 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
2112 assert(cc.Succeeded());
2114 IncreaseBuildingCount(t, type);
2115 MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2116 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2118 MarkTileDirtyByTile(tile);
2123 * Write house information into the map. For houses > 1 tile, all tiles are marked.
2124 * @param t tile index
2125 * @param town The town related to this house
2126 * @param counter of construction step
2127 * @param stage of construction (used for drawing)
2128 * @param type of house. Index into house specs array
2129 * @param random_bits required for newgrf houses
2130 * @pre house can be built here
2132 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2134 BuildingFlags size = HouseSpec::Get(type)->building_flags;
2136 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2137 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2138 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2139 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2144 * Checks if a house can be built here. Important is slope, bridge above
2145 * and ability to clear the land.
2146 * @param tile tile to check
2147 * @param noslope are slopes (foundations) allowed?
2148 * @return true iff house can be built here
2150 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2152 /* cannot build on these slopes... */
2153 Slope slope = GetTileSlope(tile);
2154 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2156 /* building under a bridge? */
2157 if (IsBridgeAbove(tile)) return false;
2159 /* can we clear the land? */
2160 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2165 * Checks if a house can be built at this tile, must have the same max z as parameter.
2166 * @param tile tile to check
2167 * @param z max z of this tile so more parts of a house are at the same height (with foundation)
2168 * @param noslope are slopes (foundations) allowed?
2169 * @return true iff house can be built here
2170 * @see CanBuildHouseHere()
2172 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2174 if (!CanBuildHouseHere(tile, noslope)) return false;
2176 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2177 if (GetTileMaxZ(tile) != z) return false;
2179 return true;
2184 * Checks if a house of size 2x2 can be built at this tile
2185 * @param tile tile, N corner
2186 * @param z maximum tile z so all tile have the same max z
2187 * @param noslope are slopes (foundations) allowed?
2188 * @return true iff house can be built
2189 * @see CheckBuildHouseSameZ()
2191 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2193 /* we need to check this tile too because we can be at different tile now */
2194 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2196 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2197 tile += TileOffsByDiagDir(d);
2198 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2201 return true;
2206 * Checks if current town layout allows building here
2207 * @param t town
2208 * @param tile tile to check
2209 * @return true iff town layout allows building here
2210 * @note see layouts
2212 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2214 /* Allow towns everywhere when we don't build roads */
2215 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2217 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2219 switch (t->layout) {
2220 case TL_2X2_GRID:
2221 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2222 break;
2224 case TL_3X3_GRID:
2225 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2226 break;
2228 default:
2229 break;
2232 return true;
2237 * Checks if current town layout allows 2x2 building here
2238 * @param t town
2239 * @param tile tile to check
2240 * @return true iff town layout allows 2x2 building here
2241 * @note see layouts
2243 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2245 /* Allow towns everywhere when we don't build roads */
2246 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2248 /* Compute relative position of tile. (Positive offsets are towards north) */
2249 TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2251 switch (t->layout) {
2252 case TL_2X2_GRID:
2253 grid_pos.x %= 3;
2254 grid_pos.y %= 3;
2255 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2256 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2257 break;
2259 case TL_3X3_GRID:
2260 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2261 break;
2263 default:
2264 break;
2267 return true;
2272 * Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout
2273 * Also, tests both building positions that occupy this tile
2274 * @param tile tile where the building should be built
2275 * @param t town
2276 * @param maxz all tiles should have the same height
2277 * @param noslope are slopes forbidden?
2278 * @param second diagdir from first tile to second tile
2280 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2282 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2284 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2285 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2287 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2288 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2289 *tile = tile2;
2290 return true;
2293 return false;
2298 * Checks if 2x2 building is allowed here, also takes into account current town layout
2299 * Also, tests all four building positions that occupy this tile
2300 * @param tile tile where the building should be built
2301 * @param t town
2302 * @param maxz all tiles should have the same height
2303 * @param noslope are slopes forbidden?
2305 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2307 TileIndex tile2 = *tile;
2309 for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2310 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2311 *tile = tile2;
2312 return true;
2314 if (d == DIAGDIR_END) break;
2315 tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2318 return false;
2323 * Tries to build a house at this tile
2324 * @param t town the house will belong to
2325 * @param tile where the house will be built
2326 * @return false iff no house can be built at this tile
2328 static bool BuildTownHouse(Town *t, TileIndex tile)
2330 /* forbidden building here by town layout */
2331 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2333 /* no house allowed at all, bail out */
2334 if (!CanBuildHouseHere(tile, false)) return false;
2336 Slope slope = GetTileSlope(tile);
2337 int maxz = GetTileMaxZ(tile);
2339 /* Get the town zone type of the current tile, as well as the climate.
2340 * This will allow to easily compare with the specs of the new house to build */
2341 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2343 /* Above snow? */
2344 int land = _settings_game.game_creation.landscape;
2345 if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2347 uint bitmask = (1 << rad) + (1 << (land + 12));
2349 /* bits 0-4 are used
2350 * bits 11-15 are used
2351 * bits 5-10 are not used. */
2352 HouseID houses[NUM_HOUSES];
2353 uint num = 0;
2354 uint probs[NUM_HOUSES];
2355 uint probability_max = 0;
2357 /* Generate a list of all possible houses that can be built. */
2358 for (uint i = 0; i < NUM_HOUSES; i++) {
2359 const HouseSpec *hs = HouseSpec::Get(i);
2361 /* Verify that the candidate house spec matches the current tile status */
2362 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2364 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2365 if (hs->class_id != HOUSE_NO_CLASS) {
2366 /* id_count is always <= class_count, so it doesn't need to be checked */
2367 if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2368 } else {
2369 /* If the house has no class, check id_count instead */
2370 if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2373 /* Without NewHouses, all houses have probability '1' */
2374 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2375 probability_max += cur_prob;
2376 probs[num] = cur_prob;
2377 houses[num++] = (HouseID)i;
2380 TileIndex baseTile = tile;
2382 while (probability_max > 0) {
2383 /* Building a multitile building can change the location of tile.
2384 * The building would still be built partially on that tile, but
2385 * its northern tile would be elsewhere. However, if the callback
2386 * fails we would be basing further work from the changed tile.
2387 * So a next 1x1 tile building could be built on the wrong tile. */
2388 tile = baseTile;
2390 uint r = RandomRange(probability_max);
2391 uint i;
2392 for (i = 0; i < num; i++) {
2393 if (probs[i] > r) break;
2394 r -= probs[i];
2397 HouseID house = houses[i];
2398 probability_max -= probs[i];
2400 /* remove tested house from the set */
2401 num--;
2402 houses[i] = houses[num];
2403 probs[i] = probs[num];
2405 const HouseSpec *hs = HouseSpec::Get(house);
2407 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
2408 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2409 continue;
2412 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2414 /* Special houses that there can be only one of. */
2415 uint oneof = 0;
2417 if (hs->building_flags & BUILDING_IS_CHURCH) {
2418 SetBit(oneof, TOWN_HAS_CHURCH);
2419 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2420 SetBit(oneof, TOWN_HAS_STADIUM);
2423 if (t->flags & oneof) continue;
2425 /* Make sure there is no slope? */
2426 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2427 if (noslope && slope != SLOPE_FLAT) continue;
2429 if (hs->building_flags & TILE_SIZE_2x2) {
2430 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2431 } else if (hs->building_flags & TILE_SIZE_2x1) {
2432 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2433 } else if (hs->building_flags & TILE_SIZE_1x2) {
2434 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2435 } else {
2436 /* 1x1 house checks are already done */
2439 byte random_bits = Random();
2441 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
2442 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2443 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2446 /* build the house */
2447 t->cache.num_houses++;
2449 /* Special houses that there can be only one of. */
2450 t->flags |= oneof;
2452 byte construction_counter = 0;
2453 byte construction_stage = 0;
2455 if (_generating_world || _game_mode == GM_EDITOR) {
2456 uint32 r = Random();
2458 construction_stage = TOWN_HOUSE_COMPLETED;
2459 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2461 if (construction_stage == TOWN_HOUSE_COMPLETED) {
2462 ChangePopulation(t, hs->population);
2463 } else {
2464 construction_counter = GB(r, 2, 2);
2468 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2469 UpdateTownRadius(t);
2470 UpdateTownCargoes(t, tile);
2472 return true;
2475 return false;
2479 * Update data structures when a house is removed
2480 * @param tile Tile of the house
2481 * @param t Town owning the house
2482 * @param house House type
2484 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2486 assert(IsTileType(tile, MP_HOUSE));
2487 DecreaseBuildingCount(t, house);
2488 DoClearSquare(tile);
2489 DeleteAnimatedTile(tile);
2491 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2495 * Determines if a given HouseID is part of a multitile house.
2496 * The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
2498 * @param house Is changed to the HouseID of the north tile of the same house
2499 * @return TileDiff from the tile of the given HouseID to the north tile
2501 TileIndexDiff GetHouseNorthPart(HouseID &house)
2503 if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2504 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2505 house--;
2506 return TileDiffXY(-1, 0);
2507 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2508 house--;
2509 return TileDiffXY(0, -1);
2510 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2511 house -= 2;
2512 return TileDiffXY(-1, 0);
2513 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2514 house -= 3;
2515 return TileDiffXY(-1, -1);
2518 return 0;
2521 void ClearTownHouse(Town *t, TileIndex tile)
2523 assert(IsTileType(tile, MP_HOUSE));
2525 HouseID house = GetHouseType(tile);
2527 /* need to align the tile to point to the upper left corner of the house */
2528 tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2530 const HouseSpec *hs = HouseSpec::Get(house);
2532 /* Remove population from the town if the house is finished. */
2533 if (IsHouseCompleted(tile)) {
2534 ChangePopulation(t, -hs->population);
2537 t->cache.num_houses--;
2539 /* Clear flags for houses that only may exist once/town. */
2540 if (hs->building_flags & BUILDING_IS_CHURCH) {
2541 ClrBit(t->flags, TOWN_HAS_CHURCH);
2542 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2543 ClrBit(t->flags, TOWN_HAS_STADIUM);
2546 /* Do the actual clearing of tiles */
2547 uint eflags = hs->building_flags;
2548 DoClearTownHouseHelper(tile, t, house);
2549 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2550 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2551 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2553 UpdateTownRadius(t);
2555 /* Update cargo acceptance. */
2556 UpdateTownCargoes(t, tile);
2560 * Rename a town (server-only).
2561 * @param tile unused
2562 * @param flags type of operation
2563 * @param p1 town ID to rename
2564 * @param p2 unused
2565 * @param text the new name or an empty string when resetting to the default
2566 * @return the cost of this operation or an error
2568 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2570 Town *t = Town::GetIfValid(p1);
2571 if (t == NULL) return CMD_ERROR;
2573 bool reset = StrEmpty(text);
2575 if (!reset) {
2576 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
2577 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2580 if (flags & DC_EXEC) {
2581 free(t->name);
2582 t->name = reset ? NULL : stredup(text);
2584 t->UpdateVirtCoord();
2585 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
2586 UpdateAllStationVirtCoords();
2588 return CommandCost();
2592 * Determines the first cargo with a certain town effect
2593 * @param effect Town effect of interest
2594 * @return first active cargo slot with that effect
2596 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
2598 const CargoSpec *cs;
2599 FOR_ALL_CARGOSPECS(cs) {
2600 if (cs->town_effect == effect) return cs;
2602 return NULL;
2605 static void UpdateTownGrowRate(Town *t);
2608 * Change the cargo goal of a town.
2609 * @param tile Unused.
2610 * @param flags Type of operation.
2611 * @param p1 various bitstuffed elements
2612 * - p1 = (bit 0 - 15) - Town ID to cargo game of.
2613 * - p1 = (bit 16 - 23) - TownEffect to change the game of.
2614 * @param p2 The new goal value.
2615 * @param text Unused.
2616 * @return Empty cost or an error.
2618 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2620 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2622 TownEffect te = (TownEffect)GB(p1, 16, 8);
2623 if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2625 uint16 index = GB(p1, 0, 16);
2626 Town *t = Town::GetIfValid(index);
2627 if (t == NULL) return CMD_ERROR;
2629 /* Validate if there is a cargo which is the requested TownEffect */
2630 const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2631 if (cargo == NULL) return CMD_ERROR;
2633 if (flags & DC_EXEC) {
2634 t->goal[te] = p2;
2635 UpdateTownGrowRate(t);
2636 InvalidateWindowData(WC_TOWN_VIEW, index);
2639 return CommandCost();
2643 * Set a custom text in the Town window.
2644 * @param tile Unused.
2645 * @param flags Type of operation.
2646 * @param p1 Town ID to change the text of.
2647 * @param p2 Unused.
2648 * @param text The new text (empty to remove the text).
2649 * @return Empty cost or an error.
2651 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2653 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2654 Town *t = Town::GetIfValid(p1);
2655 if (t == NULL) return CMD_ERROR;
2657 if (flags & DC_EXEC) {
2658 free(t->text);
2659 t->text = StrEmpty(text) ? NULL : stredup(text);
2660 InvalidateWindowData(WC_TOWN_VIEW, p1);
2663 return CommandCost();
2667 * Change the growth rate of the town.
2668 * @param tile Unused.
2669 * @param flags Type of operation.
2670 * @param p1 Town ID to cargo game of.
2671 * @param p2 Amount of days between growth, or TOWN_GROW_RATE_CUSTOM_NONE, or 0 to reset custom growth rate.
2672 * @param text Unused.
2673 * @return Empty cost or an error.
2675 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2677 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2678 if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0 && p2 != TOWN_GROW_RATE_CUSTOM_NONE) return CMD_ERROR;
2679 if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2681 Town *t = Town::GetIfValid(p1);
2682 if (t == NULL) return CMD_ERROR;
2684 if (flags & DC_EXEC) {
2685 if (p2 == 0) {
2686 /* Clear TOWN_GROW_RATE_CUSTOM, UpdateTownGrowRate will determine a proper value */
2687 t->growth_rate = 0;
2688 } else {
2689 uint old_rate = t->growth_rate & ~TOWN_GROW_RATE_CUSTOM;
2690 if (t->grow_counter >= old_rate) {
2691 /* This also catches old_rate == 0 */
2692 t->grow_counter = p2;
2693 } else {
2694 /* Scale grow_counter, so half finished houses stay half finished */
2695 t->grow_counter = t->grow_counter * p2 / old_rate;
2697 t->growth_rate = p2 | TOWN_GROW_RATE_CUSTOM;
2699 UpdateTownGrowRate(t);
2700 InvalidateWindowData(WC_TOWN_VIEW, p1);
2703 return CommandCost();
2707 * Expand a town (scenario editor only).
2708 * @param tile Unused.
2709 * @param flags Type of operation.
2710 * @param p1 Town ID to expand.
2711 * @param p2 Amount to grow, or 0 to grow a random size up to the current amount of houses.
2712 * @param text Unused.
2713 * @return Empty cost or an error.
2715 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2717 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2718 Town *t = Town::GetIfValid(p1);
2719 if (t == NULL) return CMD_ERROR;
2721 if (flags & DC_EXEC) {
2722 /* The more houses, the faster we grow */
2723 if (p2 == 0) {
2724 uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2725 t->cache.num_houses += amount;
2726 UpdateTownRadius(t);
2728 uint n = amount * 10;
2729 do GrowTown(t); while (--n);
2731 t->cache.num_houses -= amount;
2732 } else {
2733 for (; p2 > 0; p2--) {
2734 /* Try several times to grow, as we are really suppose to grow */
2735 for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2738 UpdateTownRadius(t);
2740 UpdateTownMaxPass(t);
2743 return CommandCost();
2747 * Delete a town (scenario editor or worldgen only).
2748 * @param tile Unused.
2749 * @param flags Type of operation.
2750 * @param p1 Town ID to delete.
2751 * @param p2 Unused.
2752 * @param text Unused.
2753 * @return Empty cost or an error.
2755 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2757 if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2758 Town *t = Town::GetIfValid(p1);
2759 if (t == NULL) return CMD_ERROR;
2761 /* Stations refer to towns. */
2762 const Station *st;
2763 FOR_ALL_STATIONS(st) {
2764 if (st->town == t) {
2765 /* Non-oil rig stations are always a problem. */
2766 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2767 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2768 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2769 if (ret.Failed()) return ret;
2773 /* Depots refer to towns. */
2774 const Depot *d;
2775 FOR_ALL_DEPOTS(d) {
2776 if (d->town == t) return CMD_ERROR;
2779 /* Check all tiles for town ownership. */
2780 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2781 bool try_clear = false;
2782 switch (GetTileType(tile)) {
2783 case MP_ROAD:
2784 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2785 break;
2787 case MP_TUNNELBRIDGE:
2788 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
2789 break;
2791 case MP_HOUSE:
2792 try_clear = GetTownIndex(tile) == t->index;
2793 break;
2795 case MP_INDUSTRY:
2796 try_clear = Industry::GetByTile(tile)->town == t;
2797 break;
2799 case MP_OBJECT:
2800 if (Town::GetNumItems() == 1) {
2801 /* No towns will be left, remove it! */
2802 try_clear = true;
2803 } else {
2804 Object *o = Object::GetByTile(tile);
2805 if (o->town == t) {
2806 if (o->type == OBJECT_STATUE) {
2807 /* Statue... always remove. */
2808 try_clear = true;
2809 } else {
2810 /* Tell to find a new town. */
2811 if (flags & DC_EXEC) o->town = NULL;
2815 break;
2817 default:
2818 break;
2820 if (try_clear) {
2821 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2822 if (ret.Failed()) return ret;
2826 /* The town destructor will delete the other things related to the town. */
2827 if (flags & DC_EXEC) delete t;
2829 return CommandCost();
2833 * Factor in the cost of each town action.
2834 * @see TownActions
2836 const byte _town_action_costs[TACT_COUNT] = {
2837 2, 4, 9, 35, 48, 53, 117, 175
2840 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2842 if (flags & DC_EXEC) {
2843 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2845 return CommandCost();
2848 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2850 if (flags & DC_EXEC) {
2851 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2853 return CommandCost();
2856 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2858 if (flags & DC_EXEC) {
2859 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2861 return CommandCost();
2864 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2866 /* Check if the company is allowed to fund new roads. */
2867 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
2869 if (flags & DC_EXEC) {
2870 t->road_build_months = 6;
2872 char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2873 SetDParam(0, _current_company);
2874 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2876 char *cn = stredup(company_name);
2877 SetDParam(0, t->index);
2878 SetDParamStr(1, cn);
2880 AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
2881 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2882 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2884 return CommandCost();
2888 * Check whether the land can be cleared.
2889 * @param tile Tile to check.
2890 * @return The tile can be cleared.
2892 static bool TryClearTile(TileIndex tile)
2894 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2895 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
2896 cur_company.Restore();
2897 return r.Succeeded();
2900 /** Structure for storing data while searching the best place to build a statue. */
2901 struct StatueBuildSearchData {
2902 TileIndex best_position; ///< Best position found so far.
2903 int tile_count; ///< Number of tiles tried.
2905 StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
2909 * Search callback function for #TownActionBuildStatue.
2910 * @param tile Tile on which to perform the search.
2911 * @param user_data Reference to the statue search data.
2912 * @return Result of the test.
2914 static bool SearchTileForStatue(TileIndex tile, void *user_data)
2916 static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
2918 StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
2919 statue_data->tile_count++;
2921 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2922 if (IsSteepSlope(GetTileSlope(tile))) return false;
2923 /* Don't build statues under bridges. */
2924 if (IsBridgeAbove(tile)) return false;
2926 /* A clear-able open space is always preferred. */
2927 if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
2928 statue_data->best_position = tile;
2929 return true;
2932 bool house = IsTileType(tile, MP_HOUSE);
2934 /* Searching inside the inner circle. */
2935 if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
2936 /* Save first house in inner circle. */
2937 if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
2938 statue_data->best_position = tile;
2941 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2942 return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
2945 /* Searching outside the circle, just pick the first possible spot. */
2946 statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
2947 return house && TryClearTile(tile);
2951 * Perform a 9x9 tiles circular search from the center of the town
2952 * in order to find a free tile to place a statue
2953 * @param t town to search in
2954 * @param flags Used to check if the statue must be built or not.
2955 * @return Empty cost or an error.
2957 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
2959 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
2961 TileIndex tile = t->xy;
2962 StatueBuildSearchData statue_data(INVALID_TILE, 0);
2963 if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
2965 if (flags & DC_EXEC) {
2966 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2967 DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
2968 cur_company.Restore();
2969 BuildObject(OBJECT_STATUE, statue_data.best_position, _current_company, t);
2970 SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
2971 MarkTileDirtyByTile(statue_data.best_position);
2973 return CommandCost();
2976 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
2978 /* Check if it's allowed to buy the rights */
2979 if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
2981 if (flags & DC_EXEC) {
2982 /* Build next tick */
2983 t->grow_counter = 1;
2984 /* And grow for 3 months */
2985 t->fund_buildings_months = 3;
2987 /* Enable growth (also checking GameScript's opinion) */
2988 UpdateTownGrowRate(t);
2990 SetWindowDirty(WC_TOWN_VIEW, t->index);
2992 return CommandCost();
2995 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
2997 /* Check if it's allowed to buy the rights */
2998 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
3000 if (flags & DC_EXEC) {
3001 t->exclusive_counter = 12;
3002 t->exclusivity = _current_company;
3004 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
3006 SetWindowClassesDirty(WC_STATION_VIEW);
3008 /* Spawn news message */
3009 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
3010 cni->FillData(Company::Get(_current_company));
3011 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3012 SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
3013 SetDParam(2, t->index);
3014 SetDParamStr(3, cni->company_name);
3015 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
3016 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3017 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3019 return CommandCost();
3022 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
3024 if (flags & DC_EXEC) {
3025 if (Chance16(1, 14)) {
3026 /* set as unwanted for 6 months */
3027 t->unwanted[_current_company] = 6;
3029 /* set all close by station ratings to 0 */
3030 Station *st;
3031 FOR_ALL_STATIONS(st) {
3032 if (st->town == t && st->owner == _current_company) {
3033 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
3037 /* only show error message to the executing player. All errors are handled command.c
3038 * but this is special, because it can only 'fail' on a DC_EXEC */
3039 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3041 /* decrease by a lot!
3042 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3043 * be independent of any cheat settings
3045 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3046 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3047 t->UpdateVirtCoord();
3048 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3050 } else {
3051 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3054 return CommandCost();
3057 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3058 static TownActionProc * const _town_action_proc[] = {
3059 TownActionAdvertiseSmall,
3060 TownActionAdvertiseMedium,
3061 TownActionAdvertiseLarge,
3062 TownActionRoadRebuild,
3063 TownActionBuildStatue,
3064 TownActionFundBuildings,
3065 TownActionBuyRights,
3066 TownActionBribe
3070 * Get a list of available actions to do at a town.
3071 * @param nump if not NULL add put the number of available actions in it
3072 * @param cid the company that is querying the town
3073 * @param t the town that is queried
3074 * @return bitmasked value of enabled actions
3076 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
3078 int num = 0;
3079 TownActions buttons = TACT_NONE;
3081 /* Spectators and unwanted have no options */
3082 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3084 /* Things worth more than this are not shown */
3085 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3087 /* Check the action bits for validity and
3088 * if they are valid add them */
3089 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3090 const TownActions cur = (TownActions)(1 << i);
3092 /* Is the company not able to bribe ? */
3093 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3095 /* Is the company not able to buy exclusive rights ? */
3096 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3098 /* Is the company not able to fund buildings ? */
3099 if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3101 /* Is the company not able to fund local road reconstruction? */
3102 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3104 /* Is the company not able to build a statue ? */
3105 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3107 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3108 buttons |= cur;
3109 num++;
3114 if (nump != NULL) *nump = num;
3115 return buttons;
3119 * Do a town action.
3120 * This performs an action such as advertising, building a statue, funding buildings,
3121 * but also bribing the town-council
3122 * @param tile unused
3123 * @param flags type of operation
3124 * @param p1 town to do the action at
3125 * @param p2 action to perform, @see _town_action_proc for the list of available actions
3126 * @param text unused
3127 * @return the cost of this operation or an error
3129 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3131 Town *t = Town::GetIfValid(p1);
3132 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3134 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
3136 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3138 CommandCost ret = _town_action_proc[p2](t, flags);
3139 if (ret.Failed()) return ret;
3141 if (flags & DC_EXEC) {
3142 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
3145 return cost;
3148 static void UpdateTownRating(Town *t)
3150 /* Increase company ratings if they're low */
3151 const Company *c;
3152 FOR_ALL_COMPANIES(c) {
3153 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3154 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3158 const Station *st;
3159 FOR_ALL_STATIONS(st) {
3160 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3161 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3162 if (Company::IsValidID(st->owner)) {
3163 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3164 t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3166 } else {
3167 if (Company::IsValidID(st->owner)) {
3168 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3169 t->ratings[st->owner] = max(new_rating, INT16_MIN);
3175 /* clamp all ratings to valid values */
3176 for (uint i = 0; i < MAX_COMPANIES; i++) {
3177 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3180 t->UpdateVirtCoord();
3181 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3184 static void UpdateTownGrowRate(Town *t)
3186 ClrBit(t->flags, TOWN_IS_GROWING);
3187 SetWindowDirty(WC_TOWN_VIEW, t->index);
3189 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3191 if (t->fund_buildings_months == 0) {
3192 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3193 for (int i = TE_BEGIN; i < TE_END; i++) {
3194 switch (t->goal[i]) {
3195 case TOWN_GROWTH_WINTER:
3196 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3197 break;
3198 case TOWN_GROWTH_DESERT:
3199 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3200 break;
3201 default:
3202 if (t->goal[i] > t->received[i].old_act) return;
3203 break;
3208 if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
3209 if (t->growth_rate != TOWN_GROW_RATE_CUSTOM_NONE) SetBit(t->flags, TOWN_IS_GROWING);
3210 SetWindowDirty(WC_TOWN_VIEW, t->index);
3211 return;
3215 * Towns are processed every TOWN_GROWTH_TICKS ticks, and this is the
3216 * number of times towns are processed before a new building is built.
3218 static const uint16 _grow_count_values[2][6] = {
3219 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3220 { 320, 420, 300, 220, 160, 100 } // Normal values
3223 int n = 0;
3225 const Station *st;
3226 FOR_ALL_STATIONS(st) {
3227 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3228 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3229 n++;
3234 uint16 m;
3236 if (t->fund_buildings_months != 0) {
3237 m = _grow_count_values[0][min(n, 5)];
3238 } else {
3239 m = _grow_count_values[1][min(n, 5)];
3240 if (n == 0 && !Chance16(1, 12)) return;
3243 /* Use the normal growth rate values if new buildings have been funded in
3244 * this town and the growth rate is set to none. */
3245 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3247 m >>= growth_multiplier;
3248 if (t->larger_town) m /= 2;
3250 t->growth_rate = m / (t->cache.num_houses / 50 + 1);
3251 t->grow_counter = min(t->growth_rate, t->grow_counter);
3253 SetBit(t->flags, TOWN_IS_GROWING);
3254 SetWindowDirty(WC_TOWN_VIEW, t->index);
3257 static void UpdateTownAmounts(Town *t)
3259 for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3260 for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3261 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3263 SetWindowDirty(WC_TOWN_VIEW, t->index);
3266 static void UpdateTownUnwanted(Town *t)
3268 const Company *c;
3270 FOR_ALL_COMPANIES(c) {
3271 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3276 * Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
3277 * @param tile The tile where the station shall be constructed.
3278 * @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
3279 * @return Succeeded or failed command.
3281 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
3283 return CommandCost();
3287 * Return the town closest to the given tile within \a threshold.
3288 * @param tile Starting point of the search.
3289 * @param threshold Biggest allowed distance to the town.
3290 * @return Closest town to \a tile within \a threshold, or \c NULL if there is no such town.
3292 * @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
3294 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
3296 Town *t;
3297 uint best = threshold;
3298 Town *best_town = NULL;
3300 FOR_ALL_TOWNS(t) {
3301 uint dist = DistanceManhattan(tile, t->xy);
3302 if (dist < best) {
3303 best = dist;
3304 best_town = t;
3308 return best_town;
3312 * Return the town closest (in distance or ownership) to a given tile, within a given threshold.
3313 * @param tile Starting point of the search.
3314 * @param threshold Biggest allowed distance to the town.
3315 * @return Closest town to \a tile within \a threshold, or \c NULL if there is no such town.
3317 * @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
3319 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3321 switch (GetTileType(tile)) {
3322 case MP_ROAD:
3323 if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3325 if (!HasTownOwnedRoad(tile)) {
3326 TownID tid = GetTownIndex(tile);
3328 if (tid == (TownID)INVALID_TOWN) {
3329 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3330 if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3331 assert(Town::GetNumItems() == 0);
3332 return NULL;
3335 assert(Town::IsValidID(tid));
3336 Town *town = Town::Get(tid);
3338 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
3340 return town;
3342 FALLTHROUGH;
3344 case MP_HOUSE:
3345 return Town::GetByTile(tile);
3347 default:
3348 return CalcClosestTownFromTile(tile, threshold);
3352 static bool _town_rating_test = false; ///< If \c true, town rating is in test-mode.
3353 static SmallMap<const Town *, int, 4> _town_test_ratings; ///< Map of towns to modified ratings, while in town rating test-mode.
3356 * Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
3357 * The function is safe to use in nested calls.
3358 * @param mode Test mode switch (\c true means go to test-mode, \c false means leave test-mode).
3360 void SetTownRatingTestMode(bool mode)
3362 static int ref_count = 0; // Number of times test-mode is switched on.
3363 if (mode) {
3364 if (ref_count == 0) {
3365 _town_test_ratings.Clear();
3367 ref_count++;
3368 } else {
3369 assert(ref_count > 0);
3370 ref_count--;
3372 _town_rating_test = !(ref_count == 0);
3376 * Get the rating of a town for the #_current_company.
3377 * @param t Town to get the rating from.
3378 * @return Rating of the current company in the given town.
3380 static int GetRating(const Town *t)
3382 if (_town_rating_test) {
3383 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3384 if (it != _town_test_ratings.End()) {
3385 return it->second;
3388 return t->ratings[_current_company];
3392 * Changes town rating of the current company
3393 * @param t Town to affect
3394 * @param add Value to add
3395 * @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be achievable with this change.
3396 * @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
3398 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3400 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3401 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3402 !Company::IsValidID(_current_company) ||
3403 (_cheats.magic_bulldozer.value && add < 0)) {
3404 return;
3407 int rating = GetRating(t);
3408 if (add < 0) {
3409 if (rating > max) {
3410 rating += add;
3411 if (rating < max) rating = max;
3413 } else {
3414 if (rating < max) {
3415 rating += add;
3416 if (rating > max) rating = max;
3419 if (_town_rating_test) {
3420 _town_test_ratings[t] = rating;
3421 } else {
3422 SetBit(t->have_ratings, _current_company);
3423 t->ratings[_current_company] = rating;
3424 t->UpdateVirtCoord();
3425 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3430 * Does the town authority allow the (destructive) action of the current company?
3431 * @param flags Checking flags of the command.
3432 * @param t Town that must allow the company action.
3433 * @param type Type of action that is wanted.
3434 * @return A succeeded command if the action is allowed, a failed command if it is not allowed.
3436 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
3438 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3439 if (t == NULL || !Company::IsValidID(_current_company) ||
3440 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
3441 return CommandCost();
3444 /* minimum rating needed to be allowed to remove stuff */
3445 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3446 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3447 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
3448 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
3449 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
3452 /* check if you're allowed to remove the road/bridge/tunnel
3453 * owned by a town no removal if rating is lower than ... depends now on
3454 * difficulty setting. Minimum town rating selected by difficulty level
3456 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3458 if (GetRating(t) < needed) {
3459 SetDParam(0, t->index);
3460 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3463 return CommandCost();
3466 void TownsMonthlyLoop()
3468 Town *t;
3470 FOR_ALL_TOWNS(t) {
3471 if (t->road_build_months != 0) t->road_build_months--;
3473 if (t->exclusive_counter != 0) {
3474 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3477 UpdateTownAmounts(t);
3478 UpdateTownRating(t);
3479 UpdateTownGrowRate(t);
3480 UpdateTownUnwanted(t);
3481 UpdateTownCargoes(t);
3484 UpdateTownCargoBitmap();
3487 void TownsYearlyLoop()
3489 /* Increment house ages */
3490 for (TileIndex t = 0; t < MapSize(); t++) {
3491 if (!IsTileType(t, MP_HOUSE)) continue;
3492 IncrementHouseAge(t);
3496 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3498 if (AutoslopeEnabled()) {
3499 HouseID house = GetHouseType(tile);
3500 GetHouseNorthPart(house); // modifies house to the ID of the north tile
3501 const HouseSpec *hs = HouseSpec::Get(house);
3503 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3504 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3505 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3506 bool allow_terraform = true;
3508 /* Call the autosloping callback per tile, not for the whole building at once. */
3509 house = GetHouseType(tile);
3510 hs = HouseSpec::Get(house);
3511 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
3512 /* If the callback fails, allow autoslope. */
3513 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3514 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3517 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3521 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3524 /** Tile callback functions for a town */
3525 extern const TileTypeProcs _tile_type_town_procs = {
3526 DrawTile_Town, // draw_tile_proc
3527 GetSlopePixelZ_Town, // get_slope_z_proc
3528 ClearTile_Town, // clear_tile_proc
3529 AddAcceptedCargo_Town, // add_accepted_cargo_proc
3530 GetTileDesc_Town, // get_tile_desc_proc
3531 GetTileTrackStatus_Town, // get_tile_track_status_proc
3532 NULL, // click_tile_proc
3533 AnimateTile_Town, // animate_tile_proc
3534 TileLoop_Town, // tile_loop_proc
3535 ChangeTileOwner_Town, // change_tile_owner_proc
3536 AddProducedCargo_Town, // add_produced_cargo_proc
3537 NULL, // vehicle_enter_tile_proc
3538 GetFoundation_Town, // get_foundation_proc
3539 TerraformTile_Town, // terraform_tile_proc
3543 HouseSpec _house_specs[NUM_HOUSES];
3545 void ResetHouses()
3547 memset(&_house_specs, 0, sizeof(_house_specs));
3548 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3550 /* Reset any overrides that have been set. */
3551 _house_mngr.ResetOverride();