Remove second template parameter from class GUIList
[openttd/fttd.git] / src / town_cmd.cpp
blobdc3820809726c159b9e9ecabd301004a13ba2dfe
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"
14 #include <bitset>
16 #include "road_internal.h" /* Cleaning up road bits */
17 #include "road_cmd.h"
18 #include "landscape.h"
19 #include "viewport_func.h"
20 #include "cmd_helper.h"
21 #include "command_func.h"
22 #include "industry.h"
23 #include "station_base.h"
24 #include "company_base.h"
25 #include "news_func.h"
26 #include "error.h"
27 #include "object.h"
28 #include "genworld.h"
29 #include "newgrf_debug.h"
30 #include "newgrf_house.h"
31 #include "newgrf_text.h"
32 #include "autoslope.h"
33 #include "map/zoneheight.h"
34 #include "map/road.h"
35 #include "map/tunnelbridge.h"
36 #include "strings_func.h"
37 #include "window_func.h"
38 #include "string.h"
39 #include "newgrf_cargo.h"
40 #include "cheat_type.h"
41 #include "animated_tile_func.h"
42 #include "date_func.h"
43 #include "subsidy_func.h"
44 #include "core/pool_func.hpp"
45 #include "town.h"
46 #include "townnamegen.h"
47 #include "townname_func.h"
48 #include "core/random_func.hpp"
49 #include "core/backup_type.hpp"
50 #include "depot_base.h"
51 #include "map/object.h"
52 #include "object_base.h"
53 #include "ai/ai.hpp"
54 #include "game/game.hpp"
55 #include "bridge.h"
56 #include "map/util.h"
57 #include "zoom_func.h"
59 #include "table/strings.h"
60 #include "table/town_land.h"
62 TownID _new_town_id;
63 uint32 _town_cargoes_accepted; ///< Bitmap of all cargoes accepted by houses.
65 /* Initialize the town-pool */
66 template<> Town::Pool Town::PoolItem::pool ("Town");
67 INSTANTIATE_POOL_METHODS(Town)
69 Town::~Town()
71 free(this->name);
72 free(this->text);
74 if (CleaningPool()) return;
76 /* Delete town authority window
77 * and remove from list of sorted towns */
78 DeleteWindowById(WC_TOWN_VIEW, this->index);
80 /* Delete from town set */
81 this->remove_from_tileset();
83 /* Check no industry is related to us. */
84 const Industry *i;
85 FOR_ALL_INDUSTRIES(i) assert(i->town != this);
87 /* ... and no object is related to us. */
88 const Object *o;
89 FOR_ALL_OBJECTS(o) assert(o->town != this);
91 /* Check no tile is related to us. */
92 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
93 if (IsHouseTile(tile)) {
94 assert(GetTownIndex(tile) != this->index);
95 } else {
96 switch (GetTileType(tile)) {
97 case TT_MISC:
98 if (IsTunnelTile(tile)) {
99 assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile) != this);
100 break;
102 if (!IsLevelCrossingTile(tile)) break;
103 /* fall through */
104 case TT_ROAD:
105 assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
106 break;
108 default:
109 break;
114 /* Clear the persistent storage list. */
115 this->psa_list.clear();
117 DeleteSubsidyWith(ST_TOWN, this->index);
118 DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
119 CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
120 MarkWholeScreenDirty();
125 * Invalidating of the "nearest town cache" has to be done
126 * after removing item from the pool.
127 * @param index index of deleted item
129 void Town::PostDestructor(size_t index)
131 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
132 InvalidateWindowData(WC_SELECT_TOWN, 0);
133 UpdateNearestTownForRoadTiles(false);
135 /* Give objects a new home! */
136 Object *o;
137 FOR_ALL_OBJECTS(o) {
138 if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile);
143 * Return a random valid town.
144 * @return random town, NULL if there are no towns
146 /* static */ Town *Town::GetRandom()
148 if (Town::GetNumItems() == 0) return NULL;
149 int num = RandomRange((uint16)Town::GetNumItems());
150 size_t index = MAX_UVALUE(size_t);
152 while (num >= 0) {
153 num--;
154 index++;
156 /* Make sure we have a valid town */
157 while (!Town::IsValidID(index)) {
158 index++;
159 assert(index < Town::GetPoolSize());
163 return Town::Get(index);
167 * Get the cost for removing this house
168 * @return the cost (inflation corrected etc)
170 Money HouseSpec::GetRemovalCost() const
172 return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
175 static bool BuildTownHouse(Town *t, TileIndex tile);
176 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
178 static void TownDrawHouseLift(const TileInfo *ti)
180 AddChildSpriteScreen (ti->vd, SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
183 typedef void TownDrawTileProc(const TileInfo *ti);
184 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
185 TownDrawHouseLift
189 * Return a random direction
191 * @return a random direction
193 static inline DiagDirection RandomDiagDir()
195 return (DiagDirection)(3 & Random());
199 * House Tile drawing handler.
200 * Part of the tile loop process
201 * @param ti TileInfo of the tile to draw
203 static void DrawTile_Town(TileInfo *ti)
205 HouseID house_id = GetHouseType(ti->tile);
207 if (house_id >= NEW_HOUSE_OFFSET) {
208 /* Houses don't necessarily need new graphics. If they don't have a
209 * spritegroup associated with them, then the sprite for the substitute
210 * house id is drawn instead. */
211 if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
212 DrawNewHouseTile(ti, house_id);
213 return;
214 } else {
215 house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
219 /* Retrieve pointer to the draw town tile struct */
220 const DrawBuildingsTileStruct *dcts = town_draw_tile_data[house_id][TileHash2Bit(ti->x, ti->y)][GetHouseBuildingStage(ti->tile)];
222 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
224 DrawGroundSprite (ti, dcts->ground.sprite, dcts->ground.pal);
226 /* If houses are invisible, do not draw the upper part */
227 if (IsInvisibilitySet(TO_HOUSES)) return;
229 /* Add a house on top of the ground? */
230 SpriteID image = dcts->building.sprite;
231 if (image != 0) {
232 AddSortableSpriteToDraw (ti->vd, image, dcts->building.pal,
233 ti->x + dcts->subtile_x,
234 ti->y + dcts->subtile_y,
235 dcts->width,
236 dcts->height,
237 dcts->dz,
238 ti->z,
239 IsTransparencySet(TO_HOUSES)
242 if (IsTransparencySet(TO_HOUSES)) return;
246 int proc = dcts->draw_proc - 1;
248 if (proc >= 0) _town_draw_tile_procs[proc](ti);
252 static void DrawOldHouseTileInGUI (BlitArea *dpi, int x, int y,
253 HouseID house_id, bool ground)
255 /* Retrieve pointer to the draw town tile struct */
256 const DrawBuildingsTileStruct *dcts = town_draw_tile_data[house_id][0][TOWN_HOUSE_COMPLETED];
257 if (ground) {
258 /* Draw the ground sprite */
259 DrawSprite (dpi, dcts->ground.sprite, dcts->ground.pal, x, y);
260 } else {
261 /* Add a house on top of the ground? */
262 if (dcts->building.sprite != 0) {
263 DrawSprite (dpi, dcts->building.sprite, dcts->building.pal,
264 x + ScaleGUITrad (2 * (dcts->subtile_y - dcts->subtile_x)),
265 y + ScaleGUITrad (dcts->subtile_x + dcts->subtile_y));
267 /* Draw the lift */
268 if (dcts->draw_proc == 1) DrawSprite (dpi, SPR_LIFT, PAL_NONE, x - 18, y + 7);
273 * Draw image of a house. Image will be centered between the \c left and the \c right and verticaly aligned to the \c bottom.
275 * @param house_id house type
276 * @param dpi area to draw on
277 * @param left left bound of the drawing area
278 * @param top top bound of the drawing area
279 * @param right right bound of the drawing area
280 * @param bottom bottom bound of the drawing area
282 void DrawHouseImage (HouseID house_id, BlitArea *dpi,
283 int left, int top, int right, int bottom)
285 BlitArea tmp_dpi;
286 if (!InitBlitArea (dpi, &tmp_dpi, left, top, right - left + 1, bottom - top + 1)) return;
288 const HouseSpec *hs = HouseSpec::Get(house_id);
290 /* sprites are relative to the topmost pixel of the ground tile */
291 uint x = (right - left + 1) / 2 - ScaleGUITrad (1);
292 uint y = bottom - top + 1 - ScaleGUITrad (TILE_PIXELS - 1);
293 uint half_tile_offset = ScaleGUITrad (TILE_PIXELS / 2);
294 if (hs->building_flags & TILE_SIZE_1x2) x -= half_tile_offset;
295 if (hs->building_flags & TILE_SIZE_2x1) x += half_tile_offset;
296 if (hs->building_flags & BUILDING_HAS_2_TILES) y -= half_tile_offset;
297 if (hs->building_flags & BUILDING_HAS_4_TILES) y -= half_tile_offset;
299 bool new_house = false;
300 if (house_id >= NEW_HOUSE_OFFSET) {
301 /* Houses don't necessarily need new graphics. If they don't
302 * have a spritegroup associated with them, then the sprite
303 * for the substitute house id is drawn instead. */
304 if (hs->grf_prop.spritegroup[0] != NULL) {
305 new_house = true;
306 } else {
307 house_id = hs->grf_prop.subst_id;
311 uint num_row = (hs->building_flags & BUILDING_2_TILES_X) ? 2 : 1;
312 uint num_col = (hs->building_flags & BUILDING_2_TILES_Y) ? 2 : 1;
314 Point pt[4];
315 uint n = 0;
316 for (uint row = 0; row < num_row; row++) {
317 for (uint col = 0; col < num_col; col++) {
318 Point offset = RemapCoords (row * TILE_SIZE, col * TILE_SIZE, 0); // offset for current tile
319 pt[n].x = x + UnScaleByZoom (offset.x, ZOOM_LVL_GUI);
320 pt[n].y = y + UnScaleByZoom (offset.y, ZOOM_LVL_GUI);
321 n++;
325 for (bool ground = true; ; ground = !ground) {
326 for (uint i = 0; i < n; i++) {
327 HouseID hid = house_id + i;
328 if (new_house) {
329 DrawNewHouseTileInGUI (&tmp_dpi, pt[i].x, pt[i].y, hid, ground);
330 } else {
331 DrawOldHouseTileInGUI (&tmp_dpi, pt[i].x, pt[i].y, hid, ground);
334 if (!ground) break;
338 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
340 return GetTileMaxPixelZ(tile);
343 /** Tile callback routine */
344 static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
346 HouseID hid = GetHouseType(tile);
348 /* For NewGRF house tiles we might not be drawing a foundation. We need to
349 * account for this, as other structures should
350 * draw the wall of the foundation in this case.
352 if (hid >= NEW_HOUSE_OFFSET) {
353 const HouseSpec *hs = HouseSpec::Get(hid);
354 if (hs->grf_prop.spritegroup[0] != NULL && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
355 uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
356 if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
359 return FlatteningFoundation(tileh);
363 * Animate a tile for a town
364 * Only certain houses can be animated
365 * The newhouses animation supersedes regular ones
366 * @param tile TileIndex of the house to animate
368 static void AnimateTile_Town(TileIndex tile)
370 if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
371 AnimateNewHouseTile(tile);
372 return;
375 if (_tick_counter & 3) return;
377 /* If the house is not one with a lift anymore, then stop this animating.
378 * Not exactly sure when this happens, but probably when a house changes.
379 * Before this was just a return...so it'd leak animated tiles..
380 * That bug seems to have been here since day 1?? */
381 if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
382 DeleteAnimatedTile(tile);
383 return;
386 if (!LiftHasDestination(tile)) {
387 uint i;
389 /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
390 * This is due to the fact that the first floor is, in the graphics,
391 * the height of 2 'normal' floors.
392 * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
393 do {
394 i = RandomRange(7);
395 } while (i == 1 || i * 6 == GetLiftPosition(tile));
397 SetLiftDestination(tile, i);
400 int pos = GetLiftPosition(tile);
401 int dest = GetLiftDestination(tile) * 6;
402 pos += (pos < dest) ? 1 : -1;
403 SetLiftPosition(tile, pos);
405 if (pos == dest) {
406 HaltLift(tile);
407 DeleteAnimatedTile(tile);
410 MarkTileDirtyByTile(tile);
414 * Resize the sign(label) of the town after changes in
415 * population (creation or growth or else)
417 void Town::UpdateVirtCoord()
419 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
420 SetDParam(0, this->index);
421 SetDParam(1, this->cache.population);
422 this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
423 _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
424 STR_VIEWPORT_TOWN);
426 SetWindowDirty(WC_TOWN_VIEW, this->index);
429 /** Update the virtual coords needed to draw the town sign for all towns. */
430 void UpdateAllTownVirtCoords()
432 Town *t;
434 FOR_ALL_TOWNS(t) {
435 t->UpdateVirtCoord();
440 * Change the towns population
441 * @param t Town which population has changed
442 * @param mod population change (can be positive or negative)
444 static void ChangePopulation(Town *t, int mod)
446 t->cache.population += mod;
447 InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
448 t->UpdateVirtCoord();
450 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
454 * Determines the world population
455 * Basically, count population of all towns, one by one
456 * @return uint32 the calculated population of the world
458 uint32 GetWorldPopulation()
460 uint32 pop = 0;
461 const Town *t;
463 FOR_ALL_TOWNS(t) pop += t->cache.population;
464 return pop;
468 * Helper function for house completion stages progression
469 * @param tile TileIndex of the house (or parts of it) to "grow"
471 static void MakeSingleHouseBigger(TileIndex tile)
473 assert(IsHouseTile(tile));
475 /* progress in construction stages */
476 IncHouseConstructionTick(tile);
477 if (GetHouseConstructionTick(tile) != 0) return;
479 AnimateNewHouseConstruction(tile);
481 if (IsHouseCompleted(tile)) {
482 /* Now that construction is complete, we can add the population of the
483 * building to the town. */
484 ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
485 ResetHouseAge(tile);
487 MarkTileDirtyByTile(tile);
491 * Make the house advance in its construction stages until completion
492 * @param tile TileIndex of house
494 static void MakeTownHouseBigger(TileIndex tile)
496 uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
497 if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
498 if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
499 if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
500 if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
504 * Tile callback function.
506 * Periodic tic handler for houses and town
507 * @param tile been asked to do its stuff
509 static void TileLoop_Town(TileIndex tile)
511 HouseID house_id = GetHouseType(tile);
513 /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
514 * doesn't exist any more, so don't continue here. */
515 if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
517 if (!IsHouseCompleted(tile)) {
518 /* Construction is not completed. See if we can go further in construction*/
519 MakeTownHouseBigger(tile);
520 return;
523 const HouseSpec *hs = HouseSpec::Get(house_id);
525 /* If the lift has a destination, it is already an animated tile. */
526 if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
527 house_id < NEW_HOUSE_OFFSET &&
528 !LiftHasDestination(tile) &&
529 Chance16(1, 2)) {
530 AddAnimatedTile(tile);
533 Town *t = Town::GetByTile(tile);
534 uint32 r = Random();
536 StationFinder stations(TileArea(tile, 1, 1));
538 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
539 for (uint i = 0; i < 256; i++) {
540 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
542 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
544 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
545 if (cargo == CT_INVALID) continue;
547 uint amt = GB(callback, 0, 8);
548 if (amt == 0) continue;
550 uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
552 const CargoSpec *cs = CargoSpec::Get(cargo);
553 t->supplied[cs->Index()].new_max += amt;
554 t->supplied[cs->Index()].new_act += moved;
556 } else {
557 if (GB(r, 0, 8) < hs->population) {
558 uint amt = GB(r, 0, 8) / 8 + 1;
560 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
561 t->supplied[CT_PASSENGERS].new_max += amt;
562 t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
565 if (GB(r, 8, 8) < hs->mail_generation) {
566 uint amt = GB(r, 8, 8) / 8 + 1;
568 if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
569 t->supplied[CT_MAIL].new_max += amt;
570 t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
574 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
576 if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
577 HasBit(t->flags, TOWN_IS_GROWING) &&
578 CanDeleteHouse(tile) &&
579 GetHouseAge(tile) >= hs->minimum_life &&
580 --t->time_until_rebuild == 0) {
581 t->time_until_rebuild = GB(r, 16, 8) + 192;
583 ClearTownHouse(t, tile);
585 /* Rebuild with another house? */
586 if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
589 cur_company.Restore();
592 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
594 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
595 if (!CanDeleteHouse(tile)) return CMD_ERROR;
597 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
599 CommandCost cost(EXPENSES_CONSTRUCTION);
600 cost.AddCost(hs->GetRemovalCost());
602 int rating = hs->remove_rating_decrease;
603 Town *t = Town::GetByTile(tile);
605 if (Company::IsValidID(_current_company)) {
606 if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
607 SetDParam(0, t->index);
608 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
612 ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
613 if (flags & DC_EXEC) {
614 ClearTownHouse(t, tile);
617 return cost;
620 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
622 HouseID house_id = GetHouseType(tile);
623 const HouseSpec *hs = HouseSpec::Get(house_id);
624 Town *t = Town::GetByTile(tile);
626 if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
627 for (uint i = 0; i < 256; i++) {
628 uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
630 if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
632 CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
634 if (cargo == CT_INVALID) continue;
635 produced[cargo]++;
637 } else {
638 if (hs->population > 0) {
639 produced[CT_PASSENGERS]++;
641 if (hs->mail_generation > 0) {
642 produced[CT_MAIL]++;
647 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, uint32 *always_accepted)
649 if (cargo == CT_INVALID || amount == 0) return;
650 acceptance[cargo] += amount;
651 SetBit(*always_accepted, cargo);
654 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
656 const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
657 CargoID accepts[3];
659 /* Set the initial accepted cargo types */
660 for (uint8 i = 0; i < lengthof(accepts); i++) {
661 accepts[i] = hs->accepts_cargo[i];
664 /* Check for custom accepted cargo types */
665 if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
666 uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
667 if (callback != CALLBACK_FAILED) {
668 /* Replace accepted cargo types with translated values from callback */
669 accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
670 accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
671 accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
675 /* Check for custom cargo acceptance */
676 if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
677 uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
678 if (callback != CALLBACK_FAILED) {
679 AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
680 AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
681 if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
682 /* The 'S' bit indicates food instead of goods */
683 AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
684 } else {
685 AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
687 return;
691 /* No custom acceptance, so fill in with the default values */
692 for (uint8 i = 0; i < lengthof(accepts); i++) {
693 AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
697 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
699 const HouseID house = GetHouseType(tile);
700 const HouseSpec *hs = HouseSpec::Get(house);
701 bool house_completed = IsHouseCompleted(tile);
703 td->str = hs->building_name;
705 uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
706 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
707 if (callback_res > 0x400) {
708 ErrorUnknownCallbackResult(hs->grf_prop.grffile->grfid, CBID_HOUSE_CUSTOM_NAME, callback_res);
709 } else {
710 StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
711 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
712 td->str = new_name;
717 if (!house_completed) {
718 td->dparam = td->str;
719 td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
722 if (hs->grf_prop.grffile != NULL) {
723 const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
724 td->grf = gc->GetName();
727 td->owner[0] = OWNER_TOWN;
730 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
732 /* not used */
735 /** Update the total cargo acceptance of the whole town.
736 * @param t The town to update.
738 void UpdateTownCargoTotal(Town *t)
740 t->cargo_accepted_total = 0;
742 const TileArea &area = t->cargo_accepted.GetArea();
743 TILE_AREA_LOOP(tile, area) {
744 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
745 t->cargo_accepted_total |= t->cargo_accepted[tile];
751 * Update accepted town cargoes around a specific tile.
752 * @param t The town to update.
753 * @param start Update the values around this tile.
754 * @param update_total Set to true if the total cargo acceptance should be updated.
756 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
758 CargoArray accepted, produced;
759 uint32 dummy;
761 /* Gather acceptance for all houses in an area around the start tile.
762 * The area is composed of the square the tile is in, extended one square in all
763 * directions as the coverage area of a single station is bigger than just one square. */
764 TileArea area = AcceptanceMatrix::GetAreaForTile(start, 1);
765 TILE_AREA_LOOP(tile, area) {
766 if (!IsHouseTile(tile) || GetTownIndex(tile) != t->index) continue;
768 AddAcceptedCargo_Town(tile, accepted, &dummy);
769 AddProducedCargo_Town(tile, produced);
772 /* Create bitmap of produced and accepted cargoes. */
773 uint32 acc = 0;
774 for (uint cid = 0; cid < NUM_CARGO; cid++) {
775 if (accepted[cid] >= 8) SetBit(acc, cid);
776 if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
778 t->cargo_accepted[start] = acc;
780 if (update_total) UpdateTownCargoTotal(t);
783 /** Update cargo acceptance for the complete town.
784 * @param t The town to update.
786 void UpdateTownCargoes(Town *t)
788 t->cargo_produced = 0;
790 const TileArea &area = t->cargo_accepted.GetArea();
791 if (area.tile == INVALID_TILE) return;
793 /* Update acceptance for each grid square. */
794 TILE_AREA_LOOP(tile, area) {
795 if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
796 UpdateTownCargoes(t, tile, false);
800 /* Update the total acceptance. */
801 UpdateTownCargoTotal(t);
804 /** Updates the bitmap of all cargoes accepted by houses. */
805 void UpdateTownCargoBitmap()
807 Town *town;
808 _town_cargoes_accepted = 0;
810 FOR_ALL_TOWNS(town) {
811 _town_cargoes_accepted |= town->cargo_accepted_total;
815 static bool GrowTown(Town *t);
817 void OnTick_Town()
819 if (_game_mode == GM_EDITOR) return;
821 Town *t;
822 FOR_ALL_TOWNS(t) {
823 /* Run town tick at regular intervals, but not all at once. */
824 if ((_tick_counter + t->index) % TOWN_GROWTH_TICKS == 0
825 && HasBit(t->flags, TOWN_IS_GROWING)) {
826 if (t->grow_counter > 0) {
827 t->grow_counter--;
828 } else if (GrowTown(t)) {
829 t->grow_counter = t->growth_rate & (~TOWN_GROW_RATE_CUSTOM);
836 * Return the RoadBits of a tile
838 * @note There are many other functions doing things like that.
839 * @note Needs to be checked for needlessness.
840 * @param tile The tile we want to analyse
841 * @return The roadbits of the given tile
843 static RoadBits GetTownRoadBits(TileIndex tile)
845 if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
847 return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
851 * Check for parallel road inside a given distance.
852 * Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
853 * is there a parallel road left or right of it within distance dist_multi?
855 * @param tile current tile
856 * @param dir target direction
857 * @param dist_multi distance multiplayer
858 * @return true if there is a parallel road
860 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
862 if (!IsValidTile(tile)) return false;
864 /* Lookup table for the used diff values */
865 const TileIndexDiff tid_lt[3] = {
866 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
867 TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
868 TileOffsByDiagDir(ReverseDiagDir(dir)),
871 dist_multi = (dist_multi + 1) * 4;
872 for (uint pos = 4; pos < dist_multi; pos++) {
873 /* Go (pos / 4) tiles to the left or the right */
874 TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
876 /* Use the current tile as origin, or go one tile backwards */
877 if (pos & 2) cur += tid_lt[2];
879 /* Test for roadbit parallel to dir and facing towards the middle axis */
880 if (IsValidTile(tile + cur) &&
881 GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
883 return false;
887 * Check if a Road is allowed on a given tile
889 * @param t The current town
890 * @param tile The target tile
891 * @param dir The direction in which we want to extend the town
892 * @return true if it is allowed else false
894 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
896 if (DistanceFromEdge(tile) == 0) return false;
898 /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
899 if (HasBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
901 /* Check if there already is a road at this point? */
902 if (GetTownRoadBits(tile) == ROAD_NONE) {
903 /* No, try if we are able to build a road piece there.
904 * If that fails clear the land, and if that fails exit.
905 * This is to make sure that we can build a road here later. */
906 if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
907 DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
908 return false;
912 Slope cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile) : GetTileSlope(tile);
913 bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
914 if (cur_slope == SLOPE_FLAT) return ret;
916 Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
917 if (desired_slope == cur_slope || ComplementSlope(desired_slope) == cur_slope) return ret;
919 /* If the tile is not a slope in the right direction, then
920 * maybe terraform some. */
921 if (Chance16(1, 8)) {
922 /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
923 bool terraform = !_generating_world && Chance16(1, 10) &&
924 DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
925 DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND).Succeeded();
926 if (!terraform && Chance16(1, 3)) {
927 /* We can consider building on the slope, though. */
928 return ret;
931 return false;
934 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
936 assert(tile < MapSize());
938 CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
939 if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
940 DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
941 return true;
944 static void LevelTownLand(TileIndex tile)
946 assert(tile < MapSize());
948 /* Don't terraform if land is plain or if there's a house there. */
949 if (IsHouseTile(tile)) return;
950 Slope tileh = GetTileSlope(tile);
951 if (tileh == SLOPE_FLAT) return;
953 /* First try up, then down */
954 if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
955 TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
960 * Generate the RoadBits of a grid tile
962 * @param t current town
963 * @param tile tile in reference to the town
964 * @param dir The direction to which we are growing ATM
965 * @return the RoadBit of the current tile regarding
966 * the selected town layout
968 static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
970 /* align the grid to the downtown */
971 CoordDiff grid_pos = TileCoordDiff(t->xy, tile); // Vector from downtown to the tile
972 RoadBits rcmd = ROAD_NONE;
974 switch (t->layout) {
975 default: NOT_REACHED();
977 case TL_2X2_GRID:
978 if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
979 if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
980 break;
982 case TL_3X3_GRID:
983 if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
984 if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
985 break;
988 /* Optimise only X-junctions */
989 if (rcmd != ROAD_ALL) return rcmd;
991 RoadBits rb_template;
993 switch (GetTileSlope(tile)) {
994 default: rb_template = ROAD_ALL; break;
995 case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
996 case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
997 case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
998 case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
999 case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1000 case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1001 case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1002 case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1003 case SLOPE_STEEP_W:
1004 case SLOPE_STEEP_S:
1005 case SLOPE_STEEP_E:
1006 case SLOPE_STEEP_N:
1007 rb_template = ROAD_NONE;
1008 break;
1011 /* Stop if the template is compatible to the growth dir */
1012 if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1013 /* If not generate a straight road in the direction of the growth */
1014 return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
1018 * Grows the town with an extra house.
1019 * Check if there are enough neighbor house tiles
1020 * next to the current tile. If there are enough
1021 * add another house.
1023 * @param t The current town
1024 * @param tile The target tile for the extra house
1025 * @return true if an extra house has been added
1027 static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
1029 /* We can't look further than that. */
1030 if (DistanceFromEdge(tile) == 0) return false;
1032 uint counter = 0; // counts the house neighbor tiles
1034 /* Check the tiles E,N,W and S of the current tile for houses */
1035 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1036 /* Count both void and house tiles for checking whether there
1037 * are enough houses in the area. This to make it likely that
1038 * houses get build up to the edge of the map. */
1039 TileIndex tt = TileAddByDiagDir(tile, dir);
1040 if (IsHouseTile(tt) || IsVoidTile(tt)) {
1041 counter++;
1044 /* If there are enough neighbors stop here */
1045 if (counter >= 3) {
1046 return BuildTownHouse (t, tile);
1049 return false;
1053 * Grows the town with a bridge.
1054 * At first we check if a bridge is reasonable.
1055 * If so we check if we are able to build it.
1057 * @param t The current town
1058 * @param tile The current tile
1059 * @param bridge_dir The valid direction in which to grow a bridge
1060 * @return true if a bridge has been build else false
1062 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1064 assert(bridge_dir < DIAGDIR_END);
1066 const Slope slope = GetTileSlope(tile);
1068 /* Assure that the bridge is connectable to the start side */
1069 if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1071 /* We are in the right direction */
1072 const int delta = TileOffsByDiagDir(bridge_dir);
1074 uint bridge_length = 0; // This value stores the length of the possible bridge
1075 TileIndex bridge_tile = tile + delta; // Used to store the other waterside
1077 if (slope == SLOPE_FLAT) {
1078 /* Bridges starting on flat tiles are only allowed when crossing rivers. */
1079 while (IsValidTile(bridge_tile) && IsPlainWaterTile(bridge_tile) && !IsSea(bridge_tile)) {
1080 /* Allow to cross rivers, not big lakes. */
1081 if (bridge_length >= 3) return false;
1082 bridge_length++;
1083 bridge_tile += delta;
1085 } else {
1086 /* Make sure the direction is compatible with the slope.
1087 * Well we check if the slope has an up bit set in the
1088 * reverse direction. */
1089 if (slope & InclinedSlope(bridge_dir)) return false;
1091 while (IsValidTile(bridge_tile) && IsPlainWaterTile(bridge_tile)) {
1092 /* Max 10-tile long bridges */
1093 if (bridge_length >= 10) return false;
1094 bridge_length++;
1095 bridge_tile += delta;
1099 /* no water tiles in between? */
1100 if (bridge_length == 0) return false;
1102 std::bitset <MAX_BRIDGES> tried;
1103 uint n = MAX_BRIDGES;
1104 byte bridge_type = RandomRange (n);
1106 for (;;) {
1107 /* Can we actually build the bridge? */
1108 if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 12 | t->index << 16, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1109 DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 12 | t->index << 16, DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE);
1110 return true;
1113 /* Try a different bridge. */
1114 tried[bridge_type] = true;
1115 n--;
1116 assert (n + tried.count() == MAX_BRIDGES);
1117 if (n == 0) break;
1119 bridge_type = 0;
1120 uint i = RandomRange (n);
1121 while (tried[bridge_type] || (i-- > 0)) {
1122 bridge_type++;
1123 assert (bridge_type < MAX_BRIDGES);
1127 /* Quit if no bridge can be built. */
1128 return false;
1132 * Grows the town with either a bridge or a road piece.
1134 * @param t The current town
1135 * @param tile The current tile
1136 * @param target_dir The target road dir
1137 * @param rcmd The RoadBits we want to build on the tile
1138 * @return true if the RoadBits have been added else false
1140 static bool GrowTownWithRoad(const Town *t, TileIndex tile, DiagDirection target_dir, RoadBits rcmd)
1142 /* Make the roads look nicer */
1143 rcmd = CleanUpRoadBits(tile, rcmd);
1144 if (rcmd == ROAD_NONE) return false;
1146 /* Only use the target direction for bridges to ensure they're connected.
1147 * The target_dir is as computed previously according to town layout, so
1148 * it will match it perfectly. */
1149 return GrowTownWithBridge (t, tile, target_dir)
1150 || DoCommand (tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded();
1154 * Grows the given town at a tile where there are no roads.
1155 * @param t The current town
1156 * @param tile The current tile
1157 * @param target_dir The target road dir
1158 * @return Whether a road was built
1160 static bool GrowTown_NewRoad (Town *t, TileIndex tile, DiagDirection target_dir)
1162 if (!_settings_game.economy.allow_town_roads && !_generating_world) return false;
1163 if (!_settings_game.economy.allow_town_level_crossings && IsRailwayTile(tile)) return false;
1165 /* Remove hills etc */
1166 if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1168 RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1170 /* Is a road allowed here? */
1171 switch (t->layout) {
1172 default: NOT_REACHED();
1174 case TL_3X3_GRID:
1175 case TL_2X2_GRID:
1176 rcmd = GetTownRoadGridElement (t, tile, target_dir);
1177 if (rcmd == ROAD_NONE) return false;
1178 break;
1180 case TL_BETTER_ROADS:
1181 case TL_ORIGINAL:
1182 if (!IsRoadAllowedHere (t, tile, target_dir)) return false;
1184 DiagDirection source_dir = ReverseDiagDir(target_dir);
1186 if (Chance16(1, 6)) {
1187 /* Randomize a new target dir */
1188 target_dir = ChangeDiagDir (target_dir, Chance16(1, 2) ? DIAGDIRDIFF_90RIGHT : DIAGDIRDIFF_90LEFT);
1191 if (!IsRoadAllowedHere (t, TileAddByDiagDir(tile, target_dir), target_dir)) {
1192 /* A road is not allowed to continue the randomized road,
1193 * return if the road we're trying to build is curved. */
1194 if (target_dir != ReverseDiagDir(source_dir)) return false;
1196 /* Return if neither side of the new road is a house */
1197 if (!IsHouseTile(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT))) &&
1198 !IsHouseTile(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)))) {
1199 return false;
1202 /* That means that the road is only allowed if there is a house
1203 * at any side of the new road. */
1206 rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1207 break;
1210 /* Return if a water tile */
1211 if (HasTileWaterGround(tile)) return false;
1213 return GrowTownWithRoad (t, tile, target_dir, rcmd);
1217 * Grows the given town at a tile where there is an unconnected road.
1218 * @param t The current town
1219 * @param tile The current tile
1220 * @param target_dir The target road dir
1221 * @param cur_rb The current tile RoadBits
1222 * @return Whether a road piece was built
1224 static bool GrowTown_UnconnectedRoad (Town *t, TileIndex tile, DiagDirection target_dir, RoadBits cur_rb)
1226 /* Continue building on a partial road.
1227 * Should be always OK, so we only generate
1228 * the fitting RoadBits */
1230 if (!_settings_game.economy.allow_town_roads && !_generating_world) return false;
1232 RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1234 switch (t->layout) {
1235 default: NOT_REACHED();
1237 case TL_3X3_GRID:
1238 case TL_2X2_GRID:
1239 rcmd = GetTownRoadGridElement (t, tile, target_dir);
1240 break;
1242 case TL_BETTER_ROADS:
1243 case TL_ORIGINAL:
1244 rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1245 break;
1248 return GrowTownWithRoad (t, tile, target_dir, rcmd);
1251 /* Describe the possible results of GrowTown_ConnectedRoad. */
1252 enum TownGrowthResult {
1253 GROWTH_CONTINUE, ///< continue searching
1254 GROWTH_FAILURE, ///< growth failed, stop searching
1255 GROWTH_SUCCESS, ///< growth succeeded, stop searching
1259 * Grows the given town at a tile where there is a connected road.
1260 * @param t The current town
1261 * @param tile The current tile
1262 * @param target_dir The target road dir
1263 * @param cur_rb The current tile RoadBits
1264 * @return The result of the growth attempt
1266 static TownGrowthResult GrowTown_ConnectedRoad (Town *t, TileIndex tile, DiagDirection target_dir, RoadBits cur_rb)
1268 /* Possibly extend the road in a direction.
1269 * Randomize a direction and if it has a road, bail out. */
1270 target_dir = RandomDiagDir();
1271 if (cur_rb & DiagDirToRoadBits(target_dir)) return GROWTH_CONTINUE;
1273 /* This is the tile we will reach if we extend to this direction. */
1274 TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
1276 /* Don't walk into water. */
1277 if (HasTileWaterGround(house_tile)) return GROWTH_CONTINUE;
1279 if (!IsValidTile(house_tile)) return GROWTH_CONTINUE;
1281 bool allow_house = true; // Value which decides if we want to construct a house
1282 RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1283 bool house_built = false; // Whether a house has been built
1285 if (_settings_game.economy.allow_town_roads || _generating_world) {
1286 switch (t->layout) {
1287 default: NOT_REACHED();
1289 case TL_3X3_GRID: // Use 2x2 grid afterwards!
1290 house_built = GrowTownWithExtraHouse (t, TileAddByDiagDir(house_tile, target_dir));
1291 /* fall through */
1292 case TL_2X2_GRID:
1293 rcmd = GetTownRoadGridElement (t, house_tile, target_dir);
1294 allow_house = (rcmd == ROAD_NONE);
1295 break;
1297 case TL_BETTER_ROADS: // Use original afterwards!
1298 house_built = GrowTownWithExtraHouse (t, TileAddByDiagDir(house_tile, target_dir));
1299 /* fall through */
1300 case TL_ORIGINAL:
1301 /* Allow a house at the edge. 60% chance or
1302 * always ok if no road allowed. */
1303 rcmd = DiagDirToRoadBits(target_dir);
1304 allow_house = (!IsRoadAllowedHere (t, house_tile, target_dir) || Chance16(6, 10));
1305 break;
1309 if (allow_house) {
1310 /* Build a house, but not if there already is a house there. */
1311 if (!IsHouseTile(house_tile)) {
1312 /* Level the land if possible */
1313 if (Chance16(1, 6)) LevelTownLand(house_tile);
1315 /* And build a house.
1316 * Set result to -1 if we managed to build it. */
1317 if (BuildTownHouse (t, house_tile)) house_built = true;
1319 return house_built ? GROWTH_SUCCESS : GROWTH_CONTINUE;
1322 return GrowTownWithRoad (t, tile, target_dir, rcmd) ? GROWTH_SUCCESS : GROWTH_FAILURE;
1326 * Simple heuristic to check if a tile may be usable for town growth.
1327 * @param tile The tile to check.
1328 * @return Whether the tile is usable.
1330 static bool GrowTownTileUsable (TileIndex tile)
1332 assert (tile < MapSize());
1334 switch (GetTileType (tile)) {
1335 case TT_GROUND:
1336 return !IsTileSubtype (tile, TT_GROUND_VOID);
1338 case TT_WATER:
1339 return IsCoast (tile);
1341 case TT_RAILWAY:
1342 case TT_ROAD:
1343 return true;
1345 case TT_MISC:
1346 switch (GetTileSubtype(tile)) {
1347 case TT_MISC_CROSSING: return true;
1348 case TT_MISC_TUNNEL: return GetTunnelTransportType(tile) == TRANSPORT_ROAD;
1349 default: return false;
1351 break;
1353 case TT_STATION:
1354 return IsDriveThroughStopTile (tile);
1357 default: return false;
1362 * Returns "growth" if a house was built, or no if the build failed.
1363 * @param t town to inquiry
1364 * @param tile to inquiry
1365 * @return whether expansion was possible
1367 static bool GrowTownFromTile (Town *t, TileIndex tile)
1369 DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1371 assert(tile < MapSize());
1373 /* Number of times to search.
1374 * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1375 * them a little handicap. */
1376 uint iterations;
1377 switch (t->layout) {
1378 case TL_BETTER_ROADS:
1379 iterations = 10 + t->cache.num_houses * 2 / 9;
1380 break;
1382 case TL_3X3_GRID:
1383 case TL_2X2_GRID:
1384 iterations = 10 + t->cache.num_houses * 1 / 9;
1385 break;
1387 default:
1388 iterations = 10 + t->cache.num_houses * 4 / 9;
1389 break;
1392 while (iterations-- > 0) {
1393 RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1395 /* Try to grow the town from this point */
1396 assert(tile < MapSize());
1397 assert((cur_rb == ROAD_NONE) || !HasTileWaterGround(tile));
1399 if (cur_rb == ROAD_NONE) {
1400 assert (IsValidDiagDirection(target_dir));
1401 return GrowTown_NewRoad (t, tile, target_dir);
1403 } else if (target_dir != DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1404 return GrowTown_UnconnectedRoad (t, tile, target_dir, cur_rb);
1406 } else if (!IsRoadBridgeTile(tile) && !IsTunnelTile(tile)) {
1407 switch (GrowTown_ConnectedRoad (t, tile, target_dir, cur_rb)) {
1408 case GROWTH_CONTINUE: break;
1409 case GROWTH_FAILURE: return false;
1410 case GROWTH_SUCCESS: return true;
1414 if (IsTunnelTile(tile)) {
1415 /* Reached a tunnel. Continue at the other end if this
1416 * is not the first tile, or half of the times if it is. */
1417 assert (maptile_is_road_tunnel(tile));
1419 if (target_dir == DIAGDIR_END) {
1420 if (Chance16(1, 2)) tile = GetOtherTunnelEnd (tile);
1421 target_dir = ReverseDiagDir (GetTunnelBridgeDirection(tile));
1422 } else {
1423 if (GetTunnelBridgeDirection(tile) != target_dir) return false;
1424 tile = GetOtherTunnelEnd (tile);
1427 tile = TileAddByDiagDir (tile, target_dir);
1428 if ((IsRoadBridgeTile(tile) || IsTunnelTile(tile))
1429 && GetTunnelBridgeDirection(tile) == (ReverseDiagDir(target_dir))) {
1430 return false;
1432 } else {
1433 /* Exclude the source position from the bitmask
1434 * and return if no more road blocks available */
1435 if (target_dir != DIAGDIR_END) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1437 /* Select a random bit from the blockmask, walk a step
1438 * and continue the search from there. */
1439 TileIndex target_tile;
1440 for (;;) {
1441 if (cur_rb == ROAD_NONE) return false;
1443 RoadBits connect_rb;
1444 do {
1445 target_dir = RandomDiagDir();
1446 connect_rb = DiagDirToRoadBits (target_dir);
1447 } while (!(cur_rb & connect_rb));
1448 cur_rb ^= connect_rb;
1450 if (IsRoadBridgeTile(tile) && target_dir == GetTunnelBridgeDirection(tile)) {
1451 target_tile = GetOtherBridgeEnd (tile);
1452 break;
1455 target_tile = TileAddByDiagDir (tile, target_dir);
1456 if ((IsRoadBridgeTile (target_tile) || IsTunnelTile (target_tile))
1457 && GetTunnelBridgeDirection (target_tile) == (ReverseDiagDir (target_dir))) {
1458 continue;
1461 if (_settings_game.economy.allow_town_roads || _generating_world) {
1462 if (GrowTownTileUsable (target_tile)) break;
1463 } else {
1464 connect_rb = MirrorRoadBits (connect_rb);
1465 RoadBits target_rb = GetTownRoadBits (target_tile);
1466 if ((target_rb & connect_rb) != 0 && (target_rb != connect_rb)) break;
1469 tile = target_tile;
1472 if ((IsRoadTile(tile) || IsLevelCrossingTile(tile)) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
1473 /* Don't allow building over roads of other cities */
1474 if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1475 return true;
1476 } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1477 /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1478 * owner :) (happy happy happy road now) */
1479 SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
1480 SetTownIndex(tile, t->index);
1485 return false;
1489 * Generate a random road block.
1490 * The probability of a straight road
1491 * is somewhat higher than a curved.
1493 * @return A RoadBits value with 2 bits set
1495 static RoadBits GenRandomRoadBits()
1497 uint32 r = Random();
1498 uint a = GB(r, 0, 2);
1499 uint b = GB(r, 8, 2);
1500 if (a == b) b ^= 2;
1501 return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1505 * Grow the town
1506 * @param t town to grow
1507 * @return true iff a house was built
1509 static bool GrowTown(Town *t)
1511 static const CoordDiff _town_coord_mod[] = {
1512 {-1, 0},
1513 { 1, 1},
1514 { 1, -1},
1515 {-1, -1},
1516 {-1, 0},
1517 { 0, 2},
1518 { 2, 0},
1519 { 0, -2},
1520 {-1, -1},
1521 {-2, 2},
1522 { 2, 2},
1523 { 2, -2},
1524 { 0, 0}
1527 /* Current "company" is a town */
1528 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1530 TileIndex tile = t->xy; // The tile we are working with ATM
1532 /* Find a road that we can base the construction on. */
1533 const CoordDiff *ptr;
1534 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1535 if (GetTownRoadBits(tile) != ROAD_NONE) {
1536 bool r = GrowTownFromTile (t, tile);
1537 cur_company.Restore();
1538 return r;
1540 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1543 /* No road available, try to build a random road block by
1544 * clearing some land and then building a road there. */
1545 if (_settings_game.economy.allow_town_roads || _generating_world) {
1546 tile = t->xy;
1547 for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1548 /* Only work with plain land that not already has a house */
1549 if (!IsHouseTile(tile) && IsTileFlat(tile)) {
1550 if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1551 DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
1552 cur_company.Restore();
1553 return true;
1556 tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1560 cur_company.Restore();
1561 return false;
1564 void UpdateTownRadius(Town *t)
1566 static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1567 { 4, 0, 0, 0, 0}, // 0
1568 { 16, 0, 0, 0, 0},
1569 { 25, 0, 0, 0, 0},
1570 { 36, 0, 0, 0, 0},
1571 { 49, 0, 4, 0, 0},
1572 { 64, 0, 4, 0, 0}, // 20
1573 { 64, 0, 9, 0, 1},
1574 { 64, 0, 9, 0, 4},
1575 { 64, 0, 16, 0, 4},
1576 { 81, 0, 16, 0, 4},
1577 { 81, 0, 16, 0, 4}, // 40
1578 { 81, 0, 25, 0, 9},
1579 { 81, 36, 25, 0, 9},
1580 { 81, 36, 25, 16, 9},
1581 { 81, 49, 0, 25, 9},
1582 { 81, 64, 0, 25, 9}, // 60
1583 { 81, 64, 0, 36, 9},
1584 { 81, 64, 0, 36, 16},
1585 {100, 81, 0, 49, 16},
1586 {100, 81, 0, 49, 25},
1587 {121, 81, 0, 49, 25}, // 80
1588 {121, 81, 0, 49, 25},
1589 {121, 81, 0, 49, 36}, // 88
1592 if (t->cache.num_houses < 92) {
1593 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));
1594 } else {
1595 int mass = t->cache.num_houses / 8;
1596 /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1597 * The offsets are to make sure the radii do not decrease in size when going from the table
1598 * to the calculated value.*/
1599 t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1600 t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1601 t->cache.squared_town_zone_radius[2] = 0;
1602 t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1603 t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1607 void UpdateTownMaxPass(Town *t)
1609 t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1610 t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1614 * Town constructor.
1615 * @param tile Center tile of the town.
1616 * @param townnameparts Town name.
1617 * @param city Whether the town is a city.
1618 * @param layout Road layout of the town.
1620 Town::Town (TileIndex tile, uint32 townnameparts, bool city, TownLayout layout) :
1621 xy (tile), townnameparams (_settings_game.game_creation.town_name),
1622 townnameparts (townnameparts), name (NULL), flags (0),
1623 noise_reached (0), statues (0), have_ratings (0), text (NULL),
1624 time_until_rebuild (10), grow_counter (0), growth_rate (250),
1625 fund_buildings_months (0), larger_town (city)
1627 add_to_tileset();
1629 this->cache.num_houses = 0;
1630 this->cache.population = 0;
1631 UpdateTownRadius (this);
1633 this->exclusivity = INVALID_COMPANY;
1634 this->exclusive_counter = 0;
1636 for (uint i = 0; i != MAX_COMPANIES; i++) this->ratings[i] = RATING_INITIAL;
1638 /* Set the default cargo requirement for town growth */
1639 switch (_settings_game.game_creation.landscape) {
1640 case LT_ARCTIC:
1641 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) this->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
1642 break;
1644 case LT_TROPIC:
1645 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) this->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
1646 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) this->goal[TE_WATER] = TOWN_GROWTH_DESERT;
1647 break;
1650 this->layout = (layout != TL_RANDOM) ? layout :
1651 (TownLayout) (TileHash (TileX(tile), TileY(tile)) % (NUM_TLS - 1));
1655 * Does the actual town creation.
1656 * @param tile Where to put it
1657 * @param townnameparts The town name
1658 * @param size Parameter for size determination
1659 * @param city whether to build a city or town
1660 * @param layout the (road) layout of the town
1661 * @param manual was the town placed manually?
1662 * @return The created town
1664 static Town *DoCreateTown (TileIndex tile, uint32 townnameparts,
1665 TownSize size, bool city, TownLayout layout, bool manual)
1667 Town *t = new Town (tile, townnameparts, city, layout);
1669 int x = (int)size * 16 + 3;
1670 if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1671 /* Don't create huge cities when founding town in-game */
1672 if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1674 t->cache.num_houses += x;
1675 UpdateTownRadius(t);
1677 int i = x * 4;
1678 do {
1679 GrowTown(t);
1680 } while (--i);
1682 t->cache.num_houses -= x;
1683 UpdateTownRadius(t);
1684 UpdateTownMaxPass(t);
1685 UpdateAirportsNoise();
1687 t->UpdateVirtCoord();
1688 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
1689 InvalidateWindowData(WC_SELECT_TOWN, 0);
1691 return t;
1695 * Checks if it's possible to place a town at given tile
1696 * @param tile tile to check
1697 * @return error string or STR_NULL on success
1699 static StringID TownCanBePlacedHere (TileIndex tile)
1701 /* Check if too close to the edge of map */
1702 if (DistanceFromEdge(tile) < 12) {
1703 return STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB;
1706 /* Check distance to all other towns. */
1707 if (Town::find_any<DistanceManhattan> (tile, 19)) {
1708 return STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN;
1711 /* Can only build on clear flat areas, possibly with trees. */
1712 if (!IsGroundTile(tile) || !IsTileFlat(tile)) {
1713 return STR_ERROR_SITE_UNSUITABLE;
1716 return STR_NULL;
1720 * Verifies this custom name is unique. Only custom names are checked.
1721 * @param name name to check
1722 * @return is this name unique?
1724 static bool IsUniqueTownName(const char *name)
1726 const Town *t;
1728 FOR_ALL_TOWNS(t) {
1729 if (t->name != NULL && strcmp(t->name, name) == 0) return false;
1732 return true;
1736 * Create a new town.
1737 * @param tile coordinates where town is built
1738 * @param flags type of operation
1739 * @param p1 0..1 size of the town (@see TownSize)
1740 * 2 true iff it should be a city
1741 * 3..5 town road layout (@see TownLayout)
1742 * 6 use random location (randomize \c tile )
1743 * @param p2 town name parts
1744 * @param text Custom name for the town. If empty, the town name parts will be used.
1745 * @return the cost of this operation or an error
1747 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1749 TownSize size = Extract<TownSize, 0, 2>(p1);
1750 bool city = HasBit(p1, 2);
1751 TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1752 TownNameParams par(_settings_game.game_creation.town_name);
1753 bool random = HasBit(p1, 6);
1754 uint32 townnameparts = p2;
1756 if (size >= TSZ_END) return CMD_ERROR;
1757 if (layout >= NUM_TLS) return CMD_ERROR;
1759 /* Some things are allowed only in the scenario editor and for game scripts. */
1760 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1761 if (_settings_game.economy.found_town == TF_FORBIDDEN) return CMD_ERROR;
1762 if (size == TSZ_LARGE) return CMD_ERROR;
1763 if (random) return CMD_ERROR;
1764 if (_settings_game.economy.found_town != TF_CUSTOM_LAYOUT && layout != _settings_game.economy.town_layout) {
1765 return CMD_ERROR;
1767 } else if (_current_company == OWNER_DEITY && random) {
1768 /* Random parameter is not allowed for Game Scripts. */
1769 return CMD_ERROR;
1772 if (StrEmpty(text)) {
1773 /* If supplied name is empty, townnameparts has to generate unique automatic name */
1774 if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1775 } else {
1776 /* If name is not empty, it has to be unique custom name */
1777 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
1778 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1781 /* Allocate town struct */
1782 if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1784 if (!random) {
1785 StringID str = TownCanBePlacedHere (tile);
1786 if (str != STR_NULL) return_cmd_error(str);
1789 static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1790 /* multidimensional arrays have to have defined length of non-first dimension */
1791 assert_compile(lengthof(price_mult[0]) == 4);
1793 CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1794 byte mult = price_mult[city][size];
1796 cost.MultiplyCost(mult);
1798 /* Create the town */
1799 if (flags & DC_EXEC) {
1800 if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1801 _additional_cash_required = cost.GetCost();
1802 return CommandCost(EXPENSES_OTHER);
1805 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1806 UpdateNearestTownForRoadTiles(true);
1807 Town *t;
1808 if (random) {
1809 t = CreateRandomTown(20, townnameparts, size, city, layout);
1810 if (t == NULL) {
1811 cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1812 } else {
1813 _new_town_id = t->index;
1815 } else {
1816 t = DoCreateTown (tile, townnameparts, size, city, layout, true);
1818 UpdateNearestTownForRoadTiles(false);
1819 old_generating_world.Restore();
1821 if (t != NULL && !StrEmpty(text)) {
1822 t->name = xstrdup(text);
1823 t->UpdateVirtCoord();
1826 if (_game_mode != GM_EDITOR) {
1827 /* 't' can't be NULL since 'random' is false outside scenedit */
1828 assert(!random);
1830 AddNewsItem<FoundTownNewsItem> (t->index, tile, _current_company);
1831 AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1832 Game::NewEvent(new ScriptEventTownFounded(t->index));
1835 return cost;
1839 * Towns must all be placed on the same grid or when they eventually
1840 * interpenetrate their road networks will not mesh nicely; this
1841 * function adjusts a tile so that it aligns properly.
1843 * @param tile the tile to start at
1844 * @param layout which town layout algo is in effect
1845 * @return the adjusted tile
1847 static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
1849 switch (layout) {
1850 case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1851 case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1852 default: return tile;
1857 * Towns must all be placed on the same grid or when they eventually
1858 * interpenetrate their road networks will not mesh nicely; this
1859 * function tells you if a tile is properly aligned.
1861 * @param tile the tile to start at
1862 * @param layout which town layout algo is in effect
1863 * @return true if the tile is in the correct location
1865 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
1867 switch (layout) {
1868 case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
1869 case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
1870 default: return true;
1875 * Given a spot on the map (presumed to be a water tile), find a good
1876 * coastal spot to build a city. We don't want to build too close to
1877 * the edge if we can help it (since that retards city growth) hence
1878 * the search within a search within a search. O(n*m^2), where n is
1879 * how far to search for land, and m is how far inland to look for a
1880 * flat spot.
1882 * @param tile Start looking from this spot.
1883 * @param layout the road layout to search for
1884 * @return tile that was found
1886 static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
1888 CircularTileIterator iter (tile, 40);
1889 for (TileIndex coast = iter; coast != INVALID_TILE; coast = ++iter) {
1890 if (IsGroundTile (coast)) {
1891 /* Search for a good inland spot for a town. */
1892 TileIndex spot_tile = INVALID_TILE;
1893 uint spot_dist = 0;
1895 CircularTileIterator iter (coast, 10);
1896 for (TileIndex t = iter; t != INVALID_TILE; t = ++iter) {
1897 if (!IsGroundTile(t)) continue;
1898 if (!IsTileFlat(t)) continue;
1899 if (!IsTileAlignedToGrid (t, layout)) continue;
1901 uint dist = GetClosestWaterDistance (t, true);
1902 if (dist > spot_dist) {
1903 spot_tile = t;
1904 spot_dist = dist;
1907 return spot_tile;
1911 /* if we get here just give up */
1912 return INVALID_TILE;
1915 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
1917 assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
1919 if (!Town::CanAllocateItem()) return NULL;
1921 do {
1922 /* Generate a tile index not too close from the edge */
1923 TileIndex tile = AlignTileToGrid(RandomTile(), layout);
1925 /* if we tried to place the town on water, slide it over onto
1926 * the nearest likely-looking spot */
1927 if (IsWaterTile(tile)) {
1928 tile = FindNearestGoodCoastalTownSpot(tile, layout);
1929 if (tile == INVALID_TILE) continue;
1932 /* Make sure town can be placed here */
1933 if (TownCanBePlacedHere (tile) != STR_NULL) continue;
1935 /* Allocate a town struct */
1936 Town *t = DoCreateTown (tile, townnameparts, size, city, layout, false);
1938 /* if the population is still 0 at the point, then the
1939 * placement is so bad it couldn't grow at all */
1940 if (t->cache.population > 0) return t;
1942 Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1943 CommandCost rc = DoCommand(t->xy, t->index, 0, DC_EXEC, CMD_DELETE_TOWN);
1944 cur_company.Restore();
1945 assert(rc.Succeeded());
1947 /* We already know that we can allocate a single town when
1948 * entering this function. However, we create and delete
1949 * a town which "resets" the allocation checks. As such we
1950 * need to check again when assertions are enabled. */
1951 assert(Town::CanAllocateItem());
1952 } while (--attempts != 0);
1954 return NULL;
1957 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
1960 * This function will generate a certain amount of towns, with a certain layout
1961 * It can be called from the scenario editor (i.e.: generate Random Towns)
1962 * as well as from world creation.
1963 * @param layout which towns will be set to, when created
1964 * @return true if towns have been successfully created
1966 bool GenerateTowns(TownLayout layout)
1968 uint current_number = 0;
1969 uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
1970 uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
1971 total = min(Town::Pool::MAX_SIZE, total);
1972 uint32 townnameparts;
1973 TownNames town_names;
1975 SetGeneratingWorldProgress(GWP_TOWN, total);
1977 /* First attempt will be made at creating the suggested number of towns.
1978 * Note that this is really a suggested value, not a required one.
1979 * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
1980 do {
1981 bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
1982 IncreaseGeneratingWorldProgress(GWP_TOWN);
1983 /* Get a unique name for the town. */
1984 if (!GenerateTownName(&townnameparts, &town_names)) continue;
1985 /* try 20 times to create a random-sized town for the first loop. */
1986 if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
1987 } while (--total);
1989 town_names.clear();
1991 if (current_number != 0) return true;
1993 /* If current_number is still zero at this point, it means that not a single town has been created.
1994 * So give it a last try, but now more aggressive */
1995 if (GenerateTownName(&townnameparts) &&
1996 CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
1997 return true;
2000 /* If there are no towns at all and we are generating new game, bail out */
2001 if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2002 ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2005 return false; // we are still without a town? we failed, simply
2010 * Returns the bit corresponding to the town zone of the specified tile
2011 * @param t Town on which town zone is to be found
2012 * @param tile TileIndex where town zone needs to be found
2013 * @return the bit position of the given zone, as defined in HouseZones
2015 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2017 uint dist = DistanceSquare(tile, t->xy);
2019 if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2021 HouseZonesBits smallest = HZB_TOWN_EDGE;
2022 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2023 if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2026 return smallest;
2030 * Clears tile and builds a house or house part.
2031 * @param tile tile index
2032 * @param t The town to clear the house for
2033 * @param counter of construction step
2034 * @param stage of construction (used for drawing)
2035 * @param type of house. Index into house specs array
2036 * @param random_bits required for newgrf houses
2037 * @pre house can be built here
2039 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2041 CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
2043 assert(cc.Succeeded());
2045 assert(IsGroundTile(tile));
2047 IncreaseBuildingCount(t, type);
2048 MakeHouseTile(tile, t->index, counter, stage, type, random_bits, HouseSpec::Get(type)->processing_time);
2049 if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2051 MarkTileDirtyByTile(tile);
2056 * Write house information into the map. For houses > 1 tile, all tiles are marked.
2057 * @param t tile index
2058 * @param town The town related to this house
2059 * @param counter of construction step
2060 * @param stage of construction (used for drawing)
2061 * @param type of house. Index into house specs array
2062 * @param random_bits required for newgrf houses
2063 * @pre house can be built here
2065 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2067 BuildingFlags size = HouseSpec::Get(type)->building_flags;
2069 ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2070 if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2071 if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2072 if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2077 * Checks if a house can be built here. Important is slope, bridge above
2078 * and ability to clear the land.
2079 * @param tile tile to check
2080 * @param noslope are slopes (foundations) allowed?
2081 * @return true iff house can be built here
2083 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2085 /* cannot build on these slopes... */
2086 Slope slope = GetTileSlope(tile);
2087 if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2089 /* building under a bridge? */
2090 if (HasBridgeAbove(tile)) return false;
2092 /* can we clear the land? */
2093 return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2098 * Checks if a house can be built at this tile, must have the same max z as parameter.
2099 * @param tile tile to check
2100 * @param z max z of this tile so more parts of a house are at the same height (with foundation)
2101 * @param noslope are slopes (foundations) allowed?
2102 * @return true iff house can be built here
2103 * @see CanBuildHouseHere()
2105 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2107 if (!CanBuildHouseHere(tile, noslope)) return false;
2109 /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2110 if (GetTileMaxZ(tile) != z) return false;
2112 return true;
2117 * Checks if a house of size 2x2 can be built at this tile
2118 * @param tile tile, N corner
2119 * @param z maximum tile z so all tile have the same max z
2120 * @param noslope are slopes (foundations) allowed?
2121 * @return true iff house can be built
2122 * @see CheckBuildHouseSameZ()
2124 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2126 /* we need to check this tile too because we can be at different tile now */
2127 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2129 for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2130 tile += TileOffsByDiagDir(d);
2131 if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2134 return true;
2139 * Checks if current town layout allows building here
2140 * @param t town
2141 * @param tile tile to check
2142 * @return true iff town layout allows building here
2143 * @note see layouts
2145 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2147 /* Allow towns everywhere when we don't build roads */
2148 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2150 CoordDiff grid_pos = TileCoordDiff(t->xy, tile);
2152 switch (t->layout) {
2153 case TL_2X2_GRID:
2154 if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2155 break;
2157 case TL_3X3_GRID:
2158 if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2159 break;
2161 default:
2162 break;
2165 return true;
2170 * Checks if current town layout allows 2x2 building here
2171 * @param t town
2172 * @param tile tile to check
2173 * @return true iff town layout allows 2x2 building here
2174 * @note see layouts
2176 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2178 /* Allow towns everywhere when we don't build roads */
2179 if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
2181 /* Compute relative position of tile. (Positive offsets are towards north) */
2182 CoordDiff grid_pos = TileCoordDiff(t->xy, tile);
2184 switch (t->layout) {
2185 case TL_2X2_GRID:
2186 grid_pos.x %= 3;
2187 grid_pos.y %= 3;
2188 if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2189 (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2190 break;
2192 case TL_3X3_GRID:
2193 if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2194 break;
2196 default:
2197 break;
2200 return true;
2205 * Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout
2206 * Also, tests both building positions that occupy this tile
2207 * @param tile tile where the building should be built
2208 * @param t town
2209 * @param maxz all tiles should have the same height
2210 * @param noslope are slopes forbidden?
2211 * @param second diagdir from first tile to second tile
2213 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2215 /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2217 TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2218 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2220 tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2221 if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2222 *tile = tile2;
2223 return true;
2226 return false;
2231 * Checks if 2x2 building is allowed here, also takes into account current town layout
2232 * Also, tests all four building positions that occupy this tile
2233 * @param tile tile where the building should be built
2234 * @param t town
2235 * @param maxz all tiles should have the same height
2236 * @param noslope are slopes forbidden?
2238 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2240 TileIndex tile2 = *tile;
2242 for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2243 if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2244 *tile = tile2;
2245 return true;
2247 if (d == DIAGDIR_END) break;
2248 tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2251 return false;
2254 /** Get the flag to test/set for building uniqueness in a town. */
2255 static uint GetHouseUniqueFlags (const HouseSpec *hs)
2257 return (hs->building_flags & BUILDING_IS_CHURCH) ? (1 << TOWN_HAS_CHURCH) :
2258 (hs->building_flags & BUILDING_IS_STADIUM) ? (1 << TOWN_HAS_STADIUM) :
2263 * Check if a town can have a new house of a given type.
2264 * @param t The town to check.
2265 * @param house The house type that we want to add.
2266 * @param STR_NULL on success, else an error message.
2268 StringID IsNewTownHouseAllowed (const Town *t, HouseID house)
2270 const HouseSpec *hs = HouseSpec::Get(house);
2272 /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2273 if (hs->class_id != HOUSE_NO_CLASS) {
2274 /* id_count is always <= class_count, so it doesn't need to be checked. */
2275 if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) {
2276 return STR_ERROR_TOO_MANY_CLASS_HOUSES;
2278 } else {
2279 /* If the house has no class, check id_count instead. */
2280 if (t->cache.building_counts.id_count[house] == UINT16_MAX) {
2281 return STR_ERROR_TOO_MANY_HOUSES;
2285 /* Special houses that there can be only one of. */
2286 uint oneof = GetHouseUniqueFlags (hs);
2287 if (t->flags & oneof) return STR_ERROR_ONLY_ONE_BUILDING_PER_TOWN;
2289 return STR_NULL;
2293 * Really build a house.
2294 * @param t town to build house in
2295 * @param tile house location
2296 * @param house house type
2297 * @param random_bits random bits for the house
2299 void DoBuildHouse(Town *t, TileIndex tile, HouseID house, byte random_bits)
2301 t->cache.num_houses++;
2303 const HouseSpec *hs = HouseSpec::Get(house);
2305 /* Special houses that there can be only one of. */
2306 uint oneof = GetHouseUniqueFlags (hs);
2307 assert ((t->flags & oneof) == 0);
2308 t->flags |= oneof;
2310 byte construction_counter = 0;
2311 byte construction_stage = 0;
2313 if (_generating_world || _game_mode == GM_EDITOR) {
2314 uint32 r = Random();
2316 construction_stage = TOWN_HOUSE_COMPLETED;
2317 if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2319 if (construction_stage == TOWN_HOUSE_COMPLETED) {
2320 ChangePopulation(t, hs->population);
2321 } else {
2322 construction_counter = GB(r, 2, 2);
2326 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2327 UpdateTownRadius(t);
2328 UpdateTownCargoes(t, tile);
2332 * Tries to build a house at this tile
2333 * @param t town the house will belong to
2334 * @param tile where the house will be built
2335 * @return false iff no house can be built at this tile
2337 static bool BuildTownHouse(Town *t, TileIndex tile)
2339 /* forbidden building here by town layout */
2340 if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2342 /* no house allowed at all, bail out */
2343 if (!CanBuildHouseHere(tile, false)) return false;
2345 Slope slope = GetTileSlope(tile);
2346 int maxz = GetTileMaxZ(tile);
2348 /* Get the town zone type of the current tile, as well as the climate.
2349 * This will allow to easily compare with the specs of the new house to build */
2350 HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2352 /* Above snow? */
2353 int land = _settings_game.game_creation.landscape;
2354 if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2356 uint bitmask = (1 << rad) + (1 << (land + 12));
2358 /* bits 0-4 are used
2359 * bits 11-15 are used
2360 * bits 5-10 are not used. */
2361 HouseID houses[NUM_HOUSES];
2362 uint num = 0;
2363 uint probs[NUM_HOUSES];
2364 uint probability_max = 0;
2366 /* Generate a list of all possible houses that can be built. */
2367 for (uint i = 0; i < NUM_HOUSES; i++) {
2368 const HouseSpec *hs = HouseSpec::Get(i);
2370 /* Verify that the candidate house spec matches the current tile status */
2371 if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2373 if (IsNewTownHouseAllowed (t, i) != STR_NULL) continue;
2375 /* Without NewHouses, all houses have probability '1' */
2376 uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2377 probability_max += cur_prob;
2378 probs[num] = cur_prob;
2379 houses[num++] = (HouseID)i;
2382 TileIndex baseTile = tile;
2384 while (probability_max > 0) {
2385 /* Building a multitile building can change the location of tile.
2386 * The building would still be built partially on that tile, but
2387 * its northern tile would be elsewhere. However, if the callback
2388 * fails we would be basing further work from the changed tile.
2389 * So a next 1x1 tile building could be built on the wrong tile. */
2390 tile = baseTile;
2392 uint r = RandomRange(probability_max);
2393 uint i;
2394 for (i = 0; i < num; i++) {
2395 if (probs[i] > r) break;
2396 r -= probs[i];
2399 HouseID house = houses[i];
2400 probability_max -= probs[i];
2402 /* remove tested house from the set */
2403 num--;
2404 houses[i] = houses[num];
2405 probs[i] = probs[num];
2407 const HouseSpec *hs = HouseSpec::Get(house);
2409 if (_loaded_newgrf_features.has_newhouses && !_generating_world &&
2410 _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2411 continue;
2414 if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2416 /* Make sure there is no slope? */
2417 bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2418 if (noslope && slope != SLOPE_FLAT) continue;
2420 if (hs->building_flags & TILE_SIZE_2x2) {
2421 if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2422 } else if (hs->building_flags & TILE_SIZE_2x1) {
2423 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2424 } else if (hs->building_flags & TILE_SIZE_1x2) {
2425 if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2426 } else {
2427 /* 1x1 house checks are already done */
2430 byte random_bits = Random();
2432 if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
2433 uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2434 if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2437 DoBuildHouse(t, tile, house, random_bits);
2438 return true;
2441 return false;
2445 * Update data structures when a house is removed
2446 * @param tile Tile of the house
2447 * @param t Town owning the house
2448 * @param house House type
2450 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2452 assert(IsHouseTile(tile));
2453 DecreaseBuildingCount(t, house);
2454 DoClearSquare(tile);
2455 DeleteAnimatedTile(tile);
2457 DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2461 * Determines if a given HouseID is part of a multitile house.
2462 * The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
2464 * @param house Is changed to the HouseID of the north tile of the same house
2465 * @return TileDiff from the tile of the given HouseID to the north tile
2467 TileIndexDiff GetHouseNorthPart(HouseID &house)
2469 if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2470 if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2471 house--;
2472 return TileDiffXY(-1, 0);
2473 } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2474 house--;
2475 return TileDiffXY(0, -1);
2476 } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2477 house -= 2;
2478 return TileDiffXY(-1, 0);
2479 } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2480 house -= 3;
2481 return TileDiffXY(-1, -1);
2484 return 0;
2487 void ClearTownHouse(Town *t, TileIndex tile)
2489 assert(IsHouseTile(tile));
2491 HouseID house = GetHouseType(tile);
2493 /* need to align the tile to point to the upper left corner of the house */
2494 tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2496 const HouseSpec *hs = HouseSpec::Get(house);
2498 /* Remove population from the town if the house is finished. */
2499 if (IsHouseCompleted(tile)) {
2500 ChangePopulation(t, -hs->population);
2503 t->cache.num_houses--;
2505 /* Clear flags for houses that only may exist once/town. */
2506 if (hs->building_flags & BUILDING_IS_CHURCH) {
2507 ClrBit(t->flags, TOWN_HAS_CHURCH);
2508 } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2509 ClrBit(t->flags, TOWN_HAS_STADIUM);
2512 /* Do the actual clearing of tiles */
2513 uint eflags = hs->building_flags;
2514 DoClearTownHouseHelper(tile, t, house);
2515 if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2516 if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2517 if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2519 UpdateTownRadius(t);
2521 /* Update cargo acceptance. */
2522 UpdateTownCargoes(t, tile);
2526 * Rename a town (server-only).
2527 * @param tile unused
2528 * @param flags type of operation
2529 * @param p1 town ID to rename
2530 * @param p2 unused
2531 * @param text the new name or an empty string when resetting to the default
2532 * @return the cost of this operation or an error
2534 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2536 Town *t = Town::GetIfValid(p1);
2537 if (t == NULL) return CMD_ERROR;
2539 bool reset = StrEmpty(text);
2541 if (!reset) {
2542 if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR;
2543 if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2546 if (flags & DC_EXEC) {
2547 free(t->name);
2548 t->name = reset ? NULL : xstrdup(text);
2550 t->UpdateVirtCoord();
2551 InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
2552 SetWindowDirty(WC_SELECT_TOWN, 0);
2553 UpdateAllStationVirtCoords();
2555 return CommandCost();
2559 * Determines the first cargo with a certain town effect
2560 * @param effect Town effect of interest
2561 * @return first active cargo slot with that effect
2563 const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect)
2565 const CargoSpec *cs;
2566 FOR_ALL_CARGOSPECS(cs) {
2567 if (cs->town_effect == effect) return cs;
2569 return NULL;
2572 static void UpdateTownGrowRate(Town *t);
2575 * Change the cargo goal of a town.
2576 * @param tile Unused.
2577 * @param flags Type of operation.
2578 * @param p1 various bitstuffed elements
2579 * - p1 = (bit 0 - 15) - Town ID to cargo game of.
2580 * - p1 = (bit 16 - 23) - TownEffect to change the game of.
2581 * @param p2 The new goal value.
2582 * @param text Unused.
2583 * @return Empty cost or an error.
2585 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2587 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2589 TownEffect te = (TownEffect)GB(p1, 16, 8);
2590 if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2592 uint16 index = GB(p1, 0, 16);
2593 Town *t = Town::GetIfValid(index);
2594 if (t == NULL) return CMD_ERROR;
2596 /* Validate if there is a cargo which is the requested TownEffect */
2597 const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2598 if (cargo == NULL) return CMD_ERROR;
2600 if (flags & DC_EXEC) {
2601 t->goal[te] = p2;
2602 UpdateTownGrowRate(t);
2603 InvalidateWindowData(WC_TOWN_VIEW, index);
2606 return CommandCost();
2610 * Set a custom text in the Town window.
2611 * @param tile Unused.
2612 * @param flags Type of operation.
2613 * @param p1 Town ID to change the text of.
2614 * @param p2 Unused.
2615 * @param text The new text (empty to remove the text).
2616 * @return Empty cost or an error.
2618 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2620 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2621 Town *t = Town::GetIfValid(p1);
2622 if (t == NULL) return CMD_ERROR;
2624 if (flags & DC_EXEC) {
2625 free(t->text);
2626 t->text = StrEmpty(text) ? NULL : xstrdup(text);
2627 InvalidateWindowData(WC_TOWN_VIEW, p1);
2630 return CommandCost();
2634 * Change the growth rate of the town.
2635 * @param tile Unused.
2636 * @param flags Type of operation.
2637 * @param p1 Town ID to cargo game of.
2638 * @param p2 Amount of days between growth, or TOWN_GROW_RATE_CUSTOM_NONE, or 0 to reset custom growth rate.
2639 * @param text Unused.
2640 * @return Empty cost or an error.
2642 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2644 if (_current_company != OWNER_DEITY) return CMD_ERROR;
2645 if ((p2 & TOWN_GROW_RATE_CUSTOM) != 0 && p2 != TOWN_GROW_RATE_CUSTOM_NONE) return CMD_ERROR;
2646 if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2648 Town *t = Town::GetIfValid(p1);
2649 if (t == NULL) return CMD_ERROR;
2651 if (flags & DC_EXEC) {
2652 if (p2 == 0) {
2653 /* Clear TOWN_GROW_RATE_CUSTOM, UpdateTownGrowRate will determine a proper value */
2654 t->growth_rate = 0;
2655 } else {
2656 uint old_rate = t->growth_rate & ~TOWN_GROW_RATE_CUSTOM;
2657 if (t->grow_counter >= old_rate) {
2658 /* This also catches old_rate == 0 */
2659 t->grow_counter = p2;
2660 } else {
2661 /* Scale grow_counter, so half finished houses stay half finished */
2662 t->grow_counter = t->grow_counter * p2 / old_rate;
2664 t->growth_rate = p2 | TOWN_GROW_RATE_CUSTOM;
2666 UpdateTownGrowRate(t);
2667 InvalidateWindowData(WC_TOWN_VIEW, p1);
2670 return CommandCost();
2674 * Expand a town (scenario editor only).
2675 * @param tile Unused.
2676 * @param flags Type of operation.
2677 * @param p1 Town ID to expand.
2678 * @param p2 Amount to grow, or 0 to grow a random size up to the current amount of houses.
2679 * @param text Unused.
2680 * @return Empty cost or an error.
2682 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2684 if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2685 Town *t = Town::GetIfValid(p1);
2686 if (t == NULL) return CMD_ERROR;
2688 if (flags & DC_EXEC) {
2689 /* The more houses, the faster we grow */
2690 if (p2 == 0) {
2691 uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2692 t->cache.num_houses += amount;
2693 UpdateTownRadius(t);
2695 uint n = amount * 10;
2696 do GrowTown(t); while (--n);
2698 t->cache.num_houses -= amount;
2699 } else {
2700 for (; p2 > 0; p2--) {
2701 /* Try several times to grow, as we are really suppose to grow */
2702 for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2705 UpdateTownRadius(t);
2707 UpdateTownMaxPass(t);
2710 return CommandCost();
2714 * Delete a town (scenario editor or worldgen only).
2715 * @param tile Unused.
2716 * @param flags Type of operation.
2717 * @param p1 Town ID to delete.
2718 * @param p2 Unused.
2719 * @param text Unused.
2720 * @return Empty cost or an error.
2722 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2724 if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2725 Town *t = Town::GetIfValid(p1);
2726 if (t == NULL) return CMD_ERROR;
2728 /* Stations refer to towns. */
2729 const Station *st;
2730 FOR_ALL_STATIONS(st) {
2731 if (st->town == t) {
2732 /* Non-oil rig stations are always a problem. */
2733 if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2734 /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2735 CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2736 if (ret.Failed()) return ret;
2740 /* Depots refer to towns. */
2741 const Depot *d;
2742 FOR_ALL_DEPOTS(d) {
2743 if (d->town == t) return CMD_ERROR;
2746 /* Check all tiles for town ownership. */
2747 for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2748 bool try_clear = false;
2749 if (IsHouseTile(tile)) {
2750 try_clear = GetTownIndex(tile) == t->index;
2751 } else if (IsIndustryTile(tile)) {
2752 try_clear = Industry::GetByTile(tile)->town == t;
2753 } else {
2754 switch (GetTileType(tile)) {
2755 case TT_MISC:
2756 if (IsTunnelTile(tile)) {
2757 try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile) == t;
2758 break;
2760 if (!IsLevelCrossingTile(tile)) break;
2761 /* fall through */
2762 case TT_ROAD:
2763 try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2764 break;
2766 case TT_OBJECT:
2767 if (Town::GetNumItems() == 1) {
2768 /* No towns will be left, remove it! */
2769 try_clear = true;
2770 } else {
2771 Object *o = Object::GetByTile(tile);
2772 if (o->town == t) {
2773 if (o->type == OBJECT_STATUE) {
2774 /* Statue... always remove. */
2775 try_clear = true;
2776 } else {
2777 /* Tell to find a new town. */
2778 if (flags & DC_EXEC) o->town = NULL;
2782 break;
2784 default:
2785 break;
2788 if (try_clear) {
2789 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2790 if (ret.Failed()) return ret;
2794 /* The town destructor will delete the other things related to the town. */
2795 if (flags & DC_EXEC) delete t;
2797 return CommandCost();
2801 * Factor in the cost of each town action.
2802 * @see TownActions
2804 const byte _town_action_costs[TACT_COUNT] = {
2805 2, 4, 9, 35, 48, 53, 117, 175
2808 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2810 if (flags & DC_EXEC) {
2811 ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2813 return CommandCost();
2816 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2818 if (flags & DC_EXEC) {
2819 ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2821 return CommandCost();
2824 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2826 if (flags & DC_EXEC) {
2827 ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2829 return CommandCost();
2832 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2834 /* Check if the company is allowed to fund new roads. */
2835 if (!_settings_game.economy.fund_roads) return CMD_ERROR;
2837 if (flags & DC_EXEC) {
2838 t->road_build_months = 6;
2840 AddNewsItem<RoadRebuildNewsItem> (t->index, _current_company);
2841 AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2842 Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2844 return CommandCost();
2848 * Check whether the land can be cleared.
2849 * @param tile Tile to check.
2850 * @return The tile can be cleared.
2852 static bool TryClearTile(TileIndex tile)
2854 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2855 CommandCost r = DoCommand(tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
2856 cur_company.Restore();
2857 return r.Succeeded();
2861 * Perform a 9x9 tiles circular search from the center of the town
2862 * in order to find a free tile to place a statue
2863 * @param t town to search in
2864 * @param flags Used to check if the statue must be built or not.
2865 * @return Empty cost or an error.
2867 static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
2869 static const uint STATUE_NUMBER_INNER_TILES = 25; // Number of tiles in the center of the city where we try to protect houses.
2871 if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
2873 TileIndex statue_tile = INVALID_TILE;
2874 uint tile_count = 0;
2875 CircularTileIterator iter (t->xy, 9);
2876 for (TileIndex tile = iter; tile != INVALID_TILE; tile = ++iter) {
2877 tile_count++;
2879 /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2880 if (IsSteepSlope(GetTileSlope(tile))) continue;
2881 /* Don't build statues under bridges. */
2882 if (HasBridgeAbove(tile)) continue;
2884 /* A clear-able open space is always preferred. */
2885 if (IsGroundTile(tile) && TryClearTile(tile)) {
2886 statue_tile = tile;
2887 break;
2890 bool house = IsHouseTile(tile);
2892 if (tile_count <= STATUE_NUMBER_INNER_TILES) {
2893 /* Searching inside the inner circle; store first house. */
2894 if (house && statue_tile == INVALID_TILE && TryClearTile(tile)) {
2895 statue_tile = tile;
2898 /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2899 if (tile_count == STATUE_NUMBER_INNER_TILES && statue_tile != INVALID_TILE) break;
2900 } else {
2901 /* Searching outside the circle, just pick the first possible spot. */
2902 if (house && TryClearTile(tile)) {
2903 statue_tile = tile;
2904 break;
2908 if (statue_tile == INVALID_TILE) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
2910 if (flags & DC_EXEC) {
2911 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2912 DoCommand(statue_tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
2913 cur_company.Restore();
2914 BuildObject(OBJECT_STATUE, statue_tile, _current_company, t);
2915 SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
2916 MarkTileDirtyByTile(statue_tile);
2918 return CommandCost();
2921 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
2923 /* Check if it's allowed to buy the rights */
2924 if (!_settings_game.economy.fund_buildings) return CMD_ERROR;
2926 if (flags & DC_EXEC) {
2927 /* Build next tick */
2928 t->grow_counter = 1;
2929 /* And grow for 3 months */
2930 t->fund_buildings_months = 3;
2932 /* Enable growth (also checking GameScript's opinion) */
2933 UpdateTownGrowRate(t);
2935 SetWindowDirty(WC_TOWN_VIEW, t->index);
2937 return CommandCost();
2940 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
2942 /* Check if it's allowed to buy the rights */
2943 if (!_settings_game.economy.exclusive_rights) return CMD_ERROR;
2945 if (flags & DC_EXEC) {
2946 t->exclusive_counter = 12;
2947 t->exclusivity = _current_company;
2949 ModifyStationRatingAround(t->xy, _current_company, 130, 17);
2951 SetWindowClassesDirty(WC_STATION_VIEW);
2953 /* Spawn news message */
2954 AddNewsItem<ExclusiveRightsNewsItem> (t->index, Company::Get(_current_company));
2955 AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2956 Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2958 return CommandCost();
2961 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
2963 if (flags & DC_EXEC) {
2964 if (Chance16(1, 14)) {
2965 /* set as unwanted for 6 months */
2966 t->unwanted[_current_company] = 6;
2968 /* set all close by station ratings to 0 */
2969 Station *st;
2970 FOR_ALL_STATIONS(st) {
2971 if (st->town == t && st->owner == _current_company) {
2972 for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
2976 /* only show error message to the executing player. All errors are handled command.c
2977 * but this is special, because it can only 'fail' on a DC_EXEC */
2978 if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
2980 /* decrease by a lot!
2981 * ChangeTownRating is only for stuff in demolishing. Bribe failure should
2982 * be independent of any cheat settings
2984 if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
2985 t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
2986 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
2988 } else {
2989 ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
2992 return CommandCost();
2995 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
2996 static TownActionProc * const _town_action_proc[] = {
2997 TownActionAdvertiseSmall,
2998 TownActionAdvertiseMedium,
2999 TownActionAdvertiseLarge,
3000 TownActionRoadRebuild,
3001 TownActionBuildStatue,
3002 TownActionFundBuildings,
3003 TownActionBuyRights,
3004 TownActionBribe
3008 * Get a list of available actions to do at a town.
3009 * @param nump if not NULL add put the number of available actions in it
3010 * @param cid the company that is querying the town
3011 * @param t the town that is queried
3012 * @return bitmasked value of enabled actions
3014 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
3016 int num = 0;
3017 TownActions buttons = TACT_NONE;
3019 /* Spectators and unwanted have no options */
3020 if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3022 /* Things worth more than this are not shown */
3023 Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3025 /* Check the action bits for validity and
3026 * if they are valid add them */
3027 for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3028 const TownActions cur = (TownActions)(1 << i);
3030 /* Is the company not able to bribe ? */
3031 if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3033 /* Is the company not able to buy exclusive rights ? */
3034 if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3036 /* Is the company not able to fund buildings ? */
3037 if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3039 /* Is the company not able to fund local road reconstruction? */
3040 if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3042 /* Is the company not able to build a statue ? */
3043 if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3045 if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3046 buttons |= cur;
3047 num++;
3052 if (nump != NULL) *nump = num;
3053 return buttons;
3057 * Do a town action.
3058 * This performs an action such as advertising, building a statue, funding buildings,
3059 * but also bribing the town-council
3060 * @param tile unused
3061 * @param flags type of operation
3062 * @param p1 town to do the action at
3063 * @param p2 action to perform, @see _town_action_proc for the list of available actions
3064 * @param text unused
3065 * @return the cost of this operation or an error
3067 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3069 Town *t = Town::GetIfValid(p1);
3070 if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3072 if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
3074 CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3076 CommandCost ret = _town_action_proc[p2](t, flags);
3077 if (ret.Failed()) return ret;
3079 if (flags & DC_EXEC) {
3080 SetWindowDirty(WC_TOWN_AUTHORITY, p1);
3083 return cost;
3086 static void UpdateTownRating(Town *t)
3088 /* Increase company ratings if they're low */
3089 const Company *c;
3090 FOR_ALL_COMPANIES(c) {
3091 if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3092 t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3096 const Station *st;
3097 FOR_ALL_STATIONS(st) {
3098 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3099 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3100 if (Company::IsValidID(st->owner)) {
3101 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3102 t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3104 } else {
3105 if (Company::IsValidID(st->owner)) {
3106 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3107 t->ratings[st->owner] = max(new_rating, INT16_MIN);
3113 /* clamp all ratings to valid values */
3114 for (uint i = 0; i < MAX_COMPANIES; i++) {
3115 t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3118 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3121 static void UpdateTownGrowRate(Town *t)
3123 ClrBit(t->flags, TOWN_IS_GROWING);
3124 SetWindowDirty(WC_TOWN_VIEW, t->index);
3126 if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3128 if (t->fund_buildings_months == 0) {
3129 /* Check if all goals are reached for this town to grow (given we are not funding it) */
3130 for (int i = TE_BEGIN; i < TE_END; i++) {
3131 switch (t->goal[i]) {
3132 case TOWN_GROWTH_WINTER:
3133 if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3134 break;
3135 case TOWN_GROWTH_DESERT:
3136 if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3137 break;
3138 default:
3139 if (t->goal[i] > t->received[i].old_act) return;
3140 break;
3145 if ((t->growth_rate & TOWN_GROW_RATE_CUSTOM) != 0) {
3146 if (t->growth_rate != TOWN_GROW_RATE_CUSTOM_NONE) SetBit(t->flags, TOWN_IS_GROWING);
3147 SetWindowDirty(WC_TOWN_VIEW, t->index);
3148 return;
3152 * Towns are processed every TOWN_GROWTH_TICKS ticks, and this is the
3153 * number of times towns are processed before a new building is built.
3155 static const uint16 _grow_count_values[2][6] = {
3156 { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3157 { 320, 420, 300, 220, 160, 100 } // Normal values
3160 int n = 0;
3162 const Station *st;
3163 FOR_ALL_STATIONS(st) {
3164 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3165 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3166 n++;
3171 uint16 m;
3173 if (t->fund_buildings_months != 0) {
3174 m = _grow_count_values[0][min(n, 5)];
3175 } else {
3176 m = _grow_count_values[1][min(n, 5)];
3177 if (n == 0 && !Chance16(1, 12)) return;
3180 /* Use the normal growth rate values if new buildings have been funded in
3181 * this town and the growth rate is set to none. */
3182 uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3184 m >>= growth_multiplier;
3185 if (t->larger_town) m /= 2;
3187 t->growth_rate = m / (t->cache.num_houses / 50 + 1);
3188 t->grow_counter = min(t->growth_rate, t->grow_counter);
3190 SetBit(t->flags, TOWN_IS_GROWING);
3191 SetWindowDirty(WC_TOWN_VIEW, t->index);
3194 static void UpdateTownAmounts(Town *t)
3196 for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3197 for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3198 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3200 SetWindowDirty(WC_TOWN_VIEW, t->index);
3203 static void UpdateTownUnwanted(Town *t)
3205 const Company *c;
3207 FOR_ALL_COMPANIES(c) {
3208 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3213 * Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
3214 * @param tile The tile where the station shall be constructed.
3215 * @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
3216 * @return Succeeded or failed command.
3218 CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
3220 if (!Company::IsValidID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return CommandCost();
3222 Town *t = LocalAuthorityTownFromTile(tile);
3223 if (t == NULL) return CommandCost();
3225 if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3227 SetDParam(0, t->index);
3228 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3232 * Return the town closest to the given tile.
3233 * @param tile Starting point of the search.
3234 * @return Closest town to \a tile, or \c NULL if there are no towns.
3236 * @note This function only uses distance, the #ClosestTownFromTile function also takes town ownership into account.
3238 Town *CalcClosestTownFromTile(TileIndex tile)
3240 Town *t;
3241 uint best = UINT_MAX;
3242 Town *best_town = NULL;
3244 FOR_ALL_TOWNS(t) {
3245 uint dist = DistanceManhattan(tile, t->xy);
3246 if (dist < best) {
3247 best = dist;
3248 best_town = t;
3252 return best_town;
3256 * Return the town closest (in distance or ownership) to a given tile, within a given threshold.
3257 * @param tile Starting point of the search.
3258 * @param threshold Biggest allowed distance to the town.
3259 * @return Closest town to \a tile within \a threshold, or \c NULL if there is no such town.
3261 * @note If you only care about distance, you can use the #CalcClosestTownFromTile function.
3263 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3265 if (IsHouseTile(tile)) {
3266 return Town::GetByTile(tile);
3267 } else if (IsRoadTile(tile) || IsLevelCrossingTile(tile)) {
3268 if (HasTownOwnedRoad(tile)) return Town::GetByTile(tile);
3270 TownID tid = GetTownIndex(tile);
3272 if (tid == (TownID)INVALID_TOWN) {
3273 /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3274 if (_generating_world) return threshold == UINT_MAX ? CalcClosestTownFromTile(tile) : Town::find_closest<DistanceManhattan> (tile, threshold - 1);
3275 assert(Town::GetNumItems() == 0);
3276 return NULL;
3279 assert(Town::IsValidID(tid));
3280 Town *town = Town::Get(tid);
3282 if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
3284 return town;
3287 return threshold == UINT_MAX ? CalcClosestTownFromTile(tile) : Town::find_closest<DistanceManhattan> (tile, threshold - 1);
3290 static bool _town_rating_test = false; ///< If \c true, town rating is in test-mode.
3291 static SmallMap<const Town *, int, 4> _town_test_ratings; ///< Map of towns to modified ratings, while in town rating test-mode.
3294 * Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
3295 * The function is safe to use in nested calls.
3296 * @param mode Test mode switch (\c true means go to test-mode, \c false means leave test-mode).
3298 void SetTownRatingTestMode(bool mode)
3300 static int ref_count = 0; // Number of times test-mode is switched on.
3301 if (mode) {
3302 if (ref_count == 0) {
3303 _town_test_ratings.Clear();
3305 ref_count++;
3306 } else {
3307 assert(ref_count > 0);
3308 ref_count--;
3310 _town_rating_test = !(ref_count == 0);
3314 * Get the rating of a town for the #_current_company.
3315 * @param t Town to get the rating from.
3316 * @return Rating of the current company in the given town.
3318 static int GetRating(const Town *t)
3320 if (_town_rating_test) {
3321 SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3322 if (it != _town_test_ratings.End()) {
3323 return it->second;
3326 return t->ratings[_current_company];
3330 * Changes town rating of the current company
3331 * @param t Town to affect
3332 * @param add Value to add
3333 * @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be achievable with this change.
3334 * @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
3336 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3338 /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3339 if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3340 !Company::IsValidID(_current_company) ||
3341 (_cheats.magic_bulldozer.value && add < 0)) {
3342 return;
3345 int rating = GetRating(t);
3346 if (add < 0) {
3347 if (rating > max) {
3348 rating += add;
3349 if (rating < max) rating = max;
3351 } else {
3352 if (rating < max) {
3353 rating += add;
3354 if (rating > max) rating = max;
3357 if (_town_rating_test) {
3358 _town_test_ratings[t] = rating;
3359 } else {
3360 SetBit(t->have_ratings, _current_company);
3361 t->ratings[_current_company] = rating;
3362 SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
3367 * Does the town authority allow the (destructive) action of the current company?
3368 * @param flags Checking flags of the command.
3369 * @param t Town that must allow the company action.
3370 * @param type Type of action that is wanted.
3371 * @return A succeeded command if the action is allowed, a failed command if it is not allowed.
3373 CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
3375 /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3376 if (t == NULL || !Company::IsValidID(_current_company) ||
3377 _cheats.magic_bulldozer.value || (flags & DC_NO_TEST_TOWN_RATING)) {
3378 return CommandCost();
3381 /* minimum rating needed to be allowed to remove stuff */
3382 static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3383 /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3384 { RATING_ROAD_NEEDED_PERMISSIVE, RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE}, // Permissive
3385 { RATING_ROAD_NEEDED_NEUTRAL, RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL}, // Neutral
3386 { RATING_ROAD_NEEDED_HOSTILE, RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE}, // Hostile
3389 /* check if you're allowed to remove the road/bridge/tunnel
3390 * owned by a town no removal if rating is lower than ... depends now on
3391 * difficulty setting. Minimum town rating selected by difficulty level
3393 int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3395 if (GetRating(t) < needed) {
3396 SetDParam(0, t->index);
3397 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3400 return CommandCost();
3403 void TownsMonthlyLoop()
3405 Town *t;
3407 FOR_ALL_TOWNS(t) {
3408 if (t->road_build_months != 0) t->road_build_months--;
3410 if (t->exclusive_counter != 0) {
3411 if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3414 UpdateTownAmounts(t);
3415 UpdateTownRating(t);
3416 UpdateTownGrowRate(t);
3417 UpdateTownUnwanted(t);
3418 UpdateTownCargoes(t);
3421 UpdateTownCargoBitmap();
3424 void TownsYearlyLoop()
3426 /* Increment house ages */
3427 for (TileIndex t = 0; t < MapSize(); t++) {
3428 if (!IsHouseTile(t)) continue;
3429 IncrementHouseAge(t);
3433 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3435 if (AutoslopeEnabled()) {
3436 HouseID house = GetHouseType(tile);
3437 GetHouseNorthPart(house); // modifies house to the ID of the north tile
3438 const HouseSpec *hs = HouseSpec::Get(house);
3440 /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3441 if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3442 (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3443 bool allow_terraform = true;
3445 /* Call the autosloping callback per tile, not for the whole building at once. */
3446 house = GetHouseType(tile);
3447 hs = HouseSpec::Get(house);
3448 if (HasBit(hs->callback_mask, CBM_HOUSE_AUTOSLOPE)) {
3449 /* If the callback fails, allow autoslope. */
3450 uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3451 if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3454 if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3458 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3461 /** Tile callback functions for a town */
3462 extern const TileTypeProcs _tile_type_town_procs = {
3463 DrawTile_Town, // draw_tile_proc
3464 GetSlopePixelZ_Town, // get_slope_z_proc
3465 ClearTile_Town, // clear_tile_proc
3466 AddAcceptedCargo_Town, // add_accepted_cargo_proc
3467 GetTileDesc_Town, // get_tile_desc_proc
3468 NULL, // get_tile_railway_status_proc
3469 NULL, // get_tile_road_status_proc
3470 NULL, // get_tile_waterway_status_proc
3471 NULL, // click_tile_proc
3472 AnimateTile_Town, // animate_tile_proc
3473 TileLoop_Town, // tile_loop_proc
3474 ChangeTileOwner_Town, // change_tile_owner_proc
3475 AddProducedCargo_Town, // add_produced_cargo_proc
3476 GetFoundation_Town, // get_foundation_proc
3477 TerraformTile_Town, // terraform_tile_proc
3481 HouseSpec _house_specs[NUM_HOUSES];
3483 void ResetHouses()
3485 memset(&_house_specs, 0, sizeof(_house_specs));
3486 memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3488 /* Reset any overrides that have been set. */
3489 _house_mngr.ResetOverride();