OpenTTD Source  14.1
town_cmd.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 #include "road.h"
12 #include "road_internal.h" /* Cleaning up road bits */
13 #include "road_cmd.h"
14 #include "landscape.h"
15 #include "viewport_func.h"
16 #include "viewport_kdtree.h"
17 #include "command_func.h"
18 #include "company_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "waypoint_base.h"
22 #include "station_kdtree.h"
23 #include "company_base.h"
24 #include "news_func.h"
25 #include "error.h"
26 #include "object.h"
27 #include "genworld.h"
28 #include "newgrf_debug.h"
29 #include "newgrf_house.h"
30 #include "newgrf_text.h"
31 #include "autoslope.h"
32 #include "tunnelbridge_map.h"
33 #include "strings_func.h"
34 #include "window_func.h"
35 #include "string_func.h"
36 #include "newgrf_cargo.h"
37 #include "cheat_type.h"
38 #include "animated_tile_func.h"
39 #include "subsidy_func.h"
40 #include "core/pool_func.hpp"
41 #include "town.h"
42 #include "town_kdtree.h"
43 #include "townname_func.h"
44 #include "core/random_func.hpp"
45 #include "core/backup_type.hpp"
46 #include "depot_base.h"
47 #include "object_map.h"
48 #include "object_base.h"
49 #include "ai/ai.hpp"
50 #include "game/game.hpp"
51 #include "town_cmd.h"
52 #include "landscape_cmd.h"
53 #include "road_cmd.h"
54 #include "terraform_cmd.h"
55 #include "tunnelbridge_cmd.h"
56 #include "timer/timer.h"
59 #include "timer/timer_game_tick.h"
60 
61 #include "table/strings.h"
62 #include "table/town_land.h"
63 
64 #include "safeguards.h"
65 
66 /* Initialize the town-pool */
67 TownPool _town_pool("Town");
69 
70 
71 TownKdtree _town_kdtree(&Kdtree_TownXYFunc);
72 
73 void RebuildTownKdtree()
74 {
75  std::vector<TownID> townids;
76  for (const Town *town : Town::Iterate()) {
77  townids.push_back(town->index);
78  }
79  _town_kdtree.Build(townids.begin(), townids.end());
80 }
81 
82 
92 static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
93 {
94  if (!IsTileOwner(tile, OWNER_TOWN)) return false;
95 
97  bool town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
98 
99  if (!town_owned) {
100  /* Or other adjacent road */
102  town_owned = IsTileType(adjacent, MP_ROAD) && IsTileOwner(adjacent, OWNER_TOWN) && GetTownIndex(adjacent) == t->index;
103  }
104 
105  return town_owned;
106 }
107 
109 {
110  if (CleaningPool()) return;
111 
112  /* Delete town authority window
113  * and remove from list of sorted towns */
115 
116 #ifdef WITH_ASSERT
117  /* Check no industry is related to us. */
118  for (const Industry *i : Industry::Iterate()) {
119  assert(i->town != this);
120  }
121 
122  /* ... and no object is related to us. */
123  for (const Object *o : Object::Iterate()) {
124  assert(o->town != this);
125  }
126 #endif /* WITH_ASSERT */
127 
128  /* Check no tile is related to us. */
129  for (TileIndex tile = 0; tile < Map::Size(); ++tile) {
130  switch (GetTileType(tile)) {
131  case MP_HOUSE:
132  assert(GetTownIndex(tile) != this->index);
133  break;
134 
135  case MP_ROAD:
136  assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
137  break;
138 
139  case MP_TUNNELBRIDGE:
140  assert(!TestTownOwnsBridge(tile, this));
141  break;
142 
143  default:
144  break;
145  }
146  }
147 
148  /* Clear the persistent storage list. */
149  this->psa_list.clear();
150 
155 }
156 
157 
163 {
164  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
166 
167  /* Give objects a new home! */
168  for (Object *o : Object::Iterate()) {
169  if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
170  }
171 }
172 
178 {
179  if (layout != TL_RANDOM) {
180  this->layout = layout;
181  return;
182  }
183 
184  this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1));
185 }
186 
191 /* static */ Town *Town::GetRandom()
192 {
193  if (Town::GetNumItems() == 0) return nullptr;
194  int num = RandomRange((uint16_t)Town::GetNumItems());
195  size_t index = MAX_UVALUE(size_t);
196 
197  while (num >= 0) {
198  num--;
199  index++;
200 
201  /* Make sure we have a valid town */
202  while (!Town::IsValidID(index)) {
203  index++;
204  assert(index < Town::GetPoolSize());
205  }
206  }
207 
208  return Town::Get(index);
209 }
210 
211 void Town::FillCachedName() const
212 {
213  this->cached_name = GetTownName(this);
214 }
215 
221 {
222  return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
223 }
224 
225 /* Local */
226 static int _grow_town_result;
227 
228 /* The possible states of town growth. */
229 enum TownGrowthResult {
230  GROWTH_SUCCEED = -1,
231  GROWTH_SEARCH_STOPPED = 0
232 // GROWTH_SEARCH_RUNNING >= 1
233 };
234 
235 static bool BuildTownHouse(Town *t, TileIndex tile);
236 static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout);
237 
238 static void TownDrawHouseLift(const TileInfo *ti)
239 {
240  AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
241 }
242 
243 typedef void TownDrawTileProc(const TileInfo *ti);
244 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
245  TownDrawHouseLift
246 };
247 
254 {
256 }
257 
262 static void DrawTile_Town(TileInfo *ti)
263 {
264  HouseID house_id = GetHouseType(ti->tile);
265 
266  if (house_id >= NEW_HOUSE_OFFSET) {
267  /* Houses don't necessarily need new graphics. If they don't have a
268  * spritegroup associated with them, then the sprite for the substitute
269  * house id is drawn instead. */
270  if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != nullptr) {
271  DrawNewHouseTile(ti, house_id);
272  return;
273  } else {
274  house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
275  }
276  }
277 
278  /* Retrieve pointer to the draw town tile struct */
279  const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
280 
282 
283  DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
284 
285  /* If houses are invisible, do not draw the upper part */
286  if (IsInvisibilitySet(TO_HOUSES)) return;
287 
288  /* Add a house on top of the ground? */
289  SpriteID image = dcts->building.sprite;
290  if (image != 0) {
291  AddSortableSpriteToDraw(image, dcts->building.pal,
292  ti->x + dcts->subtile_x,
293  ti->y + dcts->subtile_y,
294  dcts->width,
295  dcts->height,
296  dcts->dz,
297  ti->z,
299  );
300 
301  if (IsTransparencySet(TO_HOUSES)) return;
302  }
303 
304  {
305  int proc = dcts->draw_proc - 1;
306 
307  if (proc >= 0) _town_draw_tile_procs[proc](ti);
308  }
309 }
310 
311 static int GetSlopePixelZ_Town(TileIndex tile, uint, uint, bool)
312 {
313  return GetTileMaxPixelZ(tile);
314 }
315 
322 {
323  HouseID hid = GetHouseType(tile);
324 
325  /* For NewGRF house tiles we might not be drawing a foundation. We need to
326  * account for this, as other structures should
327  * draw the wall of the foundation in this case.
328  */
329  if (hid >= NEW_HOUSE_OFFSET) {
330  const HouseSpec *hs = HouseSpec::Get(hid);
331  if (hs->grf_prop.spritegroup[0] != nullptr && HasBit(hs->callback_mask, CBM_HOUSE_DRAW_FOUNDATIONS)) {
332  uint32_t callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
333  if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
334  }
335  }
336  return FlatteningFoundation(tileh);
337 }
338 
345 static void AnimateTile_Town(TileIndex tile)
346 {
347  if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
348  AnimateNewHouseTile(tile);
349  return;
350  }
351 
352  if (TimerGameTick::counter & 3) return;
353 
354  /* If the house is not one with a lift anymore, then stop this animating.
355  * Not exactly sure when this happens, but probably when a house changes.
356  * Before this was just a return...so it'd leak animated tiles..
357  * That bug seems to have been here since day 1?? */
358  if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
359  DeleteAnimatedTile(tile);
360  return;
361  }
362 
363  if (!LiftHasDestination(tile)) {
364  uint i;
365 
366  /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
367  * This is due to the fact that the first floor is, in the graphics,
368  * the height of 2 'normal' floors.
369  * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
370  do {
371  i = RandomRange(7);
372  } while (i == 1 || i * 6 == GetLiftPosition(tile));
373 
374  SetLiftDestination(tile, i);
375  }
376 
377  int pos = GetLiftPosition(tile);
378  int dest = GetLiftDestination(tile) * 6;
379  pos += (pos < dest) ? 1 : -1;
380  SetLiftPosition(tile, pos);
381 
382  if (pos == dest) {
383  HaltLift(tile);
384  DeleteAnimatedTile(tile);
385  }
386 
387  MarkTileDirtyByTile(tile);
388 }
389 
396 static bool IsCloseToTown(TileIndex tile, uint dist)
397 {
398  if (_town_kdtree.Count() == 0) return false;
399  Town *t = Town::Get(_town_kdtree.FindNearest(TileX(tile), TileY(tile)));
400  return DistanceManhattan(tile, t->xy) < dist;
401 }
402 
405 {
406  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
407 
408  if (this->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(this->index));
409 
410  SetDParam(0, this->index);
411  SetDParam(1, this->cache.population);
412  this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
413  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
414  STR_VIEWPORT_TOWN_TINY_WHITE);
415 
416  _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(this->index));
417 
419 }
420 
423 {
424  for (Town *t : Town::Iterate()) {
425  t->UpdateVirtCoord();
426  }
427 }
428 
431 {
432  for (Town *t : Town::Iterate()) {
433  t->cached_name.clear();
434  }
435 }
436 
442 static void ChangePopulation(Town *t, int mod)
443 {
444  t->cache.population += mod;
445  InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
447 
448  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_POPULATION_CHANGE);
449 }
450 
456 {
457  uint32_t pop = 0;
458  for (const Town *t : Town::Iterate()) pop += t->cache.population;
459  return pop;
460 }
461 
469 static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
470 {
471  for (StationList::iterator it = t->stations_near.begin(); it != t->stations_near.end(); /* incremented inside loop */) {
472  const Station *st = *it;
473 
474  bool covers_area = st->TileIsInCatchment(tile);
475  if (flags & BUILDING_2_TILES_Y) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(0, 1));
476  if (flags & BUILDING_2_TILES_X) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 0));
477  if (flags & BUILDING_HAS_4_TILES) covers_area |= st->TileIsInCatchment(tile + TileDiffXY(1, 1));
478 
479  if (covers_area && !st->CatchmentCoversTown(t->index)) {
480  it = t->stations_near.erase(it);
481  } else {
482  ++it;
483  }
484  }
485 }
486 
492 {
493  assert(IsTileType(tile, MP_HOUSE));
494 
495  /* Progress in construction stages */
497  if (GetHouseConstructionTick(tile) != 0) return;
498 
499  AnimateNewHouseConstruction(tile);
500 
501  if (IsHouseCompleted(tile)) {
502  /* Now that construction is complete, we can add the population of the
503  * building to the town. */
504  ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
505  ResetHouseAge(tile);
506  }
507  MarkTileDirtyByTile(tile);
508 }
509 
515 {
516  uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
517  if (flags & BUILDING_HAS_1_TILE) AdvanceSingleHouseConstruction(TILE_ADDXY(tile, 0, 0));
518  if (flags & BUILDING_2_TILES_Y) AdvanceSingleHouseConstruction(TILE_ADDXY(tile, 0, 1));
519  if (flags & BUILDING_2_TILES_X) AdvanceSingleHouseConstruction(TILE_ADDXY(tile, 1, 0));
520  if (flags & BUILDING_HAS_4_TILES) AdvanceSingleHouseConstruction(TILE_ADDXY(tile, 1, 1));
521 }
522 
531 static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool affected_by_recession)
532 {
533  if (amount == 0) return;
534 
535  /* All production is halved during a recession (except for NewGRF-supplied town cargo). */
536  if (affected_by_recession && EconomyIsInRecession()) {
537  amount = (amount + 1) >> 1;
538  }
539 
540  /* Scale by cargo scale setting. */
541  amount = ScaleByCargoScale(amount, true);
542 
543  /* Actually generate cargo and update town statistics. */
544  t->supplied[ct].new_max += amount;
545  t->supplied[ct].new_act += MoveGoodsToStation(ct, amount, SourceType::Town, t->index, stations.GetStations());;
546 }
547 
555 static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
556 {
557  for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
558  uint32_t r = Random();
559  if (GB(r, 0, 8) < rate) {
560  CargoID cid = cs->Index();
561  uint amt = (GB(r, 0, 8) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR) / 8 + 1;
562 
563  TownGenerateCargo(t, cid, amt, stations, true);
564  }
565  }
566 }
567 
575 static void TownGenerateCargoBinominal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
576 {
577  for (const CargoSpec *cs : CargoSpec::town_production_cargoes[tpe]) {
578  CargoID cid = cs->Index();
579  uint32_t r = Random();
580 
581  /* Make a bitmask with up to 32 bits set, one for each potential pax. */
582  int genmax = (rate + 7) / 8;
583  uint32_t genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
584 
585  /* Mask random value by potential pax and count number of actual pax. */
586  uint amt = CountBits(r & genmask) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR;
587 
588  TownGenerateCargo(t, cid, amt, stations, true);
589  }
590 }
591 
598 static void TileLoop_Town(TileIndex tile)
599 {
600  HouseID house_id = GetHouseType(tile);
601 
602  /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
603  * doesn't exist any more, so don't continue here. */
604  if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
605 
606  if (!IsHouseCompleted(tile)) {
607  /* Construction is not completed, so we advance a construction stage. */
609  return;
610  }
611 
612  const HouseSpec *hs = HouseSpec::Get(house_id);
613 
614  /* If the lift has a destination, it is already an animated tile. */
615  if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
616  house_id < NEW_HOUSE_OFFSET &&
617  !LiftHasDestination(tile) &&
618  Chance16(1, 2)) {
619  AddAnimatedTile(tile);
620  }
621 
622  Town *t = Town::GetByTile(tile);
623  uint32_t r = Random();
624 
625  StationFinder stations(TileArea(tile, 1, 1));
626 
628  for (uint i = 0; i < 256; i++) {
629  uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
630 
631  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
632 
633  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
634  if (!IsValidCargoID(cargo)) continue;
635 
636  uint amt = GB(callback, 0, 8);
637  if (amt == 0) continue;
638 
639  /* NewGRF-supplied town cargos are not affected by recessions. */
640  TownGenerateCargo(t, cargo, amt, stations, false);
641  }
642  } else {
644  case TCGM_ORIGINAL:
645  /* Original (quadratic) cargo generation algorithm */
648  break;
649 
650  case TCGM_BITCOUNT:
651  /* Binomial distribution per tick, by a series of coin flips */
652  /* Reduce generation rate to a 1/4, using tile bits to spread out distribution.
653  * As tick counter is incremented by 256 between each call, we ignore the lower 8 bits. */
654  if (GB(TimerGameTick::counter, 8, 2) == GB(tile.base(), 0, 2)) {
657  }
658  break;
659 
660  default:
661  NOT_REACHED();
662  }
663  }
664 
665  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
666 
667  if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
669  CanDeleteHouse(tile) &&
670  GetHouseAge(tile) >= hs->minimum_life &&
671  --t->time_until_rebuild == 0) {
672  t->time_until_rebuild = GB(r, 16, 8) + 192;
673 
674  ClearTownHouse(t, tile);
675 
676  /* Rebuild with another house? */
677  if (GB(r, 24, 8) >= 12) {
678  /* If we are multi-tile houses, make sure to replace the house
679  * closest to city center. If we do not do this, houses tend to
680  * wander away from roads and other houses. */
681  if (hs->building_flags & BUILDING_HAS_2_TILES) {
682  /* House tiles are always the most north tile. Move the new
683  * house to the south if we are north of the city center. */
684  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
685  int x = Clamp(grid_pos.x, 0, 1);
686  int y = Clamp(grid_pos.y, 0, 1);
687 
688  if (hs->building_flags & TILE_SIZE_2x2) {
689  tile = TILE_ADDXY(tile, x, y);
690  } else if (hs->building_flags & TILE_SIZE_1x2) {
691  tile = TILE_ADDXY(tile, 0, y);
692  } else if (hs->building_flags & TILE_SIZE_2x1) {
693  tile = TILE_ADDXY(tile, x, 0);
694  }
695  }
696 
697  BuildTownHouse(t, tile);
698  }
699  }
700 
701  cur_company.Restore();
702 }
703 
711 {
712  if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
713  if (!CanDeleteHouse(tile)) return CMD_ERROR;
714 
715  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
716 
718  cost.AddCost(hs->GetRemovalCost());
719 
720  int rating = hs->remove_rating_decrease;
721  Town *t = Town::GetByTile(tile);
722 
724  if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) &&
726  SetDParam(0, t->index);
727  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
728  }
729  }
730 
731  ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
732  if (flags & DC_EXEC) {
733  ClearTownHouse(t, tile);
734  }
735 
736  return cost;
737 }
738 
739 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
740 {
741  HouseID house_id = GetHouseType(tile);
742  const HouseSpec *hs = HouseSpec::Get(house_id);
743  Town *t = Town::GetByTile(tile);
744 
746  for (uint i = 0; i < 256; i++) {
747  uint16_t callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
748 
749  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
750 
751  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
752 
753  if (!IsValidCargoID(cargo)) continue;
754  produced[cargo]++;
755  }
756  } else {
757  if (hs->population > 0) {
759  produced[cs->Index()]++;
760  }
761  }
762  if (hs->mail_generation > 0) {
764  produced[cs->Index()]++;
765  }
766  }
767  }
768 }
769 
770 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes *always_accepted)
771 {
772  if (!IsValidCargoID(cargo) || amount == 0) return;
773  acceptance[cargo] += amount;
774  SetBit(*always_accepted, cargo);
775 }
776 
777 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
778 {
779  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
780  CargoID accepts[lengthof(hs->accepts_cargo)];
781 
782  /* Set the initial accepted cargo types */
783  for (uint8_t i = 0; i < lengthof(accepts); i++) {
784  accepts[i] = hs->accepts_cargo[i];
785  }
786 
787  /* Check for custom accepted cargo types */
789  uint16_t callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
790  if (callback != CALLBACK_FAILED) {
791  /* Replace accepted cargo types with translated values from callback */
792  accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
793  accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
794  accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
795  }
796  }
797 
798  /* Check for custom cargo acceptance */
800  uint16_t callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
801  if (callback != CALLBACK_FAILED) {
802  AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
803  AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
804  if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
805  /* The 'S' bit indicates food instead of goods */
806  AddAcceptedCargoSetMask(GetCargoIDByLabel(CT_FOOD), GB(callback, 8, 4), acceptance, always_accepted);
807  } else {
808  AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
809  }
810  return;
811  }
812  }
813 
814  /* No custom acceptance, so fill in with the default values */
815  for (uint8_t i = 0; i < lengthof(accepts); i++) {
816  AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
817  }
818 }
819 
820 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
821 {
822  const HouseID house = GetHouseType(tile);
823  const HouseSpec *hs = HouseSpec::Get(house);
824  bool house_completed = IsHouseCompleted(tile);
825 
826  td->str = hs->building_name;
827 
828  uint16_t callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
829  if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
830  if (callback_res > 0x400) {
832  } else {
833  StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
834  if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
835  td->str = new_name;
836  }
837  }
838  }
839 
840  if (!house_completed) {
841  td->dparam = td->str;
842  td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
843  }
844 
845  if (hs->grf_prop.grffile != nullptr) {
846  const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
847  td->grf = gc->GetName();
848  }
849 
850  td->owner[0] = OWNER_TOWN;
851 }
852 
853 static TrackStatus GetTileTrackStatus_Town(TileIndex, TransportType, uint, DiagDirection)
854 {
855  /* not used */
856  return 0;
857 }
858 
859 static void ChangeTileOwner_Town(TileIndex, Owner, Owner)
860 {
861  /* not used */
862 }
863 
864 static bool GrowTown(Town *t);
865 
870 static void TownTickHandler(Town *t)
871 {
872  if (HasBit(t->flags, TOWN_IS_GROWING)) {
873  int i = (int)t->grow_counter - 1;
874  if (i < 0) {
875  if (GrowTown(t)) {
876  i = t->growth_rate;
877  } else {
878  /* If growth failed wait a bit before retrying */
879  i = std::min<uint16_t>(t->growth_rate, Ticks::TOWN_GROWTH_TICKS - 1);
880  }
881  }
882  t->grow_counter = i;
883  }
884 }
885 
888 {
889  if (_game_mode == GM_EDITOR) return;
890 
891  for (Town *t : Town::Iterate()) {
892  TownTickHandler(t);
893  }
894 }
895 
902 {
903  if (IsRoadDepotTile(tile) || IsBayRoadStopTile(tile)) return ROAD_NONE;
904 
905  return GetAnyRoadBits(tile, RTT_ROAD, true);
906 }
907 
913 {
914  RoadType best_rt = ROADTYPE_ROAD;
915  const RoadTypeInfo *best = nullptr;
916  const uint16_t assume_max_speed = 50;
917 
918  for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
919  if (RoadTypeIsTram(rt)) continue;
920 
921  const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
922 
923  /* Unused road type. */
924  if (rti->label == 0) continue;
925 
926  /* Can town build this road. */
927  if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue;
928 
929  /* Not yet introduced at this date. */
931 
932  if (best != nullptr) {
933  if ((rti->max_speed == 0 ? assume_max_speed : rti->max_speed) < (best->max_speed == 0 ? assume_max_speed : best->max_speed)) continue;
934  }
935 
936  best_rt = rt;
937  best = rti;
938  }
939 
940  return best_rt;
941 }
942 
947 static TimerGameCalendar::Date GetTownRoadTypeFirstIntroductionDate()
948 {
949  const RoadTypeInfo *best = nullptr;
950  for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
951  if (RoadTypeIsTram(rt)) continue;
952  const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
953  if (rti->label == 0) continue; // Unused road type.
954  if (!HasBit(rti->flags, ROTF_TOWN_BUILD)) continue; // Town can't build this road type.
955 
956  if (best != nullptr && rti->introduction_date >= best->introduction_date) continue;
957  best = rti;
958  }
959 
960  if (best == nullptr) return INT32_MAX;
961  return best->introduction_date;
962 }
963 
969 {
970  auto min_date = GetTownRoadTypeFirstIntroductionDate();
971  if (min_date <= TimerGameCalendar::date) return true;
972 
973  if (min_date < INT32_MAX) {
974  SetDParam(0, min_date);
975  ShowErrorMessage(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET, STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET_EXPLANATION, WL_CRITICAL);
976  } else {
977  ShowErrorMessage(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL, STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL_EXPLANATION, WL_CRITICAL);
978  }
979  return false;
980 }
981 
992 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
993 {
994  if (!IsValidTile(tile)) return false;
995 
996  /* Lookup table for the used diff values */
997  const TileIndexDiff tid_lt[3] = {
1001  };
1002 
1003  dist_multi = (dist_multi + 1) * 4;
1004  for (uint pos = 4; pos < dist_multi; pos++) {
1005  /* Go (pos / 4) tiles to the left or the right */
1006  TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
1007 
1008  /* Use the current tile as origin, or go one tile backwards */
1009  if (pos & 2) cur += tid_lt[2];
1010 
1011  /* Test for roadbit parallel to dir and facing towards the middle axis */
1012  if (IsValidTile(tile + cur) &&
1013  GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
1014  }
1015  return false;
1016 }
1017 
1026 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
1027 {
1028  if (DistanceFromEdge(tile) == 0) return false;
1029 
1030  /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
1031  if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
1032 
1033  /* Check if there already is a road at this point? */
1034  if (GetTownRoadBits(tile) == ROAD_NONE) {
1035  /* No, try if we are able to build a road piece there.
1036  * If that fails clear the land, and if that fails exit.
1037  * This is to make sure that we can build a road here later. */
1038  RoadType rt = GetTownRoadType();
1039  if (Command<CMD_BUILD_ROAD>::Do(DC_AUTO | DC_NO_WATER, tile, (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X, rt, DRD_NONE, 0).Failed() &&
1041  return false;
1042  }
1043  }
1044 
1046  bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
1047  if (cur_slope == SLOPE_FLAT) return ret;
1048 
1049  /* If the tile is not a slope in the right direction, then
1050  * maybe terraform some. */
1051  Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
1052  if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
1053  if (Chance16(1, 8)) {
1054  CommandCost res = CMD_ERROR;
1055  if (!_generating_world && Chance16(1, 10)) {
1056  /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
1058  tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, false));
1059  }
1060  if (res.Failed() && Chance16(1, 3)) {
1061  /* We can consider building on the slope, though. */
1062  return ret;
1063  }
1064  }
1065  return false;
1066  }
1067  return ret;
1068 }
1069 
1070 static bool TerraformTownTile(TileIndex tile, Slope edges, bool dir)
1071 {
1072  assert(tile < Map::Size());
1073 
1074  CommandCost r = std::get<0>(Command<CMD_TERRAFORM_LAND>::Do(DC_AUTO | DC_NO_WATER, tile, edges, dir));
1075  if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
1077  return true;
1078 }
1079 
1080 static void LevelTownLand(TileIndex tile)
1081 {
1082  assert(tile < Map::Size());
1083 
1084  /* Don't terraform if land is plain or if there's a house there. */
1085  if (IsTileType(tile, MP_HOUSE)) return;
1086  Slope tileh = GetTileSlope(tile);
1087  if (tileh == SLOPE_FLAT) return;
1088 
1089  /* First try up, then down */
1090  if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, true)) {
1091  TerraformTownTile(tile, tileh & SLOPE_ELEVATED, false);
1092  }
1093 }
1094 
1104 {
1105  /* align the grid to the downtown */
1106  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
1107  RoadBits rcmd = ROAD_NONE;
1108 
1109  switch (t->layout) {
1110  default: NOT_REACHED();
1111 
1112  case TL_2X2_GRID:
1113  if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
1114  if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
1115  break;
1116 
1117  case TL_3X3_GRID:
1118  if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
1119  if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
1120  break;
1121  }
1122 
1123  /* Optimise only X-junctions */
1124  if (rcmd != ROAD_ALL) return rcmd;
1125 
1126  RoadBits rb_template;
1127 
1128  switch (GetTileSlope(tile)) {
1129  default: rb_template = ROAD_ALL; break;
1130  case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
1131  case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
1132  case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
1133  case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
1134  case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
1135  case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
1136  case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
1137  case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
1138  case SLOPE_STEEP_W:
1139  case SLOPE_STEEP_S:
1140  case SLOPE_STEEP_E:
1141  case SLOPE_STEEP_N:
1142  rb_template = ROAD_NONE;
1143  break;
1144  }
1145 
1146  /* Stop if the template is compatible to the growth dir */
1147  if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
1148  /* If not generate a straight road in the direction of the growth */
1150 }
1151 
1163 {
1164  /* We can't look further than that. */
1165  if (DistanceFromEdge(tile) == 0) return false;
1166 
1167  uint counter = 0; // counts the house neighbor tiles
1168 
1169  /* Check the tiles E,N,W and S of the current tile for houses */
1170  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1171  /* Count both void and house tiles for checking whether there
1172  * are enough houses in the area. This to make it likely that
1173  * houses get build up to the edge of the map. */
1174  switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1175  case MP_HOUSE:
1176  case MP_VOID:
1177  counter++;
1178  break;
1179 
1180  default:
1181  break;
1182  }
1183 
1184  /* If there are enough neighbors stop here */
1185  if (counter >= 3) {
1186  if (BuildTownHouse(t, tile)) {
1187  _grow_town_result = GROWTH_SUCCEED;
1188  return true;
1189  }
1190  return false;
1191  }
1192  }
1193  return false;
1194 }
1195 
1204 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1205 {
1206  RoadType rt = GetTownRoadType();
1207  if (Command<CMD_BUILD_ROAD>::Do(DC_EXEC | DC_AUTO | DC_NO_WATER, tile, rcmd, rt, DRD_NONE, t->index).Succeeded()) {
1208  _grow_town_result = GROWTH_SUCCEED;
1209  return true;
1210  }
1211  return false;
1212 }
1213 
1223 static bool CanRoadContinueIntoNextTile(const Town *t, const TileIndex tile, const DiagDirection road_dir)
1224 {
1225  const int delta = TileOffsByDiagDir(road_dir); // +1 tile in the direction of the road
1226  TileIndex next_tile = tile + delta; // The tile beyond which must be connectable to the target tile
1227  RoadBits rcmd = DiagDirToRoadBits(ReverseDiagDir(road_dir));
1228  RoadType rt = GetTownRoadType();
1229 
1230  /* Before we try anything, make sure the tile is on the map and not the void. */
1231  if (!IsValidTile(next_tile)) return false;
1232 
1233  /* If the next tile is a bridge or tunnel, allow if it's continuing in the same direction. */
1234  if (IsTileType(next_tile, MP_TUNNELBRIDGE)) {
1235  return GetTunnelBridgeTransportType(next_tile) == TRANSPORT_ROAD && GetTunnelBridgeDirection(next_tile) == road_dir;
1236  }
1237 
1238  /* If the next tile is a station, allow if it's a road station facing the proper direction. Otherwise return false. */
1239  if (IsTileType(next_tile, MP_STATION)) {
1240  /* If the next tile is a road station, allow if it can be entered by the new tunnel/bridge, otherwise disallow. */
1241  return IsRoadStop(next_tile) && (GetRoadStopDir(next_tile) == ReverseDiagDir(road_dir) || (IsDriveThroughStopTile(next_tile) && GetRoadStopDir(next_tile) == road_dir));
1242  }
1243 
1244  /* If the next tile is a road depot, allow if it's facing the right way. */
1245  if (IsTileType(next_tile, MP_ROAD)) {
1246  return IsRoadDepot(next_tile) && GetRoadDepotDirection(next_tile) == ReverseDiagDir(road_dir);
1247  }
1248 
1249  /* If the next tile is a railroad track, check if towns are allowed to build level crossings.
1250  * If level crossing are not allowed, reject the construction. Else allow DoCommand to determine if the rail track is buildable. */
1251  if (IsTileType(next_tile, MP_RAILWAY) && !_settings_game.economy.allow_town_level_crossings) return false;
1252 
1253  /* If a road tile can be built, the construction is allowed. */
1254  return Command<CMD_BUILD_ROAD>::Do(DC_AUTO | DC_NO_WATER, next_tile, rcmd, rt, DRD_NONE, t->index).Succeeded();
1255 }
1256 
1263 static bool RedundantBridgeExistsNearby(TileIndex tile, void *user_data)
1264 {
1265  /* Don't look into the void. */
1266  if (!IsValidTile(tile)) return false;
1267 
1268  /* Only consider bridge head tiles. */
1269  if (!IsBridgeTile(tile)) return false;
1270 
1271  /* Only consider road bridges. */
1272  if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return false;
1273 
1274  /* If the bridge is facing the same direction as the proposed bridge, we've found a redundant bridge. */
1275  return (GetTileSlope(tile) & InclinedSlope(ReverseDiagDir(*(DiagDirection *)user_data)));
1276 }
1277 
1288 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1289 {
1290  assert(bridge_dir < DIAGDIR_END);
1291 
1292  const Slope slope = GetTileSlope(tile);
1293 
1294  /* Make sure the direction is compatible with the slope.
1295  * Well we check if the slope has an up bit set in the
1296  * reverse direction. */
1297  if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1298 
1299  /* Assure that the bridge is connectable to the start side */
1300  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1301 
1302  /* We are in the right direction */
1303  uint bridge_length = 0; // This value stores the length of the possible bridge
1304  TileIndex bridge_tile = tile; // Used to store the other waterside
1305 
1306  const int delta = TileOffsByDiagDir(bridge_dir);
1307 
1308  /* To prevent really small towns from building disproportionately
1309  * long bridges, make the max a function of its population. */
1310  const uint TOWN_BRIDGE_LENGTH_CAP = 11;
1311  uint base_bridge_length = 5;
1312  uint max_bridge_length = std::min(t->cache.population / 1000 + base_bridge_length, TOWN_BRIDGE_LENGTH_CAP);
1313 
1314  if (slope == SLOPE_FLAT) {
1315  /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1316  do {
1317  if (bridge_length++ >= base_bridge_length) {
1318  /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1319  return false;
1320  }
1321  bridge_tile += delta;
1322  } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1323  } else {
1324  do {
1325  if (bridge_length++ >= max_bridge_length) {
1326  /* Ensure the bridge is not longer than the max allowed length. */
1327  return false;
1328  }
1329  bridge_tile += delta;
1330  } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1331  }
1332 
1333  /* Don't allow a bridge where the start and end tiles are adjacent with no span between. */
1334  if (bridge_length == 1) return false;
1335 
1336  /* Make sure the road can be continued past the bridge. At this point, bridge_tile holds the end tile of the bridge. */
1337  if (!CanRoadContinueIntoNextTile(t, bridge_tile, bridge_dir)) return false;
1338 
1339  /* If another parallel bridge exists nearby, this one would be redundant and shouldn't be built. We don't care about flat bridges. */
1340  TileIndex search = tile;
1341  DiagDirection direction_to_match = bridge_dir;
1342  if (slope != SLOPE_FLAT && CircularTileSearch(&search, bridge_length, 0, 0, RedundantBridgeExistsNearby, &direction_to_match)) return false;
1343 
1344  for (uint8_t times = 0; times <= 22; times++) {
1345  byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1346 
1347  /* Can we actually build the bridge? */
1348  RoadType rt = GetTownRoadType();
1349  if (Command<CMD_BUILD_BRIDGE>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_BRIDGE>()), tile, bridge_tile, TRANSPORT_ROAD, bridge_type, rt).Succeeded()) {
1350  Command<CMD_BUILD_BRIDGE>::Do(DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_BRIDGE>()), tile, bridge_tile, TRANSPORT_ROAD, bridge_type, rt);
1351  _grow_town_result = GROWTH_SUCCEED;
1352  return true;
1353  }
1354  }
1355  /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1356  return false;
1357 }
1358 
1369 static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
1370 {
1371  assert(tunnel_dir < DIAGDIR_END);
1372 
1373  Slope slope = GetTileSlope(tile);
1374 
1375  /* Only consider building a tunnel if the starting tile is sloped properly. */
1376  if (slope != InclinedSlope(tunnel_dir)) return false;
1377 
1378  /* Assure that the tunnel is connectable to the start side */
1379  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(tunnel_dir))) & DiagDirToRoadBits(tunnel_dir))) return false;
1380 
1381  const int delta = TileOffsByDiagDir(tunnel_dir);
1382  int max_tunnel_length = 0;
1383 
1384  /* There are two conditions for building tunnels: Under a mountain and under an obstruction. */
1385  if (CanRoadContinueIntoNextTile(t, tile, tunnel_dir)) {
1386  /* Only tunnel under a mountain if the slope is continuous for at least 4 tiles. We want tunneling to be a last resort for large hills. */
1387  TileIndex slope_tile = tile;
1388  for (uint8_t tiles = 0; tiles < 4; tiles++) {
1389  if (!IsValidTile(slope_tile)) return false;
1390  slope = GetTileSlope(slope_tile);
1391  if (slope != InclinedSlope(tunnel_dir) && !IsSteepSlope(slope) && !IsSlopeWithOneCornerRaised(slope)) return false;
1392  slope_tile += delta;
1393  }
1394 
1395  /* More population means longer tunnels, but make sure we can at least cover the smallest mountain which neccesitates tunneling. */
1396  max_tunnel_length = (t->cache.population / 1000) + 7;
1397  } else {
1398  /* When tunneling under an obstruction, the length limit is 5, enough to tunnel under a four-track railway. */
1399  max_tunnel_length = 5;
1400  }
1401 
1402  uint8_t tunnel_length = 0;
1403  TileIndex tunnel_tile = tile; // Iteratator to store the other end tile of the tunnel.
1404 
1405  /* Find the end tile of the tunnel for length and continuation checks. */
1406  do {
1407  if (tunnel_length++ >= max_tunnel_length) return false;
1408  tunnel_tile += delta;
1409  /* The tunnel ends when start and end tiles are the same height. */
1410  } while (IsValidTile(tunnel_tile) && GetTileZ(tile) != GetTileZ(tunnel_tile));
1411 
1412  /* Don't allow a tunnel where the start and end tiles are adjacent. */
1413  if (tunnel_length == 1) return false;
1414 
1415  /* Make sure the road can be continued past the tunnel. At this point, tunnel_tile holds the end tile of the tunnel. */
1416  if (!CanRoadContinueIntoNextTile(t, tunnel_tile, tunnel_dir)) return false;
1417 
1418  /* Attempt to build the tunnel. Return false if it fails to let the town build a road instead. */
1419  RoadType rt = GetTownRoadType();
1420  if (Command<CMD_BUILD_TUNNEL>::Do(CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_TUNNEL>()), tile, TRANSPORT_ROAD, rt).Succeeded()) {
1421  Command<CMD_BUILD_TUNNEL>::Do(DC_EXEC | CommandFlagsToDCFlags(GetCommandFlags<CMD_BUILD_TUNNEL>()), tile, TRANSPORT_ROAD, rt);
1422  _grow_town_result = GROWTH_SUCCEED;
1423  return true;
1424  }
1425 
1426  return false;
1427 }
1428 
1435 static inline bool RoadTypesAllowHouseHere(TileIndex t)
1436 {
1437  static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1438  bool allow = false;
1439 
1440  for (const TileIndexDiffC *ptr = tiles; ptr != endof(tiles); ++ptr) {
1441  TileIndex cur_tile = t + ToTileIndexDiff(*ptr);
1442  if (!IsValidTile(cur_tile)) continue;
1443 
1444  if (!(IsTileType(cur_tile, MP_ROAD) || IsRoadStopTile(cur_tile))) continue;
1445  allow = true;
1446 
1447  RoadType road_rt = GetRoadTypeRoad(cur_tile);
1448  RoadType tram_rt = GetRoadTypeTram(cur_tile);
1449  if (road_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(road_rt)->flags, ROTF_NO_HOUSES)) return true;
1450  if (tram_rt != INVALID_ROADTYPE && !HasBit(GetRoadTypeInfo(tram_rt)->flags, ROTF_NO_HOUSES)) return true;
1451  }
1452 
1453  /* If no road was found surrounding the tile we can allow building the house since there is
1454  * nothing which forbids it, if a road was found but the execution reached this point, then
1455  * all the found roads don't allow houses to be built */
1456  return !allow;
1457 }
1458 
1463 static bool TownCanGrowRoad(TileIndex tile)
1464 {
1465  if (!IsTileType(tile, MP_ROAD)) return true;
1466 
1467  /* Allow extending on roadtypes which can be built by town, or if the road type matches the type the town will build. */
1468  RoadType rt = GetRoadTypeRoad(tile);
1469  return HasBit(GetRoadTypeInfo(rt)->flags, ROTF_TOWN_BUILD) || GetTownRoadType() == rt;
1470 }
1471 
1476 static inline bool TownAllowedToBuildRoads()
1477 {
1478  return _settings_game.economy.allow_town_roads || _generating_world || _game_mode == GM_EDITOR;
1479 }
1480 
1498 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1499 {
1500  RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1501  TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1502 
1503  assert(tile < Map::Size());
1504 
1505  if (cur_rb == ROAD_NONE) {
1506  /* Tile has no road. First reset the status counter
1507  * to say that this is the last iteration. */
1508  _grow_town_result = GROWTH_SEARCH_STOPPED;
1509 
1510  if (!TownAllowedToBuildRoads()) return;
1512 
1513  /* Remove hills etc */
1514  if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1515 
1516  /* Is a road allowed here? */
1517  switch (t1->layout) {
1518  default: NOT_REACHED();
1519 
1520  case TL_3X3_GRID:
1521  case TL_2X2_GRID:
1522  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1523  if (rcmd == ROAD_NONE) return;
1524  break;
1525 
1526  case TL_BETTER_ROADS:
1527  case TL_ORIGINAL:
1528  if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1529 
1530  DiagDirection source_dir = ReverseDiagDir(target_dir);
1531 
1532  if (Chance16(1, 4)) {
1533  /* Randomize a new target dir */
1534  do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1535  }
1536 
1537  if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1538  /* A road is not allowed to continue the randomized road,
1539  * return if the road we're trying to build is curved. */
1540  if (target_dir != ReverseDiagDir(source_dir)) return;
1541 
1542  /* Return if neither side of the new road is a house */
1545  return;
1546  }
1547 
1548  /* That means that the road is only allowed if there is a house
1549  * at any side of the new road. */
1550  }
1551 
1552  rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1553  break;
1554  }
1555 
1556  } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1557  if (!TownCanGrowRoad(tile)) return;
1558 
1559  /* Continue building on a partial road.
1560  * Should be always OK, so we only generate
1561  * the fitting RoadBits */
1562  _grow_town_result = GROWTH_SEARCH_STOPPED;
1563 
1564  if (!TownAllowedToBuildRoads()) return;
1565 
1566  switch (t1->layout) {
1567  default: NOT_REACHED();
1568 
1569  case TL_3X3_GRID:
1570  case TL_2X2_GRID:
1571  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1572  break;
1573 
1574  case TL_BETTER_ROADS:
1575  case TL_ORIGINAL:
1576  rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1577  break;
1578  }
1579  } else {
1580  bool allow_house = true; // Value which decides if we want to construct a house
1581 
1582  /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1583  * it is the starting tile. Half the time, we stay on this side then.*/
1584  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1585  if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1586  *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1587  }
1588  return;
1589  }
1590 
1591  /* Possibly extend the road in a direction.
1592  * Randomize a direction and if it has a road, bail out. */
1593  target_dir = RandomDiagDir();
1594  RoadBits target_rb = DiagDirToRoadBits(target_dir);
1595  TileIndex house_tile; // position of a possible house
1596 
1597  if (cur_rb & target_rb) {
1598  /* If it's a road turn possibly build a house in a corner.
1599  * Use intersection with straight road as an indicator
1600  * that we randomed corner house position.
1601  * A turn (and we check for that later) always has only
1602  * one common bit with a straight road so it has the same
1603  * chance to be chosen as the house on the side of a road.
1604  */
1605  if ((cur_rb & ROAD_X) != target_rb) return;
1606 
1607  /* Check whether it is a turn and if so determine
1608  * position of the corner tile */
1609  switch (cur_rb) {
1610  case ROAD_N:
1611  house_tile = TileAddByDir(tile, DIR_S);
1612  break;
1613  case ROAD_S:
1614  house_tile = TileAddByDir(tile, DIR_N);
1615  break;
1616  case ROAD_E:
1617  house_tile = TileAddByDir(tile, DIR_W);
1618  break;
1619  case ROAD_W:
1620  house_tile = TileAddByDir(tile, DIR_E);
1621  break;
1622  default:
1623  return; // not a turn
1624  }
1625  target_dir = DIAGDIR_END;
1626  } else {
1627  house_tile = TileAddByDiagDir(tile, target_dir);
1628  }
1629 
1630  /* Don't walk into water. */
1631  if (HasTileWaterGround(house_tile)) return;
1632 
1633  if (!IsValidTile(house_tile)) return;
1634 
1635  if (target_dir != DIAGDIR_END && TownAllowedToBuildRoads()) {
1636  switch (t1->layout) {
1637  default: NOT_REACHED();
1638 
1639  case TL_3X3_GRID: // Use 2x2 grid afterwards!
1640  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1641  [[fallthrough]];
1642 
1643  case TL_2X2_GRID:
1644  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1645  allow_house = (rcmd & target_rb) == ROAD_NONE;
1646  break;
1647 
1648  case TL_BETTER_ROADS: // Use original afterwards!
1649  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1650  [[fallthrough]];
1651 
1652  case TL_ORIGINAL:
1653  /* Allow a house at the edge. 60% chance or
1654  * always ok if no road allowed. */
1655  rcmd = target_rb;
1656  allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1657  break;
1658  }
1659  }
1660 
1661  allow_house &= RoadTypesAllowHouseHere(house_tile);
1662 
1663  if (allow_house) {
1664  /* Build a house, but not if there already is a house there. */
1665  if (!IsTileType(house_tile, MP_HOUSE)) {
1666  /* Level the land if possible */
1667  if (Chance16(1, 6)) LevelTownLand(house_tile);
1668 
1669  /* And build a house.
1670  * Set result to -1 if we managed to build it. */
1671  if (BuildTownHouse(t1, house_tile)) {
1672  _grow_town_result = GROWTH_SUCCEED;
1673  }
1674  }
1675  return;
1676  }
1677 
1678  if (!TownCanGrowRoad(tile)) return;
1679 
1680  _grow_town_result = GROWTH_SEARCH_STOPPED;
1681  }
1682 
1683  /* Return if a water tile */
1684  if (HasTileWaterGround(tile)) return;
1685 
1686  /* Make the roads look nicer */
1687  rcmd = CleanUpRoadBits(tile, rcmd);
1688  if (rcmd == ROAD_NONE) return;
1689 
1690  /* Only use the target direction for bridges and tunnels to ensure they're connected.
1691  * The target_dir is as computed previously according to town layout, so
1692  * it will match it perfectly. */
1693  if (GrowTownWithBridge(t1, tile, target_dir)) return;
1694  if (GrowTownWithTunnel(t1, tile, target_dir)) return;
1695 
1696  GrowTownWithRoad(t1, tile, rcmd);
1697 }
1698 
1706 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1707 {
1708  TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1709  if (!IsValidTile(target_tile)) return false;
1710  if (HasTileWaterGround(target_tile)) return false;
1711 
1712  RoadBits target_rb = GetTownRoadBits(target_tile);
1713  if (TownAllowedToBuildRoads()) {
1714  /* Check whether a road connection exists or can be build. */
1715  switch (GetTileType(target_tile)) {
1716  case MP_ROAD:
1717  return target_rb != ROAD_NONE;
1718 
1719  case MP_STATION:
1720  return IsDriveThroughStopTile(target_tile);
1721 
1722  case MP_TUNNELBRIDGE:
1723  return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1724 
1725  case MP_HOUSE:
1726  case MP_INDUSTRY:
1727  case MP_OBJECT:
1728  return false;
1729 
1730  default:
1731  /* Checked for void and water earlier */
1732  return true;
1733  }
1734  } else {
1735  /* Check whether a road connection already exists,
1736  * and it leads somewhere else. */
1737  RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1738  return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1739  }
1740 }
1741 
1748 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1749 {
1750  /* Special case.
1751  * @see GrowTownInTile Check the else if
1752  */
1753  DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1754 
1755  assert(tile < Map::Size());
1756 
1757  /* Number of times to search.
1758  * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1759  * them a little handicap. */
1760  switch (t->layout) {
1761  case TL_BETTER_ROADS:
1762  _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1763  break;
1764 
1765  case TL_3X3_GRID:
1766  case TL_2X2_GRID:
1767  _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1768  break;
1769 
1770  default:
1771  _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1772  break;
1773  }
1774 
1775  do {
1776  RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1777 
1778  /* Try to grow the town from this point */
1779  GrowTownInTile(&tile, cur_rb, target_dir, t);
1780  if (_grow_town_result == GROWTH_SUCCEED) return true;
1781 
1782  /* Exclude the source position from the bitmask
1783  * and return if no more road blocks available */
1784  if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1785  if (cur_rb == ROAD_NONE) return false;
1786 
1787  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1788  /* Only build in the direction away from the tunnel or bridge. */
1789  target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1790  } else {
1791  /* Select a random bit from the blockmask, walk a step
1792  * and continue the search from there. */
1793  do {
1794  if (cur_rb == ROAD_NONE) return false;
1795  RoadBits target_bits;
1796  do {
1797  target_dir = RandomDiagDir();
1798  target_bits = DiagDirToRoadBits(target_dir);
1799  } while (!(cur_rb & target_bits));
1800  cur_rb &= ~target_bits;
1801  } while (!CanFollowRoad(tile, target_dir));
1802  }
1803  tile = TileAddByDiagDir(tile, target_dir);
1804 
1805  if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, RTT_ROAD)) {
1806  /* Don't allow building over roads of other cities */
1807  if (IsRoadOwner(tile, RTT_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1808  return false;
1809  } else if (IsRoadOwner(tile, RTT_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1810  /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1811  * owner :) (happy happy happy road now) */
1812  SetRoadOwner(tile, RTT_ROAD, OWNER_TOWN);
1813  SetTownIndex(tile, t->index);
1814  }
1815  }
1816 
1817  /* Max number of times is checked. */
1818  } while (--_grow_town_result >= 0);
1819 
1820  return false;
1821 }
1822 
1831 {
1832  uint32_t r = Random();
1833  uint a = GB(r, 0, 2);
1834  uint b = GB(r, 8, 2);
1835  if (a == b) b ^= 2;
1836  return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1837 }
1838 
1844 static bool GrowTown(Town *t)
1845 {
1846  static const TileIndexDiffC _town_coord_mod[] = {
1847  {-1, 0},
1848  { 1, 1},
1849  { 1, -1},
1850  {-1, -1},
1851  {-1, 0},
1852  { 0, 2},
1853  { 2, 0},
1854  { 0, -2},
1855  {-1, -1},
1856  {-2, 2},
1857  { 2, 2},
1858  { 2, -2},
1859  { 0, 0}
1860  };
1861 
1862  /* Current "company" is a town */
1863  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1864 
1865  TileIndex tile = t->xy; // The tile we are working with ATM
1866 
1867  /* Find a road that we can base the construction on. */
1868  const TileIndexDiffC *ptr;
1869  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1870  if (GetTownRoadBits(tile) != ROAD_NONE) {
1871  bool success = GrowTownAtRoad(t, tile);
1872  cur_company.Restore();
1873  return success;
1874  }
1875  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1876  }
1877 
1878  /* No road available, try to build a random road block by
1879  * clearing some land and then building a road there. */
1880  if (TownAllowedToBuildRoads()) {
1881  tile = t->xy;
1882  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1883  /* Only work with plain land that not already has a house */
1884  if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1885  if (Command<CMD_LANDSCAPE_CLEAR>::Do(DC_AUTO | DC_NO_WATER, tile).Succeeded()) {
1886  RoadType rt = GetTownRoadType();
1888  cur_company.Restore();
1889  return true;
1890  }
1891  }
1892  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1893  }
1894  }
1895 
1896  cur_company.Restore();
1897  return false;
1898 }
1899 
1905 {
1906  static const uint32_t _town_squared_town_zone_radius_data[23][HZB_END] = {
1907  { 4, 0, 0, 0, 0}, // 0
1908  { 16, 0, 0, 0, 0},
1909  { 25, 0, 0, 0, 0},
1910  { 36, 0, 0, 0, 0},
1911  { 49, 0, 4, 0, 0},
1912  { 64, 0, 4, 0, 0}, // 20
1913  { 64, 0, 9, 0, 1},
1914  { 64, 0, 9, 0, 4},
1915  { 64, 0, 16, 0, 4},
1916  { 81, 0, 16, 0, 4},
1917  { 81, 0, 16, 0, 4}, // 40
1918  { 81, 0, 25, 0, 9},
1919  { 81, 36, 25, 0, 9},
1920  { 81, 36, 25, 16, 9},
1921  { 81, 49, 0, 25, 9},
1922  { 81, 64, 0, 25, 9}, // 60
1923  { 81, 64, 0, 36, 9},
1924  { 81, 64, 0, 36, 16},
1925  {100, 81, 0, 49, 16},
1926  {100, 81, 0, 49, 25},
1927  {121, 81, 0, 49, 25}, // 80
1928  {121, 81, 0, 49, 25},
1929  {121, 81, 0, 49, 36}, // 88
1930  };
1931 
1932  if (t->cache.num_houses < 92) {
1933  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));
1934  } else {
1935  int mass = t->cache.num_houses / 8;
1936  /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1937  * The offsets are to make sure the radii do not decrease in size when going from the table
1938  * to the calculated value.*/
1939  t->cache.squared_town_zone_radius[HZB_TOWN_EDGE] = mass * 15 - 40;
1940  t->cache.squared_town_zone_radius[HZB_TOWN_OUTSKIRT] = mass * 9 - 15;
1941  t->cache.squared_town_zone_radius[HZB_TOWN_OUTER_SUBURB] = 0;
1942  t->cache.squared_town_zone_radius[HZB_TOWN_INNER_SUBURB] = mass * 5 - 5;
1943  t->cache.squared_town_zone_radius[HZB_TOWN_CENTRE] = mass * 3 + 5;
1944  }
1945 }
1946 
1952 {
1954  t->supplied[cs->Index()].old_max = ScaleByCargoScale(t->cache.population >> 3, true);
1955  }
1957  t->supplied[cs->Index()].old_max = ScaleByCargoScale(t->cache.population >> 4, true);
1958  }
1959 }
1960 
1961 static void UpdateTownGrowthRate(Town *t);
1962 static void UpdateTownGrowth(Town *t);
1963 
1975 static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1976 {
1977  t->xy = tile;
1978  t->cache.num_houses = 0;
1979  t->time_until_rebuild = 10;
1980  UpdateTownRadius(t);
1981  t->flags = 0;
1982  t->cache.population = 0;
1983  /* Spread growth across ticks so even if there are many
1984  * similar towns they're unlikely to grow all in one tick */
1986  t->growth_rate = TownTicksToGameTicks(250);
1987  t->show_zone = false;
1988 
1989  _town_kdtree.Insert(t->index);
1990 
1991  /* Set the default cargo requirement for town growth */
1993  case LT_ARCTIC:
1995  break;
1996 
1997  case LT_TROPIC:
2000  break;
2001  }
2002 
2003  t->fund_buildings_months = 0;
2004 
2005  for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
2006 
2007  t->have_ratings = 0;
2009  t->exclusive_counter = 0;
2010  t->statues = 0;
2011 
2012  {
2014  t->townnamegrfid = tnp.grfid;
2015  t->townnametype = tnp.type;
2016  }
2017  t->townnameparts = townnameparts;
2018 
2019  t->UpdateVirtCoord();
2020  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
2021 
2022  t->InitializeLayout(layout);
2023 
2024  t->larger_town = city;
2025 
2026  int x = (int)size * 16 + 3;
2027  if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
2028  /* Don't create huge cities when founding town in-game */
2029  if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
2030 
2031  t->cache.num_houses += x;
2032  UpdateTownRadius(t);
2033 
2034  int i = x * 4;
2035  do {
2036  GrowTown(t);
2037  } while (--i);
2038 
2039  t->cache.num_houses -= x;
2040  UpdateTownRadius(t);
2042  UpdateTownMaxPass(t);
2044 }
2045 
2052 {
2053  /* Check if too close to the edge of map */
2054  if (DistanceFromEdge(tile) < 12) {
2055  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
2056  }
2057 
2058  /* Check distance to all other towns. */
2059  if (IsCloseToTown(tile, 20)) {
2060  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
2061  }
2062 
2063  /* Can only build on clear flat areas, possibly with trees. */
2064  if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
2065  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2066  }
2067 
2068  return CommandCost(EXPENSES_OTHER);
2069 }
2070 
2076 static bool IsUniqueTownName(const std::string &name)
2077 {
2078  for (const Town *t : Town::Iterate()) {
2079  if (!t->name.empty() && t->name == name) return false;
2080  }
2081 
2082  return true;
2083 }
2084 
2097 std::tuple<CommandCost, Money, TownID> CmdFoundTown(DoCommandFlag flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
2098 {
2100 
2101  if (size >= TSZ_END) return { CMD_ERROR, 0, INVALID_TOWN };
2102  if (layout >= NUM_TLS) return { CMD_ERROR, 0, INVALID_TOWN };
2103 
2104  /* Some things are allowed only in the scenario editor and for game scripts. */
2105  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
2106  if (_settings_game.economy.found_town == TF_FORBIDDEN) return { CMD_ERROR, 0, INVALID_TOWN };
2107  if (size == TSZ_LARGE) return { CMD_ERROR, 0, INVALID_TOWN };
2108  if (random_location) return { CMD_ERROR, 0, INVALID_TOWN };
2110  return { CMD_ERROR, 0, INVALID_TOWN };
2111  }
2112  } else if (_current_company == OWNER_DEITY && random_location) {
2113  /* Random parameter is not allowed for Game Scripts. */
2114  return { CMD_ERROR, 0, INVALID_TOWN };
2115  }
2116 
2117  if (text.empty()) {
2118  /* If supplied name is empty, townnameparts has to generate unique automatic name */
2119  if (!VerifyTownName(townnameparts, &par)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE), 0, INVALID_TOWN };
2120  } else {
2121  /* If name is not empty, it has to be unique custom name */
2122  if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return { CMD_ERROR, 0, INVALID_TOWN };
2123  if (!IsUniqueTownName(text)) return { CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE), 0, INVALID_TOWN };
2124  }
2125 
2126  /* Allocate town struct */
2127  if (!Town::CanAllocateItem()) return { CommandCost(STR_ERROR_TOO_MANY_TOWNS), 0, INVALID_TOWN };
2128 
2129  if (!random_location) {
2130  CommandCost ret = TownCanBePlacedHere(tile);
2131  if (ret.Failed()) return { ret, 0, INVALID_TOWN };
2132  }
2133 
2134  static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
2135  /* multidimensional arrays have to have defined length of non-first dimension */
2136  static_assert(lengthof(price_mult[0]) == 4);
2137 
2138  CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
2139  byte mult = price_mult[city][size];
2140 
2141  cost.MultiplyCost(mult);
2142 
2143  /* Create the town */
2144  TownID new_town = INVALID_TOWN;
2145  if (flags & DC_EXEC) {
2146  if (cost.GetCost() > GetAvailableMoneyForCommand()) {
2147  return { CommandCost(EXPENSES_OTHER), cost.GetCost(), INVALID_TOWN };
2148  }
2149 
2150  Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
2152  Town *t;
2153  if (random_location) {
2154  t = CreateRandomTown(20, townnameparts, size, city, layout);
2155  if (t == nullptr) {
2156  cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
2157  } else {
2158  new_town = t->index;
2159  }
2160  } else {
2161  t = new Town(tile);
2162  DoCreateTown(t, tile, townnameparts, size, city, layout, true);
2163  }
2165  old_generating_world.Restore();
2166 
2167  if (t != nullptr && !text.empty()) {
2168  t->name = text;
2169  t->UpdateVirtCoord();
2170  }
2171 
2172  if (_game_mode != GM_EDITOR) {
2173  /* 't' can't be nullptr since 'random' is false outside scenedit */
2174  assert(!random_location);
2175 
2176  if (_current_company == OWNER_DEITY) {
2177  SetDParam(0, t->index);
2178  AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED, NT_INDUSTRY_OPEN, tile);
2179  } else {
2181  NewsStringData *company_name = new NewsStringData(GetString(STR_COMPANY_NAME));
2182 
2183  SetDParamStr(0, company_name->string);
2184  SetDParam(1, t->index);
2185 
2186  AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, company_name);
2187  }
2188  AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
2189  Game::NewEvent(new ScriptEventTownFounded(t->index));
2190  }
2191  }
2192  return { cost, 0, new_town };
2193 }
2194 
2205 {
2206  switch (layout) {
2207  case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
2208  case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
2209  default: return tile;
2210  }
2211 }
2212 
2222 static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
2223 {
2224  switch (layout) {
2225  case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
2226  case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
2227  default: return true;
2228  }
2229 }
2230 
2234 struct SpotData {
2236  uint max_dist;
2238 };
2239 
2256 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
2257 {
2258  SpotData *sp = (SpotData*)user_data;
2259  uint dist = GetClosestWaterDistance(tile, true);
2260 
2261  if (IsTileType(tile, MP_CLEAR) &&
2262  IsTileFlat(tile) &&
2263  IsTileAlignedToGrid(tile, sp->layout) &&
2264  dist > sp->max_dist) {
2265  sp->tile = tile;
2266  sp->max_dist = dist;
2267  }
2268 
2269  return false;
2270 }
2271 
2276 static bool FindNearestEmptyLand(TileIndex tile, void *)
2277 {
2278  return IsTileType(tile, MP_CLEAR);
2279 }
2280 
2294 {
2295  SpotData sp = { INVALID_TILE, 0, layout };
2296 
2297  TileIndex coast = tile;
2298  if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, nullptr)) {
2299  CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
2300  return sp.tile;
2301  }
2302 
2303  /* if we get here just give up */
2304  return INVALID_TILE;
2305 }
2306 
2316 static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
2317 {
2318  assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
2319 
2320  if (!Town::CanAllocateItem()) return nullptr;
2321 
2322  do {
2323  /* Generate a tile index not too close from the edge */
2324  TileIndex tile = AlignTileToGrid(RandomTile(), layout);
2325 
2326  /* if we tried to place the town on water, slide it over onto
2327  * the nearest likely-looking spot */
2328  if (IsTileType(tile, MP_WATER)) {
2329  tile = FindNearestGoodCoastalTownSpot(tile, layout);
2330  if (tile == INVALID_TILE) continue;
2331  }
2332 
2333  /* Make sure town can be placed here */
2334  if (TownCanBePlacedHere(tile).Failed()) continue;
2335 
2336  /* Allocate a town struct */
2337  Town *t = new Town(tile);
2338 
2339  DoCreateTown(t, tile, townnameparts, size, city, layout, false);
2340 
2341  /* if the population is still 0 at the point, then the
2342  * placement is so bad it couldn't grow at all */
2343  if (t->cache.population > 0) return t;
2344 
2345  Backup<CompanyID> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
2346  [[maybe_unused]] CommandCost rc = Command<CMD_DELETE_TOWN>::Do(DC_EXEC, t->index);
2347  cur_company.Restore();
2348  assert(rc.Succeeded());
2349 
2350  /* We already know that we can allocate a single town when
2351  * entering this function. However, we create and delete
2352  * a town which "resets" the allocation checks. As such we
2353  * need to check again when assertions are enabled. */
2354  assert(Town::CanAllocateItem());
2355  } while (--attempts != 0);
2356 
2357  return nullptr;
2358 }
2359 
2360 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
2361 
2369 {
2370  uint current_number = 0;
2371  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
2372  uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : Map::ScaleBySize(_num_initial_towns[difficulty] + (Random() & 7));
2373  total = std::min<uint>(TownPool::MAX_SIZE, total);
2374  uint32_t townnameparts;
2375  TownNames town_names;
2376 
2378 
2379  /* Pre-populate the town names list with the names of any towns already on the map */
2380  for (const Town *town : Town::Iterate()) {
2381  town_names.insert(town->GetCachedName());
2382  }
2383 
2384  /* First attempt will be made at creating the suggested number of towns.
2385  * Note that this is really a suggested value, not a required one.
2386  * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2387  do {
2390  /* Get a unique name for the town. */
2391  if (!GenerateTownName(_random, &townnameparts, &town_names)) continue;
2392  /* try 20 times to create a random-sized town for the first loop. */
2393  if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != nullptr) current_number++; // If creation was successful, raise a flag.
2394  } while (--total);
2395 
2396  town_names.clear();
2397 
2398  /* Build the town k-d tree again to make sure it's well balanced */
2399  RebuildTownKdtree();
2400 
2401  if (current_number != 0) return true;
2402 
2403  /* If current_number is still zero at this point, it means that not a single town has been created.
2404  * So give it a last try, but now more aggressive */
2405  if (GenerateTownName(_random, &townnameparts) &&
2406  CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != nullptr) {
2407  return true;
2408  }
2409 
2410  /* If there are no towns at all and we are generating new game, bail out */
2411  if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2412  ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2413  }
2414 
2415  return false; // we are still without a town? we failed, simply
2416 }
2417 
2418 
2425 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2426 {
2427  uint dist = DistanceSquare(tile, t->xy);
2428 
2429  if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2430 
2431  HouseZonesBits smallest = HZB_TOWN_EDGE;
2432  for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2433  if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2434  }
2435 
2436  return smallest;
2437 }
2438 
2449 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2450 {
2451  [[maybe_unused]] CommandCost cc = Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_AUTO | DC_NO_WATER, tile);
2452  assert(cc.Succeeded());
2453 
2454  IncreaseBuildingCount(t, type);
2455  MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2456  if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2457 
2458  MarkTileDirtyByTile(tile);
2459 }
2460 
2461 
2472 static void MakeTownHouse(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2473 {
2474  BuildingFlags size = HouseSpec::Get(type)->building_flags;
2475 
2476  ClearMakeHouseTile(tile, t, counter, stage, type, random_bits);
2477  if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(tile + TileDiffXY(0, 1), t, counter, stage, ++type, random_bits);
2478  if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(tile + TileDiffXY(1, 0), t, counter, stage, ++type, random_bits);
2479  if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(tile + TileDiffXY(1, 1), t, counter, stage, ++type, random_bits);
2480 
2481  ForAllStationsAroundTiles(TileArea(tile, (size & BUILDING_2_TILES_X) ? 2 : 1, (size & BUILDING_2_TILES_Y) ? 2 : 1), [t](Station *st, TileIndex) {
2482  t->stations_near.insert(st);
2483  return true;
2484  });
2485 }
2486 
2487 
2494 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2495 {
2496  /* cannot build on these slopes... */
2497  Slope slope = GetTileSlope(tile);
2498  if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2499 
2500  /* at least one RoadTypes allow building the house here? */
2501  if (!RoadTypesAllowHouseHere(tile)) return false;
2502 
2503  /* building under a bridge? */
2504  if (IsBridgeAbove(tile)) return false;
2505 
2506  /* can we clear the land? */
2507  return Command<CMD_LANDSCAPE_CLEAR>::Do(DC_AUTO | DC_NO_WATER, tile).Succeeded();
2508 }
2509 
2510 
2519 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2520 {
2521  if (!CanBuildHouseHere(tile, noslope)) return false;
2522 
2523  /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2524  if (GetTileMaxZ(tile) != z) return false;
2525 
2526  return true;
2527 }
2528 
2529 
2538 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2539 {
2540  /* we need to check this tile too because we can be at different tile now */
2541  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2542 
2543  for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2544  tile += TileOffsByDiagDir(d);
2545  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2546  }
2547 
2548  return true;
2549 }
2550 
2551 
2559 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2560 {
2561  /* Allow towns everywhere when we don't build roads */
2562  if (!TownAllowedToBuildRoads()) return true;
2563 
2564  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2565 
2566  switch (t->layout) {
2567  case TL_2X2_GRID:
2568  if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2569  break;
2570 
2571  case TL_3X3_GRID:
2572  if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2573  break;
2574 
2575  default:
2576  break;
2577  }
2578 
2579  return true;
2580 }
2581 
2582 
2590 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2591 {
2592  /* Allow towns everywhere when we don't build roads */
2593  if (!TownAllowedToBuildRoads()) return true;
2594 
2595  /* Compute relative position of tile. (Positive offsets are towards north) */
2596  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2597 
2598  switch (t->layout) {
2599  case TL_2X2_GRID:
2600  grid_pos.x %= 3;
2601  grid_pos.y %= 3;
2602  if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2603  (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2604  break;
2605 
2606  case TL_3X3_GRID:
2607  if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2608  break;
2609 
2610  default:
2611  break;
2612  }
2613 
2614  return true;
2615 }
2616 
2617 
2627 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2628 {
2629  /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2630 
2631  TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2632  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2633 
2634  tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2635  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2636  *tile = tile2;
2637  return true;
2638  }
2639 
2640  return false;
2641 }
2642 
2643 
2652 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2653 {
2654  TileIndex tile2 = *tile;
2655 
2656  for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2657  if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2658  *tile = tile2;
2659  return true;
2660  }
2661  if (d == DIAGDIR_END) break;
2662  tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2663  }
2664 
2665  return false;
2666 }
2667 
2668 
2675 static bool BuildTownHouse(Town *t, TileIndex tile)
2676 {
2677  /* forbidden building here by town layout */
2678  if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2679 
2680  /* no house allowed at all, bail out */
2681  if (!CanBuildHouseHere(tile, false)) return false;
2682 
2683  Slope slope = GetTileSlope(tile);
2684  int maxz = GetTileMaxZ(tile);
2685 
2686  /* Get the town zone type of the current tile, as well as the climate.
2687  * This will allow to easily compare with the specs of the new house to build */
2688  HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2689 
2690  /* Above snow? */
2692  if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2693 
2694  uint bitmask = (1 << rad) + (1 << (land + 12));
2695 
2696  /* bits 0-4 are used
2697  * bits 11-15 are used
2698  * bits 5-10 are not used. */
2699  HouseID houses[NUM_HOUSES];
2700  uint num = 0;
2701  uint probs[NUM_HOUSES];
2702  uint probability_max = 0;
2703 
2704  /* Generate a list of all possible houses that can be built. */
2705  for (uint i = 0; i < NUM_HOUSES; i++) {
2706  const HouseSpec *hs = HouseSpec::Get(i);
2707 
2708  /* Verify that the candidate house spec matches the current tile status */
2709  if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2710 
2711  /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2712  if (hs->class_id != HOUSE_NO_CLASS) {
2713  /* id_count is always <= class_count, so it doesn't need to be checked */
2714  if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2715  } else {
2716  /* If the house has no class, check id_count instead */
2717  if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2718  }
2719 
2720  uint cur_prob = hs->probability;
2721  probability_max += cur_prob;
2722  probs[num] = cur_prob;
2723  houses[num++] = (HouseID)i;
2724  }
2725 
2726  TileIndex baseTile = tile;
2727 
2728  while (probability_max > 0) {
2729  /* Building a multitile building can change the location of tile.
2730  * The building would still be built partially on that tile, but
2731  * its northern tile would be elsewhere. However, if the callback
2732  * fails we would be basing further work from the changed tile.
2733  * So a next 1x1 tile building could be built on the wrong tile. */
2734  tile = baseTile;
2735 
2736  uint r = RandomRange(probability_max);
2737  uint i;
2738  for (i = 0; i < num; i++) {
2739  if (probs[i] > r) break;
2740  r -= probs[i];
2741  }
2742 
2743  HouseID house = houses[i];
2744  probability_max -= probs[i];
2745 
2746  /* remove tested house from the set */
2747  num--;
2748  houses[i] = houses[num];
2749  probs[i] = probs[num];
2750 
2751  const HouseSpec *hs = HouseSpec::Get(house);
2752 
2753  if (!_generating_world && _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2754  continue;
2755  }
2756 
2757  if (TimerGameCalendar::year < hs->min_year || TimerGameCalendar::year > hs->max_year) continue;
2758 
2759  /* Special houses that there can be only one of. */
2760  uint oneof = 0;
2761 
2762  if (hs->building_flags & BUILDING_IS_CHURCH) {
2763  SetBit(oneof, TOWN_HAS_CHURCH);
2764  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2765  SetBit(oneof, TOWN_HAS_STADIUM);
2766  }
2767 
2768  if (t->flags & oneof) continue;
2769 
2770  /* Make sure there is no slope? */
2771  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2772  if (noslope && slope != SLOPE_FLAT) continue;
2773 
2774  if (hs->building_flags & TILE_SIZE_2x2) {
2775  if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2776  } else if (hs->building_flags & TILE_SIZE_2x1) {
2777  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2778  } else if (hs->building_flags & TILE_SIZE_1x2) {
2779  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2780  } else {
2781  /* 1x1 house checks are already done */
2782  }
2783 
2784  byte random_bits = Random();
2785 
2787  uint16_t callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2788  if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2789  }
2790 
2791  /* build the house */
2792  t->cache.num_houses++;
2793 
2794  /* Special houses that there can be only one of. */
2795  t->flags |= oneof;
2796 
2797  byte construction_counter = 0;
2798  byte construction_stage = 0;
2799 
2800  if (_generating_world || _game_mode == GM_EDITOR) {
2801  uint32_t construction_random = Random();
2802 
2803  construction_stage = TOWN_HOUSE_COMPLETED;
2804  if (Chance16(1, 7)) construction_stage = GB(construction_random, 0, 2);
2805 
2806  if (construction_stage == TOWN_HOUSE_COMPLETED) {
2807  ChangePopulation(t, hs->population);
2808  } else {
2809  construction_counter = GB(construction_random, 2, 2);
2810  }
2811  }
2812 
2813  MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2814  UpdateTownRadius(t);
2816 
2817  return true;
2818  }
2819 
2820  return false;
2821 }
2822 
2829 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2830 {
2831  assert(IsTileType(tile, MP_HOUSE));
2832  DecreaseBuildingCount(t, house);
2833  DoClearSquare(tile);
2834  DeleteAnimatedTile(tile);
2835 
2836  DeleteNewGRFInspectWindow(GSF_HOUSES, tile.base());
2837 }
2838 
2847 {
2848  if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2849  if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2850  house--;
2851  return TileDiffXY(-1, 0);
2852  } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2853  house--;
2854  return TileDiffXY(0, -1);
2855  } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2856  house -= 2;
2857  return TileDiffXY(-1, 0);
2858  } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2859  house -= 3;
2860  return TileDiffXY(-1, -1);
2861  }
2862  }
2863  return 0;
2864 }
2865 
2872 {
2873  assert(IsTileType(tile, MP_HOUSE));
2874 
2875  HouseID house = GetHouseType(tile);
2876 
2877  /* The northernmost tile of the house is the main house. */
2878  tile += GetHouseNorthPart(house);
2879 
2880  const HouseSpec *hs = HouseSpec::Get(house);
2881 
2882  /* Remove population from the town if the house is finished. */
2883  if (IsHouseCompleted(tile)) {
2884  ChangePopulation(t, -hs->population);
2885  }
2886 
2887  t->cache.num_houses--;
2888 
2889  /* Clear flags for houses that only may exist once/town. */
2890  if (hs->building_flags & BUILDING_IS_CHURCH) {
2892  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2894  }
2895 
2896  /* Do the actual clearing of tiles */
2897  DoClearTownHouseHelper(tile, t, house);
2898  if (hs->building_flags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2899  if (hs->building_flags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2900  if (hs->building_flags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2901 
2902  RemoveNearbyStations(t, tile, hs->building_flags);
2903 
2904  UpdateTownRadius(t);
2905 }
2906 
2914 CommandCost CmdRenameTown(DoCommandFlag flags, TownID town_id, const std::string &text)
2915 {
2916  Town *t = Town::GetIfValid(town_id);
2917  if (t == nullptr) return CMD_ERROR;
2918 
2919  bool reset = text.empty();
2920 
2921  if (!reset) {
2923  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2924  }
2925 
2926  if (flags & DC_EXEC) {
2927  t->cached_name.clear();
2928  if (reset) {
2929  t->name.clear();
2930  } else {
2931  t->name = text;
2932  }
2933 
2934  t->UpdateVirtCoord();
2935  InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_RESORT);
2936  ClearAllStationCachedNames();
2937  ClearAllIndustryCachedNames();
2939  }
2940  return CommandCost();
2941 }
2942 
2949 {
2950  for (const CargoSpec *cs : CargoSpec::Iterate()) {
2951  if (cs->town_acceptance_effect == effect) return cs;
2952  }
2953  return nullptr;
2954 }
2955 
2964 CommandCost CmdTownCargoGoal(DoCommandFlag flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
2965 {
2966  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2967 
2968  if (tae < TAE_BEGIN || tae >= TAE_END) return CMD_ERROR;
2969 
2970  Town *t = Town::GetIfValid(town_id);
2971  if (t == nullptr) return CMD_ERROR;
2972 
2973  /* Validate if there is a cargo which is the requested TownEffect */
2975  if (cargo == nullptr) return CMD_ERROR;
2976 
2977  if (flags & DC_EXEC) {
2978  t->goal[tae] = goal;
2979  UpdateTownGrowth(t);
2981  }
2982 
2983  return CommandCost();
2984 }
2985 
2993 CommandCost CmdTownSetText(DoCommandFlag flags, TownID town_id, const std::string &text)
2994 {
2995  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2996  Town *t = Town::GetIfValid(town_id);
2997  if (t == nullptr) return CMD_ERROR;
2998 
2999  if (flags & DC_EXEC) {
3000  t->text.clear();
3001  if (!text.empty()) t->text = text;
3003  }
3004 
3005  return CommandCost();
3006 }
3007 
3015 CommandCost CmdTownGrowthRate(DoCommandFlag flags, TownID town_id, uint16_t growth_rate)
3016 {
3017  if (_current_company != OWNER_DEITY) return CMD_ERROR;
3018 
3019  Town *t = Town::GetIfValid(town_id);
3020  if (t == nullptr) return CMD_ERROR;
3021 
3022  if (flags & DC_EXEC) {
3023  if (growth_rate == 0) {
3024  /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
3026  } else {
3027  uint old_rate = t->growth_rate;
3028  if (t->grow_counter >= old_rate) {
3029  /* This also catches old_rate == 0 */
3030  t->grow_counter = growth_rate;
3031  } else {
3032  /* Scale grow_counter, so half finished houses stay half finished */
3033  t->grow_counter = t->grow_counter * growth_rate / old_rate;
3034  }
3035  t->growth_rate = growth_rate;
3037  }
3038  UpdateTownGrowth(t);
3040  }
3041 
3042  return CommandCost();
3043 }
3044 
3053 CommandCost CmdTownRating(DoCommandFlag flags, TownID town_id, CompanyID company_id, int16_t rating)
3054 {
3055  if (_current_company != OWNER_DEITY) return CMD_ERROR;
3056 
3057  Town *t = Town::GetIfValid(town_id);
3058  if (t == nullptr) return CMD_ERROR;
3059 
3060  if (!Company::IsValidID(company_id)) return CMD_ERROR;
3061 
3062  int16_t new_rating = Clamp(rating, RATING_MINIMUM, RATING_MAXIMUM);
3063  if (flags & DC_EXEC) {
3064  t->ratings[company_id] = new_rating;
3066  }
3067 
3068  return CommandCost();
3069 }
3070 
3078 CommandCost CmdExpandTown(DoCommandFlag flags, TownID town_id, uint32_t grow_amount)
3079 {
3080  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
3081  Town *t = Town::GetIfValid(town_id);
3082  if (t == nullptr) return CMD_ERROR;
3083 
3084  if (flags & DC_EXEC) {
3085  /* The more houses, the faster we grow */
3086  if (grow_amount == 0) {
3087  uint amount = RandomRange(ClampTo<uint16_t>(t->cache.num_houses / 10)) + 3;
3088  t->cache.num_houses += amount;
3089  UpdateTownRadius(t);
3090 
3091  uint n = amount * 10;
3092  do GrowTown(t); while (--n);
3093 
3094  t->cache.num_houses -= amount;
3095  } else {
3096  for (; grow_amount > 0; grow_amount--) {
3097  /* Try several times to grow, as we are really suppose to grow */
3098  for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
3099  }
3100  }
3101  UpdateTownRadius(t);
3102 
3103  UpdateTownMaxPass(t);
3104  }
3105 
3106  return CommandCost();
3107 }
3108 
3116 {
3117  if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
3118  Town *t = Town::GetIfValid(town_id);
3119  if (t == nullptr) return CMD_ERROR;
3120 
3121  /* Stations refer to towns. */
3122  for (const Station *st : Station::Iterate()) {
3123  if (st->town == t) {
3124  /* Non-oil rig stations are always a problem. */
3125  if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
3126  /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
3127  CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, st->airport.tile);
3128  if (ret.Failed()) return ret;
3129  }
3130  }
3131 
3132  /* Waypoints refer to towns. */
3133  for (const Waypoint *wp : Waypoint::Iterate()) {
3134  if (wp->town == t) return CMD_ERROR;
3135  }
3136 
3137  /* Depots refer to towns. */
3138  for (const Depot *d : Depot::Iterate()) {
3139  if (d->town == t) return CMD_ERROR;
3140  }
3141 
3142  /* Check all tiles for town ownership. First check for bridge tiles, as
3143  * these do not directly have an owner so we need to check adjacent
3144  * tiles. This won't work correctly in the same loop if the adjacent
3145  * tile was already deleted earlier in the loop. */
3146  for (TileIndex current_tile = 0; current_tile < Map::Size(); ++current_tile) {
3147  if (IsTileType(current_tile, MP_TUNNELBRIDGE) && TestTownOwnsBridge(current_tile, t)) {
3148  CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, current_tile);
3149  if (ret.Failed()) return ret;
3150  }
3151  }
3152 
3153  /* Check all remaining tiles for town ownership. */
3154  for (TileIndex current_tile = 0; current_tile < Map::Size(); ++current_tile) {
3155  bool try_clear = false;
3156  switch (GetTileType(current_tile)) {
3157  case MP_ROAD:
3158  try_clear = HasTownOwnedRoad(current_tile) && GetTownIndex(current_tile) == t->index;
3159  break;
3160 
3161  case MP_HOUSE:
3162  try_clear = GetTownIndex(current_tile) == t->index;
3163  break;
3164 
3165  case MP_INDUSTRY:
3166  try_clear = Industry::GetByTile(current_tile)->town == t;
3167  break;
3168 
3169  case MP_OBJECT:
3170  if (Town::GetNumItems() == 1) {
3171  /* No towns will be left, remove it! */
3172  try_clear = true;
3173  } else {
3174  Object *o = Object::GetByTile(current_tile);
3175  if (o->town == t) {
3176  if (o->type == OBJECT_STATUE) {
3177  /* Statue... always remove. */
3178  try_clear = true;
3179  } else {
3180  /* Tell to find a new town. */
3181  if (flags & DC_EXEC) o->town = nullptr;
3182  }
3183  }
3184  }
3185  break;
3186 
3187  default:
3188  break;
3189  }
3190  if (try_clear) {
3191  CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, current_tile);
3192  if (ret.Failed()) return ret;
3193  }
3194  }
3195 
3196  /* The town destructor will delete the other things related to the town. */
3197  if (flags & DC_EXEC) {
3198  _town_kdtree.Remove(t->index);
3199  if (t->cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(t->index));
3200  delete t;
3201  }
3202 
3203  return CommandCost();
3204 }
3205 
3211  2, 4, 9, 35, 48, 53, 117, 175
3212 };
3213 
3221 {
3222  if (flags & DC_EXEC) {
3223  ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
3224  }
3225  return CommandCost();
3226 }
3227 
3235 {
3236  if (flags & DC_EXEC) {
3237  ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
3238  }
3239  return CommandCost();
3240 }
3241 
3249 {
3250  if (flags & DC_EXEC) {
3251  ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
3252  }
3253  return CommandCost();
3254 }
3255 
3263 {
3264  /* Check if the company is allowed to fund new roads. */
3266 
3267  if (flags & DC_EXEC) {
3268  t->road_build_months = 6;
3269 
3271  NewsStringData *company_name = new NewsStringData(GetString(STR_COMPANY_NAME));
3272 
3273  SetDParam(0, t->index);
3274  SetDParamStr(1, company_name->string);
3275 
3276  AddNewsItem(
3277  TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_ROAD_REBUILDING_MINUTES : STR_NEWS_ROAD_REBUILDING_MONTHS,
3278  NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, company_name);
3279  AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3280  Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3281  }
3282  return CommandCost();
3283 }
3284 
3290 static bool CheckClearTile(TileIndex tile)
3291 {
3292  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3294  cur_company.Restore();
3295  return r.Succeeded();
3296 }
3297 
3302 
3303  StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
3304 };
3305 
3312 static bool SearchTileForStatue(TileIndex tile, void *user_data)
3313 {
3314  static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
3315 
3316  StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
3317  statue_data->tile_count++;
3318 
3319  /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
3320  if (IsSteepSlope(GetTileSlope(tile))) return false;
3321  /* Don't build statues under bridges. */
3322  if (IsBridgeAbove(tile)) return false;
3323 
3324  /* A clear-able open space is always preferred. */
3325  if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && CheckClearTile(tile)) {
3326  statue_data->best_position = tile;
3327  return true;
3328  }
3329 
3330  bool house = IsTileType(tile, MP_HOUSE);
3331 
3332  /* Searching inside the inner circle. */
3333  if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
3334  /* Save first house in inner circle. */
3335  if (house && statue_data->best_position == INVALID_TILE && CheckClearTile(tile)) {
3336  statue_data->best_position = tile;
3337  }
3338 
3339  /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
3340  return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
3341  }
3342 
3343  /* Searching outside the circle, just pick the first possible spot. */
3344  statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
3345  return house && CheckClearTile(tile);
3346 }
3347 
3356 {
3357  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
3358 
3359  TileIndex tile = t->xy;
3360  StatueBuildSearchData statue_data(INVALID_TILE, 0);
3361  if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
3362 
3363  if (flags & DC_EXEC) {
3364  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
3366  cur_company.Restore();
3368  SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
3369  MarkTileDirtyByTile(statue_data.best_position);
3370  }
3371  return CommandCost();
3372 }
3373 
3381 {
3382  /* Check if it's allowed to buy the rights */
3384 
3385  if (flags & DC_EXEC) {
3386  /* And grow for 3 months */
3387  t->fund_buildings_months = 3;
3388 
3389  /* Enable growth (also checking GameScript's opinion) */
3390  UpdateTownGrowth(t);
3391 
3392  /* Build a new house, but add a small delay to make sure
3393  * that spamming funding doesn't let town grow any faster
3394  * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
3395  * Also emulate original behaviour when town was only growing in
3396  * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
3397  * tick-perfect and gives player some time window where they can
3398  * spam funding with the exact same efficiency.
3399  */
3401 
3403  }
3404  return CommandCost();
3405 }
3406 
3414 {
3415  /* Check if it's allowed to buy the rights */
3417  if (t->exclusivity != INVALID_COMPANY) return CMD_ERROR;
3418 
3419  if (flags & DC_EXEC) {
3420  t->exclusive_counter = 12;
3422 
3423  ModifyStationRatingAround(t->xy, _current_company, 130, 17);
3424 
3426 
3427  /* Spawn news message */
3429  SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3430  SetDParam(1, TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MINUTES : STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION_MONTHS);
3431  SetDParam(2, t->index);
3432  SetDParamStr(3, cni->company_name);
3433  AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
3434  AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3435  Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
3436  }
3437  return CommandCost();
3438 }
3439 
3447 {
3448  if (flags & DC_EXEC) {
3449  if (Chance16(1, 14)) {
3450  /* set as unwanted for 6 months */
3451  t->unwanted[_current_company] = 6;
3452 
3453  /* set all close by station ratings to 0 */
3454  for (Station *st : Station::Iterate()) {
3455  if (st->town == t && st->owner == _current_company) {
3456  for (GoodsEntry &ge : st->goods) ge.rating = 0;
3457  }
3458  }
3459 
3460  /* only show error message to the executing player. All errors are handled command.c
3461  * but this is special, because it can only 'fail' on a DC_EXEC */
3462  if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3463 
3464  /* decrease by a lot!
3465  * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3466  * be independent of any cheat settings
3467  */
3468  if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3469  t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3471  }
3472  } else {
3473  ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3476  t->exclusive_counter = 0;
3477  }
3478  }
3479  }
3480  return CommandCost();
3481 }
3482 
3483 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3484 static TownActionProc * const _town_action_proc[] = {
3493 };
3494 
3502 {
3503  TownActions buttons = TACT_NONE;
3504 
3505  /* Spectators and unwanted have no options */
3506  if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3507 
3508  /* Actions worth more than this are not able to be performed */
3509  Money avail = GetAvailableMoney(cid);
3510 
3511  /* Check the action bits for validity and
3512  * if they are valid add them */
3513  for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3514  const TownActions cur = (TownActions)(1 << i);
3515 
3516  /* Is the company not able to bribe ? */
3517  if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3518 
3519  /* Is the company not able to buy exclusive rights ? */
3520  if (cur == TACT_BUY_RIGHTS && (!_settings_game.economy.exclusive_rights || t->exclusive_counter != 0)) continue;
3521 
3522  /* Is the company not able to fund buildings ? */
3523  if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3524 
3525  /* Is the company not able to fund local road reconstruction? */
3526  if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3527 
3528  /* Is the company not able to build a statue ? */
3529  if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3530 
3531  if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3532  buttons |= cur;
3533  }
3534  }
3535  }
3536 
3537  return buttons;
3538 }
3539 
3549 CommandCost CmdDoTownAction(DoCommandFlag flags, TownID town_id, uint8_t action)
3550 {
3551  Town *t = Town::GetIfValid(town_id);
3552  if (t == nullptr || action >= lengthof(_town_action_proc)) return CMD_ERROR;
3553 
3554  if (!HasBit(GetMaskOfTownActions(_current_company, t), action)) return CMD_ERROR;
3555 
3556  CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[action] >> 8);
3557 
3558  CommandCost ret = _town_action_proc[action](t, flags);
3559  if (ret.Failed()) return ret;
3560 
3561  if (flags & DC_EXEC) {
3563  }
3564 
3565  return cost;
3566 }
3567 
3568 template <typename Func>
3569 static void ForAllStationsNearTown(Town *t, Func func)
3570 {
3571  /* Ideally the search radius should be close to the actual town zone 0 radius.
3572  * The true radius is not stored or calculated anywhere, only the squared radius. */
3573  /* The efficiency of this search might be improved for large towns and many stations on the map,
3574  * by using an integer square root approximation giving a value not less than the true square root. */
3575  uint search_radius = t->cache.squared_town_zone_radius[HZB_TOWN_EDGE] / 2;
3576  ForAllStationsRadius(t->xy, search_radius, [&](const Station * st) {
3577  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
3578  func(st);
3579  }
3580  });
3581 }
3582 
3587 static void UpdateTownRating(Town *t)
3588 {
3589  /* Increase company ratings if they're low */
3590  for (const Company *c : Company::Iterate()) {
3591  if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3592  t->ratings[c->index] = std::min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
3593  }
3594  }
3595 
3596  ForAllStationsNearTown(t, [&](const Station *st) {
3597  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3598  if (Company::IsValidID(st->owner)) {
3599  int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3600  t->ratings[st->owner] = std::min<int>(new_rating, INT16_MAX); // do not let it overflow
3601  }
3602  } else {
3603  if (Company::IsValidID(st->owner)) {
3604  int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3605  t->ratings[st->owner] = std::max(new_rating, INT16_MIN);
3606  }
3607  }
3608  });
3609 
3610  /* clamp all ratings to valid values */
3611  for (uint i = 0; i < MAX_COMPANIES; i++) {
3612  t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3613  }
3614 
3616 }
3617 
3618 
3625 static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
3626 {
3627  if (t->growth_rate == TOWN_GROWTH_RATE_NONE) return;
3628  if (prev_growth_rate == TOWN_GROWTH_RATE_NONE) {
3629  t->grow_counter = std::min<uint16_t>(t->growth_rate, t->grow_counter);
3630  return;
3631  }
3632  t->grow_counter = RoundDivSU((uint32_t)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1);
3633 }
3634 
3641 {
3642  int n = 0;
3643  ForAllStationsNearTown(t, [&](const Station * st) {
3644  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3645  n++;
3646  }
3647  });
3648  return n;
3649 }
3650 
3657 static uint GetNormalGrowthRate(Town *t)
3658 {
3664  static const uint16_t _grow_count_values[2][6] = {
3665  { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3666  { 320, 420, 300, 220, 160, 100 } // Normal values
3667  };
3668 
3669  int n = CountActiveStations(t);
3670  uint16_t m = _grow_count_values[t->fund_buildings_months != 0 ? 0 : 1][std::min(n, 5)];
3671 
3672  uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3673 
3674  m >>= growth_multiplier;
3675  if (t->larger_town) m /= 2;
3676 
3677  return TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3678 }
3679 
3685 {
3686  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) return;
3687  uint old_rate = t->growth_rate;
3689  UpdateTownGrowCounter(t, old_rate);
3691 }
3692 
3697 static void UpdateTownGrowth(Town *t)
3698 {
3700 
3703 
3704  if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3705 
3706  if (t->fund_buildings_months == 0) {
3707  /* Check if all goals are reached for this town to grow (given we are not funding it) */
3708  for (int i = TAE_BEGIN; i < TAE_END; i++) {
3709  switch (t->goal[i]) {
3710  case TOWN_GROWTH_WINTER:
3711  if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3712  break;
3713  case TOWN_GROWTH_DESERT:
3714  if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3715  break;
3716  default:
3717  if (t->goal[i] > t->received[i].old_act) return;
3718  break;
3719  }
3720  }
3721  }
3722 
3723  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) {
3726  return;
3727  }
3728 
3729  if (t->fund_buildings_months == 0 && CountActiveStations(t) == 0 && !Chance16(1, 12)) return;
3730 
3733 }
3734 
3742 {
3743  /* The required rating is hardcoded to RATING_VERYPOOR (see below), not the authority attitude setting, so we can bail out like this. */
3744  if (_settings_game.difficulty.town_council_tolerance == TOWN_COUNCIL_PERMISSIVE) return CommandCost();
3745 
3747 
3749  if (t == nullptr) return CommandCost();
3750 
3751  if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3752 
3753  SetDParam(0, t->index);
3754  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3755 }
3756 
3766 {
3767  if (Town::GetNumItems() == 0) return nullptr;
3768 
3769  TownID tid = _town_kdtree.FindNearest(TileX(tile), TileY(tile));
3770  Town *town = Town::Get(tid);
3771  if (DistanceManhattan(tile, town->xy) < threshold) return town;
3772  return nullptr;
3773 }
3774 
3783 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3784 {
3785  switch (GetTileType(tile)) {
3786  case MP_ROAD:
3787  if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3788 
3789  if (!HasTownOwnedRoad(tile)) {
3790  TownID tid = GetTownIndex(tile);
3791 
3792  if (tid == INVALID_TOWN) {
3793  /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3794  if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3795  assert(Town::GetNumItems() == 0);
3796  return nullptr;
3797  }
3798 
3799  assert(Town::IsValidID(tid));
3800  Town *town = Town::Get(tid);
3801 
3802  if (DistanceManhattan(tile, town->xy) >= threshold) town = nullptr;
3803 
3804  return town;
3805  }
3806  [[fallthrough]];
3807 
3808  case MP_HOUSE:
3809  return Town::GetByTile(tile);
3810 
3811  default:
3812  return CalcClosestTownFromTile(tile, threshold);
3813  }
3814 }
3815 
3816 static bool _town_rating_test = false;
3817 static std::map<const Town *, int> _town_test_ratings;
3818 
3824 void SetTownRatingTestMode(bool mode)
3825 {
3826  static int ref_count = 0; // Number of times test-mode is switched on.
3827  if (mode) {
3828  if (ref_count == 0) {
3829  _town_test_ratings.clear();
3830  }
3831  ref_count++;
3832  } else {
3833  assert(ref_count > 0);
3834  ref_count--;
3835  }
3836  _town_rating_test = !(ref_count == 0);
3837 }
3838 
3844 static int GetRating(const Town *t)
3845 {
3846  if (_town_rating_test) {
3847  auto it = _town_test_ratings.find(t);
3848  if (it != _town_test_ratings.end()) {
3849  return it->second;
3850  }
3851  }
3852  return t->ratings[_current_company];
3853 }
3854 
3862 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
3863 {
3864  /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3865  if (t == nullptr || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3867  (_cheats.magic_bulldozer.value && add < 0)) {
3868  return;
3869  }
3870 
3871  int rating = GetRating(t);
3872  if (add < 0) {
3873  if (rating > max) {
3874  rating += add;
3875  if (rating < max) rating = max;
3876  }
3877  } else {
3878  if (rating < max) {
3879  rating += add;
3880  if (rating > max) rating = max;
3881  }
3882  }
3883  if (_town_rating_test) {
3884  _town_test_ratings[t] = rating;
3885  } else {
3887  t->ratings[_current_company] = rating;
3889  }
3890 }
3891 
3900 {
3901  /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3902  if (t == nullptr || !Company::IsValidID(_current_company) ||
3904  return CommandCost();
3905  }
3906 
3907  /* minimum rating needed to be allowed to remove stuff */
3908  static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3909  /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3914  };
3915 
3916  /* check if you're allowed to remove the road/bridge/tunnel
3917  * owned by a town no removal if rating is lower than ... depends now on
3918  * difficulty setting. Minimum town rating selected by difficulty level
3919  */
3920  int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3921 
3922  if (GetRating(t) < needed) {
3923  SetDParam(0, t->index);
3924  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3925  }
3926 
3927  return CommandCost();
3928 }
3929 
3930 static IntervalTimer<TimerGameEconomy> _economy_towns_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::TOWN}, [](auto)
3931 {
3932  for (Town *t : Town::Iterate()) {
3933  /* Check for active town actions and decrement their counters. */
3934  if (t->road_build_months != 0) t->road_build_months--;
3935  if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3936 
3937  if (t->exclusive_counter != 0) {
3938  if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3939  }
3940 
3941  /* Check for active failed bribe cooloff periods and decrement them. */
3942  for (const Company *c : Company::Iterate()) {
3943  if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3944  }
3945 
3946  /* Update cargo statistics. */
3947  for (auto &supplied : t->supplied) supplied.NewMonth();
3948  for (auto &received : t->received) received.NewMonth();
3949 
3950  UpdateTownGrowth(t);
3951  UpdateTownRating(t);
3952 
3954  }
3955 });
3956 
3957 static IntervalTimer<TimerGameEconomy> _economy_towns_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::TOWN}, [](auto)
3958 {
3959  /* Increment house ages */
3960  for (TileIndex t = 0; t < Map::Size(); t++) {
3961  if (!IsTileType(t, MP_HOUSE)) continue;
3962  IncrementHouseAge(t);
3963  }
3964 });
3965 
3966 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3967 {
3968  if (AutoslopeEnabled()) {
3969  HouseID house = GetHouseType(tile);
3970  GetHouseNorthPart(house); // modifies house to the ID of the north tile
3971  const HouseSpec *hs = HouseSpec::Get(house);
3972 
3973  /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3974  if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3975  (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3976  bool allow_terraform = true;
3977 
3978  /* Call the autosloping callback per tile, not for the whole building at once. */
3979  house = GetHouseType(tile);
3980  hs = HouseSpec::Get(house);
3982  /* If the callback fails, allow autoslope. */
3983  uint16_t res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3984  if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3985  }
3986 
3987  if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3988  }
3989  }
3990 
3991  return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
3992 }
3993 
3995 extern const TileTypeProcs _tile_type_town_procs = {
3996  DrawTile_Town, // draw_tile_proc
3997  GetSlopePixelZ_Town, // get_slope_z_proc
3998  ClearTile_Town, // clear_tile_proc
3999  AddAcceptedCargo_Town, // add_accepted_cargo_proc
4000  GetTileDesc_Town, // get_tile_desc_proc
4001  GetTileTrackStatus_Town, // get_tile_track_status_proc
4002  nullptr, // click_tile_proc
4003  AnimateTile_Town, // animate_tile_proc
4004  TileLoop_Town, // tile_loop_proc
4005  ChangeTileOwner_Town, // change_tile_owner_proc
4006  AddProducedCargo_Town, // add_produced_cargo_proc
4007  nullptr, // vehicle_enter_tile_proc
4008  GetFoundation_Town, // get_foundation_proc
4009  TerraformTile_Town, // terraform_tile_proc
4010 };
4011 
4012 
4013 HouseSpec _house_specs[NUM_HOUSES];
4014 
4015 void ResetHouses()
4016 {
4017  ResetHouseClassIDs();
4018 
4019  auto insert = std::copy(std::begin(_original_house_specs), std::end(_original_house_specs), std::begin(_house_specs));
4020  std::fill(insert, std::end(_house_specs), HouseSpec{});
4021 
4022  /* Reset any overrides that have been set. */
4023  _house_mngr.ResetOverride();
4024 }
GrowTownInTile
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
Definition: town_cmd.cpp:1498
game.hpp
RoadTypeInfo::flags
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:127
TileY
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:437
TileInfo::z
int z
Height.
Definition: tile_cmd.h:48
MP_CLEAR
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:48
MP_HOUSE
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:51
HouseSpec::removal_cost
byte removal_cost
cost multiplier for removing it
Definition: house.h:103
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition: newgrf_debug_gui.cpp:739
IsTileFlat
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:100
DIAGDIR_SE
@ DIAGDIR_SE
Southeast.
Definition: direction_type.h:76
TACT_BRIBE
@ TACT_BRIBE
Try to bribe the council.
Definition: town.h:218
SLOPE_SE
@ SLOPE_SE
south and east corner are raised
Definition: slope_type.h:57
TileDesc::grf
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
Town::have_ratings
CompanyMask have_ratings
which companies have a rating
Definition: town.h:69
ClearTownHouse
void ClearTownHouse(Town *t, TileIndex tile)
Clear a town house.
Definition: town_cmd.cpp:2871
TROPICZONE_DESERT
@ TROPICZONE_DESERT
Tile is desert.
Definition: tile_type.h:78
RoadTypeInfo
Definition: road.h:78
TACT_BUILD_STATUE
@ TACT_BUILD_STATUE
Build a statue.
Definition: town.h:215
TILE_ADD
#define TILE_ADD(x, y)
Adds two tiles together.
Definition: map_func.h:466
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3204
StatueBuildSearchData
Structure for storing data while searching the best place to build a statue.
Definition: town_cmd.cpp:3299
TileLoop_Town
static void TileLoop_Town(TileIndex tile)
Tile callback function.
Definition: town_cmd.cpp:598
ResetHouseAge
void ResetHouseAge(Tile t)
Sets the age of the house to zero.
Definition: town_map.h:227
SLOPE_STEEP_E
@ SLOPE_STEEP_E
a steep slope falling to west (from east)
Definition: slope_type.h:68
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:29
_town_test_ratings
static std::map< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
Definition: town_cmd.cpp:3817
Cheats::magic_bulldozer
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:27
GoodsEntry::rating
uint8_t rating
Station rating for this cargo.
Definition: station_base.h:226
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
newgrf_house.h
TPE_MAIL
@ TPE_MAIL
Cargo behaves mail-like for production.
Definition: cargotype.h:37
RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
@ RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:61
StationFinder
Structure contains cached list of stations nearby.
Definition: station_type.h:100
CalcClosestTownFromTile
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3765
Pool::PoolItem<&_town_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
GetDisallowedRoadDirections
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition: road_map.h:301
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition: timer_game_tick.h:60
station_kdtree.h
TO_HOUSES
@ TO_HOUSES
town buildings
Definition: transparency.h:25
OnTick_Town
void OnTick_Town()
Iterate through all towns and call their tick handler.
Definition: town_cmd.cpp:887
EconomySettings::larger_towns
uint8_t larger_towns
the number of cities to build. These start off larger and grow twice as fast
Definition: settings_type.h:550
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3086
GetTileMaxZ
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:141
GetRating
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
Definition: town_cmd.cpp:3844
TAE_FOOD
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:28
TownGenerateCargoOriginal
static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the original algorithm.
Definition: town_cmd.cpp:555
CBM_HOUSE_CARGO_ACCEPTANCE
@ CBM_HOUSE_CARGO_ACCEPTANCE
decides amount of cargo acceptance
Definition: newgrf_callbacks.h:335
DoClearTownHouseHelper
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
Definition: town_cmd.cpp:2829
TileHash2Bit
uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition: tile_map.h:334
command_func.h
TownGenerateCargoBinominal
static void TownGenerateCargoBinominal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the binominal algorithm.
Definition: town_cmd.cpp:575
IsInsideMM
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:268
SLOPE_STEEP_S
@ SLOPE_STEEP_S
a steep slope falling to north (from south)
Definition: slope_type.h:67
Town::InitializeLayout
void InitializeLayout(TownLayout layout)
Assign the town layout.
Definition: town_cmd.cpp:177
Town::road_build_months
byte road_build_months
fund road reconstruction in action?
Definition: town.h:95
IsRoadOwner
bool IsRoadOwner(Tile t, RoadTramType rtt, Owner o)
Check if a specific road type is owned by an owner.
Definition: road_map.h:268
EconomySettings::town_layout
TownLayout town_layout
select town layout,
Definition: settings_type.h:552
FindNearestEmptyLand
static bool FindNearestEmptyLand(TileIndex tile, void *)
CircularTileSearch callback to find the nearest land tile.
Definition: town_cmd.cpp:2276
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
Definition: error_gui.cpp:367
Pool::PoolItem<&_town_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:350
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
RoadTypeInfo::introduction_date
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: road.h:166
FlatteningFoundation
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:369
TownActionBuildStatue
static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
Perform a 9x9 tiles circular search from the center of the town in order to find a free tile to place...
Definition: town_cmd.cpp:3355
Kdtree
K-dimensional tree, specialised for 2-dimensional space.
Definition: kdtree.hpp:35
TileInfo
Tile information, used while rendering the tile.
Definition: tile_cmd.h:43
GameCreationSettings::landscape
byte landscape
the landscape we're currently in
Definition: settings_type.h:355
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
Town::statues
CompanyMask statues
which companies have a statue?
Definition: town.h:66
terraform_cmd.h
company_base.h
HouseSpec::max_year
TimerGameCalendar::Year max_year
last year it can be built
Definition: house.h:101
BuildObject
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=nullptr, uint8_t view=0)
Actually build the object.
Definition: object_cmd.cpp:88
tunnelbridge_map.h
EXPENSES_OTHER
@ EXPENSES_OTHER
Other expenses.
Definition: economy_type.h:185
CommandFlagsToDCFlags
static constexpr DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
Definition: command_func.h:58
RemoveNearbyStations
static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
Remove stations from nearby station list if a town is no longer in the catchment area of each.
Definition: town_cmd.cpp:469
timer_game_calendar.h
CommandCost::MultiplyCost
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:74
HouseSpec::accepts_cargo
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:108
TileDesc::owner
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
SLOPE_NW
@ SLOPE_NW
north and west corner are raised
Definition: slope_type.h:55
Station
Station data structure.
Definition: station_base.h:442
GetWorldPopulation
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
Definition: town_cmd.cpp:455
GetClosestWaterDistance
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition: map.cpp:342
CargoPacket::InvalidateAllFrom
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Definition: cargopacket.cpp:137
TF_FORBIDDEN
@ TF_FORBIDDEN
Forbidden.
Definition: town_type.h:96
UpdateTownRating
static void UpdateTownRating(Town *t)
Monthly callback to update town and station ratings.
Definition: town_cmd.cpp:3587
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
ROAD_S
@ ROAD_S
Road at the two southern edges.
Definition: road_type.h:63
DifficultySettings::town_council_tolerance
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:116
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1141
_town_rating_test
static bool _town_rating_test
If true, town rating is in test-mode.
Definition: town_cmd.cpp:3816
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition: timer.h:76
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
IncHouseConstructionTick
void IncHouseConstructionTick(Tile t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits,...
Definition: town_map.h:209
TL_RANDOM
@ TL_RANDOM
Random town layout.
Definition: town_type.h:87
TownSize
TownSize
Supported initial town sizes.
Definition: town_type.h:19
DIAGDIR_END
@ DIAGDIR_END
Used for iterations.
Definition: direction_type.h:79
AutoslopeEnabled
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:44
IsTransparencySet
bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:48
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
TACT_FUND_BUILDINGS
@ TACT_FUND_BUILDINGS
Fund new buildings.
Definition: town.h:216
DiagDirToAxis
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition: direction_func.h:214
Object::GetByTile
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:55
GrowTownAtRoad
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Try to grow a town at a given road tile.
Definition: town_cmd.cpp:1748
IsRoadAllowedHere
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
Definition: town_cmd.cpp:1026
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:114
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:23
HouseSpec::enabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:112
CheckTownBuild2x2House
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
Definition: town_cmd.cpp:2652
SLOPE_ELEVATED
@ SLOPE_ELEVATED
bit mask containing all 'simple' slopes
Definition: slope_type.h:61
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:617
GetTileZ
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.cpp:121
INVALID_TILE
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:95
Town::growth_rate
uint16_t growth_rate
town growth rate
Definition: town.h:92
AdvanceSingleHouseConstruction
static void AdvanceSingleHouseConstruction(TileIndex tile)
Helper function for house construction stage progression.
Definition: town_cmd.cpp:491
DIAGDIRDIFF_90LEFT
@ DIAGDIRDIFF_90LEFT
90 degrees left
Definition: direction_type.h:100
Waypoint
Representation of a waypoint.
Definition: waypoint_base.h:16
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition: tile_type.h:49
_tile_type_town_procs
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
Definition: landscape.cpp:50
TileHash
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:316
IsSteepSlope
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:36
OBJECT_STATUE
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:18
GameCreationSettings::town_name
byte town_name
the town name generator used for town names
Definition: settings_type.h:354
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
TownActionBuyRights
static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
Perform the "buy exclusive transport rights" town action.
Definition: town_cmd.cpp:3413
CBID_HOUSE_CUSTOM_NAME
@ CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
Definition: newgrf_callbacks.h:224
VerifyTownName
bool VerifyTownName(uint32_t r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition: townname.cpp:103
_random
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:37
HasTownOwnedRoad
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
Definition: road_map.h:280
HouseSpec::callback_mask
uint16_t callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:116
HouseSpec::building_name
StringID building_name
building name
Definition: house.h:104
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:187
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:54
Town::xy
TileIndex xy
town center tile
Definition: town.h:51
TCGM_ORIGINAL
@ TCGM_ORIGINAL
Original algorithm (quadratic cargo by population)
Definition: town_type.h:105
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:68
DC_NO_WATER
@ DC_NO_WATER
don't allow building on water
Definition: command_type.h:374
GetRoadStopDir
DiagDirection GetRoadStopDir(Tile t)
Gets the direction the road stop entrance points towards.
Definition: station_map.h:258
TSZ_RANDOM
@ TSZ_RANDOM
Random size, bigger than small, smaller than large.
Definition: town_type.h:23
MP_INDUSTRY
@ MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:56
TimerGameEconomy::UsingWallclockUnits
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
Definition: timer_game_economy.cpp:97
town.h
newgrf_debug.h
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:716
TileInfo::y
int y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:45
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
SLOPE_S
@ SLOPE_S
the south corner of the tile is raised
Definition: slope_type.h:51
DIAGDIR_NW
@ DIAGDIR_NW
Northwest.
Definition: direction_type.h:78
TownLayout
TownLayout
Town Layouts.
Definition: town_type.h:80
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:345
IsWaterTile
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition: water_map.h:193
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
CreateRandomTown
static Town * CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
Create a random town somewhere in the world.
Definition: town_cmd.cpp:2316
Industry
Defines the internal data of a functional industry.
Definition: industry.h:68
Chance16
bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
Definition: random_func.hpp:131
Station::CatchmentCoversTown
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
Definition: station.cpp:442
CBID_HOUSE_DRAW_FOUNDATIONS
@ CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house tile.
Definition: newgrf_callbacks.h:227
Map::ScaleBySize
static uint ScaleBySize(uint n)
Scales the given value by the map size, where the given value is for a 256 by 256 map.
Definition: map_func.h:328
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
Town::fund_buildings_months
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:94
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:371
Kdtree::Build
void Build(It begin, It end)
Clear and rebuild the tree from a new sequence of elements,.
Definition: kdtree.hpp:362
GetTownRoadBits
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile, ignoring depot and bay road stops.
Definition: town_cmd.cpp:901
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:74
DIR_N
@ DIR_N
North.
Definition: direction_type.h:26
MP_ROAD
@ MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:50
TOWN_GROWTH_RATE_NONE
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:33
TileDesc
Tile description for the 'land area information' tool.
Definition: tile_cmd.h:52
LiftHasDestination
bool LiftHasDestination(Tile t)
Check if the lift of this animated house has a destination.
Definition: town_map.h:83
Town::show_zone
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:100
TOWN_HAS_STADIUM
@ TOWN_HAS_STADIUM
There can be only one stadium by town.
Definition: town.h:194
CBM_HOUSE_PRODUCE_CARGO
@ CBM_HOUSE_PRODUCE_CARGO
custom cargo production
Definition: newgrf_callbacks.h:339
SLOPE_E
@ SLOPE_E
the east corner of the tile is raised
Definition: slope_type.h:52
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:369
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
genworld.h
Town::UpdateVirtCoord
void UpdateVirtCoord()
Resize the sign (label) of the town after it changes population.
Definition: town_cmd.cpp:404
Foundation
Foundation
Enumeration for Foundations.
Definition: slope_type.h:93
UpdateTownRadius
void UpdateTownRadius(Town *t)
Update the cached town zone radii of a town, based on the number of houses.
Definition: town_cmd.cpp:1904
GenerateTowns
bool GenerateTowns(TownLayout layout)
Generate a number of towns with a given layout.
Definition: town_cmd.cpp:2368
ROAD_W
@ ROAD_W
Road at the two western edges.
Definition: road_type.h:64
Kdtree::Count
size_t Count() const
Get number of elements stored in tree.
Definition: kdtree.hpp:430
IncreaseGeneratingWorldProgress
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Definition: genworld_gui.cpp:1550
GetHouseConstructionTick
byte GetHouseConstructionTick(Tile t)
Gets the construction stage of a house.
Definition: town_map.h:196
SpotData
Used as the user_data for FindFurthestFromWater.
Definition: town_cmd.cpp:2234
Town::GetRandom
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:191
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:162
RATING_GROWTH_UP_STEP
@ RATING_GROWTH_UP_STEP
when a town grows, all companies have rating increased a bit ...
Definition: town_type.h:52
object_base.h
EconomySettings::bribe
bool bribe
enable bribing the local authority
Definition: settings_type.h:539
RandomRange
static uint32_t RandomRange(uint32_t limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:81
Kdtree::Remove
void Remove(const T &element)
Remove a single element from the tree, if it exists.
Definition: kdtree.hpp:417
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:618
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition: base_station_base.h:310
ai.hpp
NR_NONE
@ NR_NONE
Empty reference.
Definition: news_type.h:53
EconomySettings::town_growth_rate
uint8_t town_growth_rate
town growth rate
Definition: settings_type.h:549
RATING_INITIAL
@ RATING_INITIAL
initial rating
Definition: town_type.h:44
ComplementSlope
Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:76
TF_CUSTOM_LAYOUT
@ TF_CUSTOM_LAYOUT
Allowed, with custom town layout.
Definition: town_type.h:98
TileInfo::tileh
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:46
GetTileType
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
ROAD_X
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:58
TimerGameConst< struct Calendar >::MAX_DATE
static constexpr TimerGame< struct Calendar >::Date MAX_DATE
The date of the last day of the max year.
Definition: timer_game_common.h:187
TestTownOwnsBridge
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
Check if a town 'owns' a bridge.
Definition: town_cmd.cpp:92
RoundDivSU
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
Definition: math_func.hpp:342
NR_TOWN
@ NR_TOWN
Reference town. Scroll to town when clicking on the news.
Definition: news_type.h:58
GetRoadDepotDirection
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
Definition: road_map.h:565
Pool::MAX_SIZE
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:84
ScaleByCargoScale
uint ScaleByCargoScale(uint num, bool town)
Scale a number by the cargo scale setting.
Definition: economy_func.h:77
IsInvisibilitySet
bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
Definition: transparency.h:59
townname_func.h
HouseSpec::extra_flags
HouseExtraFlags extra_flags
some more flags
Definition: house.h:119
GetHouseAge
TimerGameCalendar::Year GetHouseAge(Tile t)
Get the age of the house.
Definition: town_map.h:250
HouseSpec::probability
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:118
GrowTown
static bool GrowTown(Town *t)
Grow the town.
Definition: town_cmd.cpp:1844
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:378
GRFFileProps::override
uint16_t override
id of the entity been replaced by
Definition: newgrf_commons.h:332
ROAD_Y
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:59
Pool::PoolItem<&_town_pool >::GetPoolSize
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:360
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
DistanceManhattan
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:159
DIAGDIR_SW
@ DIAGDIR_SW
Southwest.
Definition: direction_type.h:77
EconomySettings::fund_buildings
bool fund_buildings
allow funding new buildings
Definition: settings_type.h:544
depot_base.h
landscape_cmd.h
CompanyNewsInformation::company_name
std::string company_name
The name of the company.
Definition: news_type.h:162
ROAD_ALL
@ ROAD_ALL
Full 4-way crossing.
Definition: road_type.h:66
Town::supplied
TransportedCargoStat< uint32_t > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:75
CmdTownCargoGoal
CommandCost CmdTownCargoGoal(DoCommandFlag flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
Change the cargo goal of a town.
Definition: town_cmd.cpp:2964
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
TOWN_RATING_CHECK_TYPE_COUNT
@ TOWN_RATING_CHECK_TYPE_COUNT
Number of town checking action types.
Definition: town.h:174
RandomDiagDir
static DiagDirection RandomDiagDir()
Return a random direction.
Definition: town_cmd.cpp:253
ROAD_NE
@ ROAD_NE
North-east part.
Definition: road_type.h:57
TL_BETTER_ROADS
@ TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:83
ToTileIndexDiff
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition: map_func.h:452
IsBayRoadStopTile
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
Definition: station_map.h:223
GetTownRoadType
RoadType GetTownRoadType()
Get the road type that towns should build at this current moment.
Definition: town_cmd.cpp:912
GetAvailableMoneyForCommand
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
Definition: company_cmd.cpp:228
EXPENSES_CONSTRUCTION
@ EXPENSES_CONSTRUCTION
Construction costs.
Definition: economy_type.h:173
TownActionAdvertiseSmall
static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
Perform the "small advertising campaign" town action.
Definition: town_cmd.cpp:3220
GetTownRadiusGroup
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2425
CommandCost
Common return value for all commands.
Definition: command_type.h:23
GetSnowLine
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:611
SetLiftPosition
void SetLiftPosition(Tile t, byte pos)
Set the position of the lift on this animated house.
Definition: town_map.h:136
town_cmd.h
CircularTileSearch
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Definition: map.cpp:260
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:147
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
Town::grow_counter
uint16_t grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:91
ChangeDiagDir
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Definition: direction_func.h:149
WC_TOWN_AUTHORITY
@ WC_TOWN_AUTHORITY
Town authority; Window numbers:
Definition: window_type.h:194
SpotData::tile
TileIndex tile
holds the tile that was found
Definition: town_cmd.cpp:2235
SLOPE_NE
@ SLOPE_NE
north and east corner are raised
Definition: slope_type.h:58
TownAcceptanceEffect
TownAcceptanceEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:21
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:35
Industry::GetByTile
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:207
GSF_FAKE_TOWNS
@ GSF_FAKE_TOWNS
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:90
GameCreationSettings::custom_town_number
uint16_t custom_town_number
manually entered number of towns
Definition: settings_type.h:357
GetSlopeMaxZ
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
Definition: slope_func.h:160
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
NT_GENERAL
@ NT_GENERAL
General news (from towns)
Definition: news_type.h:39
_original_house_specs
static const HouseSpec _original_house_specs[]
House specifications from original data.
Definition: town_land.h:1820
NEW_HOUSE_OFFSET
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
TSZ_END
@ TSZ_END
Number of available town sizes.
Definition: town_type.h:25
TownCanBePlacedHere
static CommandCost TownCanBePlacedHere(TileIndex tile)
Check if it's possible to place a town on a given tile.
Definition: town_cmd.cpp:2051
TOWN_GROWTH_DESERT
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:32
autoslope.h
SpotData::max_dist
uint max_dist
holds the distance that tile is from the water
Definition: town_cmd.cpp:2236
TownRatingCheckType
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:171
CountActiveStations
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
Definition: town_cmd.cpp:3640
DistanceFromEdge
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:219
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:110
Kdtree::Insert
void Insert(const T &element)
Insert a single element in the tree.
Definition: kdtree.hpp:398
MP_OBJECT
@ MP_OBJECT
Contains objects such as transmitters and owned land.
Definition: tile_type.h:58
TransportType
TransportType
Available types of transport.
Definition: transport_type.h:19
CBID_HOUSE_ALLOW_CONSTRUCTION
@ CBID_HOUSE_ALLOW_CONSTRUCTION
Determine whether the house can be built on the specified tile.
Definition: newgrf_callbacks.h:54
_cheats
Cheats _cheats
All the cheats.
Definition: cheat.cpp:16
GUISettings::population_in_label
bool population_in_label
show the population of a town in its label?
Definition: settings_type.h:167
CBM_HOUSE_ACCEPT_CARGO
@ CBM_HOUSE_ACCEPT_CARGO
decides accepted types
Definition: newgrf_callbacks.h:338
CargoSpec::town_production_cargoes
static std::array< std::vector< const CargoSpec * >, NUM_TPE > town_production_cargoes
List of cargo specs for each Town Product Effect.
Definition: cargotype.h:190
MP_WATER
@ MP_WATER
Water tile.
Definition: tile_type.h:54
UpdateAirportsNoise
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
Definition: station_cmd.cpp:2364
ReverseDiagDir
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition: direction_func.h:118
Town::stations_near
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:87
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:171
DoCreateTown
static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Actually create a town.
Definition: town_cmd.cpp:1975
AlignTileToGrid
static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
Definition: town_cmd.cpp:2204
SetLiftDestination
void SetLiftDestination(Tile t, byte dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit.
Definition: town_map.h:94
Object
An object, such as transmitter, on the map.
Definition: object_base.h:23
GrowTownWithTunnel
static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
Grows the town with a tunnel.
Definition: town_cmd.cpp:1369
CmdTownRating
CommandCost CmdTownRating(DoCommandFlag flags, TownID town_id, CompanyID company_id, int16_t rating)
Change the rating of a company in a town.
Definition: town_cmd.cpp:3053
TACT_ROAD_REBUILD
@ TACT_ROAD_REBUILD
Rebuild the roads.
Definition: town.h:214
TownLayoutAllowsHouseHere
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
Checks if the current town layout allows building here.
Definition: town_cmd.cpp:2559
TileDiffXY
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:401
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:55
NewsStringData
Container for a single string to be passed as NewsAllocatedData.
Definition: news_type.h:150
DeleteSubsidyWith
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:152
CALLBACK_HOUSEPRODCARGO_END
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
Definition: newgrf_callbacks.h:421
timer_game_tick.h
IsBridgeTile
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition: bridge_map.h:35
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:146
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:627
WL_INFO
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:24
DIAGDIRDIFF_90RIGHT
@ DIAGDIRDIFF_90RIGHT
90 degrees right
Definition: direction_type.h:98
Object::type
ObjectType type
Type of the object.
Definition: object_base.h:24
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
AI::BroadcastNewEvent
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:269
industry.h
safeguards.h
Town::unwanted
uint8_t unwanted[MAX_COMPANIES]
how many months companies aren't wanted by towns (bribe)
Definition: town.h:70
timer.h
HighestSnowLine
byte HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:624
RedundantBridgeExistsNearby
static bool RedundantBridgeExistsNearby(TileIndex tile, void *user_data)
CircularTileSearch proc which checks for a nearby parallel bridge to avoid building redundant bridges...
Definition: town_cmd.cpp:1263
GetTownRoadTypeFirstIntroductionDate
static TimerGameCalendar::Date GetTownRoadTypeFirstIntroductionDate()
Get the calendar date of the earliest town-buildable road type.
Definition: town_cmd.cpp:947
ChangePopulation
static void ChangePopulation(Town *t, int mod)
Change the town's population as recorded in the town cache, town label, and town directory.
Definition: town_cmd.cpp:442
RATING_ROAD_NEEDED_HOSTILE
@ RATING_ROAD_NEEDED_HOSTILE
"Hostile"
Definition: town_type.h:69
lengthof
#define lengthof(array)
Return the length of an fixed size array.
Definition: stdafx.h:303
IsNormalRoadTile
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition: road_map.h:74
SearchTileForStatue
static bool SearchTileForStatue(TileIndex tile, void *user_data)
Search callback function for TownActionBuildStatue.
Definition: town_cmd.cpp:3312
HasTileRoadType
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition: road_map.h:211
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
GetTileSlope
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:59
DIR_S
@ DIR_S
South.
Definition: direction_type.h:30
StatueBuildSearchData::tile_count
int tile_count
Number of tiles tried.
Definition: town_cmd.cpp:3301
IsCloseToTown
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition: town_cmd.cpp:396
TownActionRoadRebuild
static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
Perform the "local road reconstruction" town action.
Definition: town_cmd.cpp:3262
GetFoundation_Town
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Get the foundation for a house.
Definition: town_cmd.cpp:321
HaltLift
void HaltLift(Tile t)
Stop the lift of this animated house from moving.
Definition: town_map.h:116
RandomTile
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:657
RoadTypesAllowHouseHere
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding road allows to build a house here.
Definition: town_cmd.cpp:1435
TownActionFundBuildings
static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
Perform the "fund new buildings" town action.
Definition: town_cmd.cpp:3380
FindNearestGoodCoastalTownSpot
static TileIndex FindNearestGoodCoastalTownSpot(TileIndex tile, TownLayout layout)
Given a spot on the map (presumed to be a water tile), find a good coastal spot to build a city.
Definition: town_cmd.cpp:2293
DC_NO_TEST_TOWN_RATING
@ DC_NO_TEST_TOWN_RATING
town rating does not disallow you from building
Definition: command_type.h:376
HouseSpec::minimum_life
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:123
CleanUpRoadBits
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
Definition: road.cpp:47
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:27
EconomySettings::exclusive_rights
bool exclusive_rights
allow buying exclusive rights
Definition: settings_type.h:543
TownActionAdvertiseLarge
static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
Perform the "large advertising campaign" town action.
Definition: town_cmd.cpp:3248
UpdateTownMaxPass
void UpdateTownMaxPass(Town *t)
Update the maximum amount of montly passengers and mail for a town, based on its population.
Definition: town_cmd.cpp:1951
MP_TUNNELBRIDGE
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:57
TownLayoutAllows2x2HouseHere
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
Checks if the current town layout allows a 2x2 building here.
Definition: town_cmd.cpp:2590
newgrf_text.h
road_internal.h
road.h
TileIndexDiff
int32_t TileIndexDiff
An offset value between two tiles.
Definition: map_func.h:376
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Point
Coordinates of a point in 2D.
Definition: geometry_type.hpp:21
GetHouseType
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
Definition: town_map.h:60
FOUNDATION_NONE
@ FOUNDATION_NONE
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:94
EconomySettings::found_town
TownFounding found_town
town founding.
Definition: settings_type.h:555
error.h
DiagDirToRoadBits
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition: road_func.h:96
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition: direction_type.h:73
RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
@ RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
Definition: town_type.h:59
SetTownRatingTestMode
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
Definition: town_cmd.cpp:3824
GetFoundationSlope
Slope GetFoundationSlope(TileIndex tile, int *z)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
Definition: landscape.cpp:379
TL_3X3_GRID
@ TL_3X3_GRID
Geometric 3x3 grid algorithm.
Definition: town_type.h:85
GetGRFStringID
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:587
tunnelbridge_cmd.h
GetTownRoadGridElement
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
Definition: town_cmd.cpp:1103
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
CBID_HOUSE_CARGO_ACCEPTANCE
@ CBID_HOUSE_CARGO_ACCEPTANCE
Called to decide how much cargo a town building can accept.
Definition: newgrf_callbacks.h:78
stdafx.h
UpdateTownGrowth
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
Definition: town_cmd.cpp:3697
TileAddByDir
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition: map_func.h:592
landscape.h
TileTypeProcs
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:158
StationFinder::GetStations
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
Definition: station_cmd.cpp:4150
DRD_NONE
@ DRD_NONE
None of the directions are disallowed.
Definition: road_type.h:74
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:17
CountBits
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
Definition: bitmath_func.hpp:243
Cheat::value
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:18
UpdateNearestTownForRoadTiles
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1903
HouseSpec::mail_generation
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:106
viewport_func.h
NF_NORMAL
@ NF_NORMAL
Normal news item. (Newspaper with text only)
Definition: news_type.h:81
RATING_ROAD_NEEDED_NEUTRAL
@ RATING_ROAD_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:68
HouseSpec::population
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:102
SourceType::Town
@ Town
Source/destination is a town.
ClearTile_Town
static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
Callback function to clear a house tile.
Definition: town_cmd.cpp:710
EconomySettings::town_cargogen_mode
TownCargoGenMode town_cargogen_mode
algorithm for generating cargo from houses,
Definition: settings_type.h:553
WC_TOWN_DIRECTORY
@ WC_TOWN_DIRECTORY
Town directory; Window numbers:
Definition: window_type.h:254
HouseSpec::cargo_acceptance
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:107
animated_tile_func.h
UpdateAllTownVirtCoords
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:422
IsPlainRailTile
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
TownCache::population
uint32_t population
Current population of people.
Definition: town.h:42
AddSortableSpriteToDraw
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition: viewport.cpp:673
Town::time_until_rebuild
uint16_t time_until_rebuild
time until we rebuild a house
Definition: town.h:89
SLOPE_W
@ SLOPE_W
the west corner of the tile is raised
Definition: slope_type.h:50
IsValidTile
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition: tile_map.h:161
RATING_ROAD_NEEDED_PERMISSIVE
@ RATING_ROAD_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
Definition: town_type.h:70
ConvertBooleanCallback
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:529
TileOffsByDiagDir
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:563
object_map.h
MP_TREES
@ MP_TREES
Tile got trees.
Definition: tile_type.h:52
TransportedCargoStat::new_max
Tstorage new_max
Maximum amount this month.
Definition: town_type.h:116
GetRoadTypeInfo
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition: road.h:227
TileIndexDiffC
A pair-construct of a TileIndexDiff.
Definition: map_type.h:31
Ticks::TOWN_GROWTH_TICKS
static constexpr TimerGameTick::Ticks TOWN_GROWTH_TICKS
Cycle duration for towns trying to grow (this originates from the size of the town array in TTD).
Definition: timer_game_tick.h:83
AdvanceHouseConstruction
static void AdvanceHouseConstruction(TileIndex tile)
Increase the construction stage of a house.
Definition: town_cmd.cpp:514
DrawFoundation
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:427
NT_INDUSTRY_OPEN
@ NT_INDUSTRY_OPEN
Opening of industries.
Definition: news_type.h:29
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:62
EconomySettings::dist_local_authority
byte dist_local_authority
distance for town local authority, default 20
Definition: settings_type.h:542
DistanceSquare
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
Definition: map.cpp:176
TransportedCargoStat::old_max
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:115
ForAllStationsRadius
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
Definition: station_kdtree.h:29
Industry::town
Town * town
Nearest town.
Definition: industry.h:97
TOWN_GROWTH_WINTER
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:31
string_func.h
GetAnyRoadBits
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition: road_map.cpp:33
Town::PostDestructor
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool.
Definition: town_cmd.cpp:162
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:420
EconomySettings::allow_town_level_crossings
bool allow_town_level_crossings
towns are allowed to build level crossings
Definition: settings_type.h:558
Town::text
std::string text
General text with additional information.
Definition: town.h:79
RemapCoords2
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition: landscape.h:98
TCGM_BITCOUNT
@ TCGM_BITCOUNT
Bit-counted algorithm (normal distribution from individual house population)
Definition: town_type.h:106
IsValidDiagDirection
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition: direction_func.h:21
GoodsEntry
Stores station stats for a single cargo.
Definition: station_base.h:166
CmdTownSetText
CommandCost CmdTownSetText(DoCommandFlag flags, TownID town_id, const std::string &text)
Set a custom text in the Town window.
Definition: town_cmd.cpp:2993
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:51
TransportedCargoStat::new_act
Tstorage new_act
Actually transported this month.
Definition: town_type.h:118
TownActionBribe
static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
Perform the "bribe" town action.
Definition: town_cmd.cpp:3446
MakeHouseTile
void MakeHouseTile(Tile t, TownID tid, byte counter, byte stage, HouseID type, byte random_bits)
Make the tile a house.
Definition: town_map.h:353
station_base.h
Pool::PoolItem<&_town_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
GRFFilePropsBase::spritegroup
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
Definition: newgrf_commons.h:320
CompanyNewsInformation
Data that needs to be stored for company news messages.
Definition: news_type.h:161
strings_func.h
IsNeighborRoadTile
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
Definition: town_cmd.cpp:992
IncrementHouseAge
void IncrementHouseAge(Tile t)
Increments the age of the house.
Definition: town_map.h:238
TownCache::building_counts
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
Definition: town.h:46
Pool
Base class for all pools.
Definition: pool_type.hpp:80
RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
@ RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
Definition: town_type.h:62
GetHouseBuildingStage
byte GetHouseBuildingStage(Tile t)
House Construction Scheme.
Definition: town_map.h:184
TownAllowedToBuildRoads
static bool TownAllowedToBuildRoads()
Check if the town is allowed to build roads.
Definition: town_cmd.cpp:1476
TACT_COUNT
@ TACT_COUNT
Number of available town actions.
Definition: town.h:220
CanFollowRoad
static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
Definition: town_cmd.cpp:1706
MP_VOID
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:55
subsidy_func.h
Pool::PoolItem<&_town_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:369
DeleteAnimatedTile
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
Definition: animated_tile.cpp:25
RoadTypeInfo::label
RoadTypeLabel label
Unique 32 bit road type identifier.
Definition: road.h:147
Backup::Restore
void Restore()
Restore the variable.
Definition: backup_type.hpp:112
TrackedViewportSign::UpdatePosition
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport_type.h:56
CmdExpandTown
CommandCost CmdExpandTown(DoCommandFlag flags, TownID town_id, uint32_t grow_amount)
Expand a town (scenario editor only).
Definition: town_cmd.cpp:3078
SLOPE_N
@ SLOPE_N
the north corner of the tile is raised
Definition: slope_type.h:53
CheckTownRoadTypes
bool CheckTownRoadTypes()
Check if towns are able to build road.
Definition: town_cmd.cpp:968
Map::Size
static debug_inline uint Size()
Get the size of the map.
Definition: map_func.h:288
TileDesc::dparam
uint64_t dparam
Parameter of the str string.
Definition: tile_cmd.h:54
IncreaseBuildingCount
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town.
Definition: newgrf_house.cpp:112
NF_COMPANY
@ NF_COMPANY
Company news item. (Newspaper with face)
Definition: news_type.h:83
UpdateTownGrowCounter
static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
Updates town grow counter after growth rate change.
Definition: town_cmd.cpp:3625
SetDParam
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings.cpp:104
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
SetGeneratingWorldProgress
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Definition: genworld_gui.cpp:1536
RATING_GROWTH_MAXIMUM
@ RATING_GROWTH_MAXIMUM
... up to RATING_MEDIOCRE
Definition: town_type.h:53
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:311
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:370
GetTownName
static void GetTownName(StringBuilder &builder, const TownNameParams *par, uint32_t townnameparts)
Fills builder with specified town name.
Definition: townname.cpp:48
ROAD_N
@ ROAD_N
Road at the two northern edges.
Definition: road_type.h:61
SLOPE_SW
@ SLOPE_SW
south and west corner are raised
Definition: slope_type.h:56
DrawBuildingsTileStruct
This structure is the same for both Industries and Houses.
Definition: sprite.h:67
cheat_type.h
ClearAllTownCachedNames
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition: town_cmd.cpp:430
Pool::PoolItem<&_town_pool >::CleaningPool
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:318
Town::goal
uint32_t goal[NUM_TAE]
Amount of cargo required for the town to grow.
Definition: town.h:77
BuildTownHouse
static bool BuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
Definition: town_cmd.cpp:2675
MarkTileDirtyByTile
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:2051
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
AddNewsItem
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32_t ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32_t ref2=UINT32_MAX, const NewsAllocatedData *data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:827
FOUNDATION_LEVELED
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition: slope_type.h:95
TAE_WATER
@ TAE_WATER
Cargo behaves water-like.
Definition: cargotype.h:27
IsRoadStop
bool IsRoadStop(Tile t)
Is the station at t a road station?
Definition: station_map.h:202
Kdtree::FindNearest
T FindNearest(CoordT x, CoordT y) const
Find the element closest to given coordinate, in Manhattan distance.
Definition: kdtree.hpp:441
TransportedCargoStat::old_act
Tstorage old_act
Actually transported last month.
Definition: town_type.h:117
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:327
Town::cache
TownCache cache
Container for all cacheable data.
Definition: town.h:53
OverrideManagerBase::ResetOverride
void ResetOverride()
Resets the override, which is used while initializing game.
Definition: newgrf_commons.cpp:78
waypoint_base.h
TrackedViewportSign::kdtree_valid
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Definition: viewport_type.h:50
ForAllStationsAroundTiles
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
Definition: station_base.h:567
HouseSpec::class_id
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:120
Pool::PoolItem<&_town_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:309
IsHouseCompleted
bool IsHouseCompleted(Tile t)
Get the completion of this house.
Definition: town_map.h:146
TownNameParams
Struct holding parameters used to generate town name.
Definition: townname_type.h:28
GetTunnelBridgeTransportType
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
Definition: tunnelbridge_map.h:39
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3783
Town::~Town
~Town()
Destroy the town.
Definition: town_cmd.cpp:108
MakeTownHouse
static void MakeTownHouse(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
Write house information into the map.
Definition: town_cmd.cpp:2472
DIAGDIR_BEGIN
@ DIAGDIR_BEGIN
Used for iterations.
Definition: direction_type.h:74
HouseSpec::building_availability
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:111
MAX_UVALUE
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:391
CheckforTownRating
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3899
TOWN_IS_GROWING
@ TOWN_IS_GROWING
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:192
ChangeTownRating
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3862
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:25
SetDParamStr
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:352
GetLiftDestination
byte GetLiftDestination(Tile t)
Get the current destination for this lift.
Definition: town_map.h:105
HouseID
uint16_t HouseID
OpenTTD ID of house types.
Definition: house_type.h:13
OWNER_DEITY
@ OWNER_DEITY
The object is owned by a superuser / goal script.
Definition: company_type.h:27
IsBridgeAbove
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
TileDesc::str
StringID str
Description of the tile.
Definition: tile_cmd.h:53
EconomySettings::fund_roads
bool fund_roads
allow funding local road reconstruction
Definition: settings_type.h:545
DC_AUTO
@ DC_AUTO
don't allow building on structures
Definition: command_type.h:372
DC_NO_MODIFY_TOWN_RATING
@ DC_NO_MODIFY_TOWN_RATING
do not change town rating
Definition: command_type.h:381
_town_action_costs
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:3210
CanRoadContinueIntoNextTile
static bool CanRoadContinueIntoNextTile(const Town *t, const TileIndex tile, const DiagDirection road_dir)
Checks if a town road can be continued into the next tile.
Definition: town_cmd.cpp:1223
company_func.h
SetRoadOwner
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:251
RoadBits
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:52
StatueBuildSearchData::best_position
TileIndex best_position
Best position found so far.
Definition: town_cmd.cpp:3300
TownCache::num_houses
uint32_t num_houses
Amount of houses.
Definition: town.h:41
ROTF_TOWN_BUILD
@ ROTF_TOWN_BUILD
Bit number for allowing towns to build this roadtype.
Definition: road.h:42
SetTownIndex
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:35
GetOtherTunnelBridgeEnd
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
Definition: tunnelbridge_map.h:78
TACT_NONE
@ TACT_NONE
Empty action set.
Definition: town.h:209
GetHouseNorthPart
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2846
GetLiftPosition
byte GetLiftPosition(Tile t)
Get the position of the lift on this animated house.
Definition: town_map.h:126
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:237
TILE_ADDXY
#define TILE_ADDXY(tile, x, y)
Adds a given offset to a tile.
Definition: map_func.h:480
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:499
TileArea
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:102
TileIndexDiffC::y
int16_t y
The y value of the coordinate.
Definition: map_type.h:33
InclinedSlope
Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition: slope_func.h:256
TownProductionEffect
TownProductionEffect
Town effect when producing cargo.
Definition: cargotype.h:34
CommandHelper
Definition: command_func.h:93
CBID_HOUSE_PRODUCE_CARGO
@ CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
Definition: newgrf_callbacks.h:129
window_func.h
AnimateTile_Town
static void AnimateTile_Town(TileIndex tile)
Animate a tile for a town.
Definition: town_cmd.cpp:345
ROAD_NW
@ ROAD_NW
North-west part.
Definition: road_type.h:54
TownTickHandler
static void TownTickHandler(Town *t)
Handle the town tick for a single town, by growing the town if desired.
Definition: town_cmd.cpp:870
Depot
Definition: depot_base.h:20
RoadTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:142
GrowTownWithExtraHouse
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
Definition: town_cmd.cpp:1162
ROAD_SW
@ ROAD_SW
South-west part.
Definition: road_type.h:55
Town
Town data structure.
Definition: town.h:50
TownCanGrowRoad
static bool TownCanGrowRoad(TileIndex tile)
Test if town can grow road onto a specific tile.
Definition: town_cmd.cpp:1463
ROAD_NONE
@ ROAD_NONE
No road-part is build.
Definition: road_type.h:53
ROTF_NO_HOUSES
@ ROTF_NO_HOUSES
Bit number for setting this roadtype as not house friendly.
Definition: road.h:40
AddChildSpriteScreen
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
Add a child sprite to a parent sprite.
Definition: viewport.cpp:829
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1548
ROAD_SE
@ ROAD_SE
South-east part.
Definition: road_type.h:56
CheckBuildHouseSameZ
static bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
Check if a tile where we want to build a multi-tile house has an appropriate max Z.
Definition: town_cmd.cpp:2519
TileXY
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:385
random_func.hpp
GetTileMaxPixelZ
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:304
TileHeight
static debug_inline uint TileHeight(Tile tile)
Returns the height of a tile.
Definition: tile_map.h:29
CmdDeleteTown
CommandCost CmdDeleteTown(DoCommandFlag flags, TownID town_id)
Delete a town (scenario editor or worldgen only).
Definition: town_cmd.cpp:3115
OverflowSafeInt< int64_t >
GenRandomRoadBits
static RoadBits GenRandomRoadBits()
Generate a random road block.
Definition: town_cmd.cpp:1830
GrowTownWithBridge
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
Definition: town_cmd.cpp:1288
TAE_END
@ TAE_END
End of town effects.
Definition: cargotype.h:29
HouseSpec
Definition: house.h:98
Town::ratings
int16_t ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:73
TownGenerateCargo
static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool affected_by_recession)
Generate cargo for a house, scaled by the current economy scale.
Definition: town_cmd.cpp:531
CmdRenameTown
CommandCost CmdRenameTown(DoCommandFlag flags, TownID town_id, const std::string &text)
Rename a town (server-only).
Definition: town_cmd.cpp:2914
Town::received
TransportedCargoStat< uint16_t > received[NUM_TAE]
Cargo statistics about received cargotypes.
Definition: town.h:76
CBM_HOUSE_AUTOSLOPE
@ CBM_HOUSE_AUTOSLOPE
decides allowance of autosloping
Definition: newgrf_callbacks.h:342
INVALID_COMPANY
@ INVALID_COMPANY
An invalid company.
Definition: company_type.h:30
TRANSPORT_ROAD
@ TRANSPORT_ROAD
Transport by road vehicle.
Definition: transport_type.h:28
NewsStringData::string
std::string string
The string to retain.
Definition: news_type.h:151
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
WC_TOWN_VIEW
@ WC_TOWN_VIEW
Town view; Window numbers:
Definition: window_type.h:333
CmdFoundTown
std::tuple< CommandCost, Money, TownID > CmdFoundTown(DoCommandFlag flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
Create a new town.
Definition: town_cmd.cpp:2097
GenerateTownName
bool GenerateTownName(Randomizer &randomizer, uint32_t *townnameparts, TownNames *town_names)
Generates valid town name.
Definition: townname.cpp:136
Town::layout
TownLayout layout
town specific road layout
Definition: town.h:98
TileInfo::x
int x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:44
FindFirstCargoWithTownAcceptanceEffect
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2948
CheckClearTile
static bool CheckClearTile(TileIndex tile)
Check whether the land can be cleared.
Definition: town_cmd.cpp:3290
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:24
TL_ORIGINAL
@ TL_ORIGINAL
Original algorithm (min. 1 distance between roads)
Definition: town_type.h:82
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition: timer_game_calendar.h:34
IsUniqueTownName
static bool IsUniqueTownName(const std::string &name)
Verifies this custom name is unique.
Definition: town_cmd.cpp:2076
TileInfo::tile
TileIndex tile
Tile index.
Definition: tile_cmd.h:47
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:619
ClearMakeHouseTile
static void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
Clears tile and builds a house or house part.
Definition: town_cmd.cpp:2449
SLOPE_STEEP_W
@ SLOPE_STEEP_W
a steep slope falling to east (from west)
Definition: slope_type.h:66
DC_NONE
@ DC_NONE
no flag is set
Definition: command_type.h:370
NUM_TLS
@ NUM_TLS
Number of town layouts.
Definition: town_type.h:89
_town_draw_tile_data
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition: town_land.h:27
IsTileType
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
EconomyIsInRecession
bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
GetAvailableMoney
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
Definition: company_cmd.cpp:214
Pool::PoolItem<&_town_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:328
CBM_HOUSE_DRAW_FOUNDATIONS
@ CBM_HOUSE_DRAW_FOUNDATIONS
decides if default foundations need to be drawn
Definition: newgrf_callbacks.h:341
ROAD_E
@ ROAD_E
Road at the two eastern edges.
Definition: road_type.h:62
CheckIfAuthorityAllowsNewStation
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
Definition: town_cmd.cpp:3741
FindFurthestFromWater
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
Definition: town_cmd.cpp:2256
TPE_PASSENGERS
@ TPE_PASSENGERS
Cargo behaves passenger-like for production.
Definition: cargotype.h:36
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:319
FACIL_AIRPORT
@ FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:55
TileX
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:427
Town::larger_town
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:97
TownActionAdvertiseMedium
static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
Perform the "medium advertising campaign" town action.
Definition: town_cmd.cpp:3234
DrawTile_Town
static void DrawTile_Town(TileInfo *ti)
Draw a house and its tile.
Definition: town_cmd.cpp:262
MAX_LENGTH_TOWN_NAME_CHARS
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including '\0'.
Definition: town_type.h:110
DecreaseBuildingCount
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
Definition: newgrf_house.cpp:131
BUILDING_IS_HISTORICAL
@ BUILDING_IS_HISTORICAL
this house will only appear during town generation in random games, thus the historical
Definition: house.h:90
CmdDoTownAction
CommandCost CmdDoTownAction(DoCommandFlag flags, TownID town_id, uint8_t action)
Do a town action.
Definition: town_cmd.cpp:3549
TileIndexToTileIndexDiffC
TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition: map_func.h:538
SLOPE_FLAT
@ SLOPE_FLAT
a flat tile
Definition: slope_type.h:49
pool_func.hpp
IsRoadStopTile
bool IsRoadStopTile(Tile t)
Is tile t a road stop station?
Definition: station_map.h:213
TL_2X2_GRID
@ TL_2X2_GRID
Geometric 2x2 grid algorithm.
Definition: town_type.h:84
HouseSpec::remove_rating_decrease
uint16_t remove_rating_decrease
rating decrease if removed
Definition: house.h:105
TOWN_HOUSE_COMPLETED
static const byte TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition: house.h:23
CBM_HOUSE_ALLOW_CONSTRUCTION
@ CBM_HOUSE_ALLOW_CONSTRUCTION
decide whether the house can be built on a given tile
Definition: newgrf_callbacks.h:330
GetBridgeAxis
Axis GetBridgeAxis(Tile t)
Get the axis of the bridge that goes over the tile.
Definition: bridge_map.h:68
Company
Definition: company_base.h:129
GetCargoTranslation
CargoID GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:79
IsSlopeWithOneCornerRaised
bool IsSlopeWithOneCornerRaised(Slope s)
Tests if a specific slope has exactly one corner raised.
Definition: slope_func.h:88
TSZ_LARGE
@ TSZ_LARGE
Large town.
Definition: town_type.h:22
IsLocalCompany
bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:47
Town::name
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition: town.h:59
DifficultySettings::number_towns
byte number_towns
the amount of towns
Definition: settings_type.h:101
Town::exclusivity
CompanyID exclusivity
which company has exclusivity
Definition: town.h:71
RATING_ROAD_NEEDED_LENIENT
@ RATING_ROAD_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
Definition: town_type.h:67
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
IsTileOwner
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3112
UpdateAllStationVirtCoords
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
Definition: station_cmd.cpp:472
HouseSpec::GetRemovalCost
Money GetRemovalCost() const
Get the cost for removing this house.
Definition: town_cmd.cpp:220
GetTropicZone
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition: tile_map.h:238
TOWN_CUSTOM_GROWTH
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
Definition: town.h:195
ROADTYPE_BEGIN
@ ROADTYPE_BEGIN
Used for iterations.
Definition: road_type.h:26
EconomySettings::allow_town_roads
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Definition: settings_type.h:554
TileAddByDiagDir
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:604
GrowTownWithRoad
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
Definition: town_cmd.cpp:1204
GWP_TOWN
@ GWP_TOWN
Generate towns.
Definition: genworld.h:74
HasTileWaterGround
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition: water_map.h:353
CBID_HOUSE_ACCEPT_CARGO
@ CBID_HOUSE_ACCEPT_CARGO
Called to determine which cargoes a town building should accept.
Definition: newgrf_callbacks.h:114
TileIndexDiffC::x
int16_t x
The x value of the coordinate.
Definition: map_type.h:32
GetMaskOfTownActions
TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
Get a list of available town authority actions.
Definition: town_cmd.cpp:3501
newgrf_cargo.h
CheckTownBuild2House
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
Definition: town_cmd.cpp:2627
Object::town
Town * town
Town the object is built in.
Definition: object_base.h:25
Convert8bitBooleanCallback
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
Definition: newgrf_commons.cpp:548
town_kdtree.h
TOWN_HAS_CHURCH
@ TOWN_HAS_CHURCH
There can be only one church by town.
Definition: town.h:193
Town::exclusive_counter
uint8_t exclusive_counter
months till the exclusivity expires
Definition: town.h:72
IsRoadDepot
static debug_inline bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition: road_map.h:106
town_land.h
TownCache::squared_town_zone_radius
uint32_t squared_town_zone_radius[HZB_END]
UpdateTownRadius updates this given the house count.
Definition: town.h:45
HouseSpec::grf_prop
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:115
Town::cached_name
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition: town.h:60
TownActions
TownActions
Town actions of a company.
Definition: town.h:208
CUSTOM_TOWN_NUMBER_DIFFICULTY
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:26
SLOPE_STEEP_N
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
Definition: slope_type.h:69
OWNER_TOWN
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
CmdTownGrowthRate
CommandCost CmdTownGrowthRate(DoCommandFlag flags, TownID town_id, uint16_t growth_rate)
Change the growth rate of the town.
Definition: town_cmd.cpp:3015
CBID_HOUSE_AUTOSLOPE
@ CBID_HOUSE_AUTOSLOPE
Called to determine if one can alter the ground below a house tile.
Definition: newgrf_callbacks.h:230
UpdateTownGrowthRate
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
Definition: town_cmd.cpp:3684
timer_game_economy.h
road_cmd.h
IsDriveThroughStopTile
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station?
Definition: station_map.h:233
DrawGroundSprite
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition: viewport.cpp:589
AT_OILRIG
@ AT_OILRIG
Oilrig airport.
Definition: airport.h:38
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:635
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:27
TownCache::sign
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:43
object.h
RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
@ RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
"Neutral"
Definition: town_type.h:60
IsRoadDepotTile
static debug_inline bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
Definition: road_map.h:116
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:98
CheckFree2x2Area
static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
Checks if a house of size 2x2 can be built at this tile.
Definition: town_cmd.cpp:2538
Town::flags
byte flags
See TownFlags.
Definition: town.h:62
TACT_BUY_RIGHTS
@ TACT_BUY_RIGHTS
Buy exclusive transport rights.
Definition: town.h:217
EconomySettings::initial_city_size
uint8_t initial_city_size
multiplier for the initial size of the cities compared to towns
Definition: settings_type.h:551
news_func.h
AddAnimatedTile
void AddAnimatedTile(TileIndex tile)
Add the given tile to the animated tile table (if it does not exist on that table yet).
Definition: animated_tile.cpp:40
GetTunnelBridgeDirection
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
Definition: tunnelbridge_map.h:26
SpotData::layout
TownLayout layout
tells us what kind of town we're building
Definition: town_cmd.cpp:2237
GetNormalGrowthRate
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
Definition: town_cmd.cpp:3657
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition: timer_game_calendar.h:32
GetTownIndex
TownID GetTownIndex(Tile t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:23
IsTileAlignedToGrid
static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
Definition: town_cmd.cpp:2222
CanBuildHouseHere
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Check if a house can be built here, based on slope, whether there's a bridge above,...
Definition: town_cmd.cpp:2494
backup_type.hpp
IsSea
bool IsSea(Tile t)
Is it a sea water tile?
Definition: water_map.h:161
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103