OpenTTD
town_cmd.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 #include "road_internal.h" /* Cleaning up road bits */
14 #include "road_cmd.h"
15 #include "landscape.h"
16 #include "viewport_func.h"
17 #include "cmd_helper.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "station_base.h"
21 #include "company_base.h"
22 #include "news_func.h"
23 #include "error.h"
24 #include "object.h"
25 #include "genworld.h"
26 #include "newgrf_debug.h"
27 #include "newgrf_house.h"
28 #include "newgrf_text.h"
29 #include "autoslope.h"
30 #include "tunnelbridge_map.h"
31 #include "strings_func.h"
32 #include "window_func.h"
33 #include "string_func.h"
34 #include "newgrf_cargo.h"
35 #include "cheat_type.h"
36 #include "animated_tile_func.h"
37 #include "date_func.h"
38 #include "subsidy_func.h"
39 #include "core/pool_func.hpp"
40 #include "town.h"
41 #include "townname_func.h"
42 #include "core/random_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "depot_base.h"
45 #include "object_map.h"
46 #include "object_base.h"
47 #include "ai/ai.hpp"
48 #include "game/game.hpp"
49 
50 #include "table/strings.h"
51 #include "table/town_land.h"
52 
53 #include "safeguards.h"
54 
55 TownID _new_town_id;
57 
58 /* Initialize the town-pool */
59 TownPool _town_pool("Town");
61 
63 {
64  free(this->name);
65  free(this->text);
66 
67  if (CleaningPool()) return;
68 
69  /* Delete town authority window
70  * and remove from list of sorted towns */
71  DeleteWindowById(WC_TOWN_VIEW, this->index);
72 
73  /* Check no industry is related to us. */
74  const Industry *i;
75  FOR_ALL_INDUSTRIES(i) assert(i->town != this);
76 
77  /* ... and no object is related to us. */
78  const Object *o;
79  FOR_ALL_OBJECTS(o) assert(o->town != this);
80 
81  /* Check no tile is related to us. */
82  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
83  switch (GetTileType(tile)) {
84  case MP_HOUSE:
85  assert(GetTownIndex(tile) != this->index);
86  break;
87 
88  case MP_ROAD:
89  assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
90  break;
91 
92  case MP_TUNNELBRIDGE:
93  assert(!IsTileOwner(tile, OWNER_TOWN) || ClosestTownFromTile(tile, UINT_MAX) != this);
94  break;
95 
96  default:
97  break;
98  }
99  }
100 
101  /* Clear the persistent storage list. */
102  this->psa_list.clear();
103 
104  DeleteSubsidyWith(ST_TOWN, this->index);
108 }
109 
110 
116 void Town::PostDestructor(size_t index)
117 {
120 
121  /* Give objects a new home! */
122  Object *o;
123  FOR_ALL_OBJECTS(o) {
124  if (o->town == NULL) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
125  }
126 }
127 
132 {
133  if (layout != TL_RANDOM) {
134  this->layout = layout;
135  return;
136  }
137 
138  this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
139 }
140 
145 /* static */ Town *Town::GetRandom()
146 {
147  if (Town::GetNumItems() == 0) return NULL;
148  int num = RandomRange((uint16)Town::GetNumItems());
149  size_t index = MAX_UVALUE(size_t);
150 
151  while (num >= 0) {
152  num--;
153  index++;
154 
155  /* Make sure we have a valid town */
156  while (!Town::IsValidID(index)) {
157  index++;
158  assert(index < Town::GetPoolSize());
159  }
160  }
161 
162  return Town::Get(index);
163 }
164 
170 {
171  return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
172 }
173 
174 /* Local */
175 static int _grow_town_result;
176 
177 /* Describe the possible states */
178 enum TownGrowthResult {
179  GROWTH_SUCCEED = -1,
180  GROWTH_SEARCH_STOPPED = 0
181 // GROWTH_SEARCH_RUNNING >= 1
182 };
183 
184 static bool BuildTownHouse(Town *t, TileIndex tile);
185 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);
186 
187 static void TownDrawHouseLift(const TileInfo *ti)
188 {
189  AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
190 }
191 
192 typedef void TownDrawTileProc(const TileInfo *ti);
193 static TownDrawTileProc * const _town_draw_tile_procs[1] = {
194  TownDrawHouseLift
195 };
196 
203 {
204  return (DiagDirection)(3 & Random());
205 }
206 
212 static void DrawTile_Town(TileInfo *ti)
213 {
214  HouseID house_id = GetHouseType(ti->tile);
215 
216  if (house_id >= NEW_HOUSE_OFFSET) {
217  /* Houses don't necessarily need new graphics. If they don't have a
218  * spritegroup associated with them, then the sprite for the substitute
219  * house id is drawn instead. */
220  if (HouseSpec::Get(house_id)->grf_prop.spritegroup[0] != NULL) {
221  DrawNewHouseTile(ti, house_id);
222  return;
223  } else {
224  house_id = HouseSpec::Get(house_id)->grf_prop.subst_id;
225  }
226  }
227 
228  /* Retrieve pointer to the draw town tile struct */
229  const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
230 
232 
233  DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
234 
235  /* If houses are invisible, do not draw the upper part */
236  if (IsInvisibilitySet(TO_HOUSES)) return;
237 
238  /* Add a house on top of the ground? */
239  SpriteID image = dcts->building.sprite;
240  if (image != 0) {
241  AddSortableSpriteToDraw(image, dcts->building.pal,
242  ti->x + dcts->subtile_x,
243  ti->y + dcts->subtile_y,
244  dcts->width,
245  dcts->height,
246  dcts->dz,
247  ti->z,
249  );
250 
251  if (IsTransparencySet(TO_HOUSES)) return;
252  }
253 
254  {
255  int proc = dcts->draw_proc - 1;
256 
257  if (proc >= 0) _town_draw_tile_procs[proc](ti);
258  }
259 }
260 
261 static int GetSlopePixelZ_Town(TileIndex tile, uint x, uint y)
262 {
263  return GetTileMaxPixelZ(tile);
264 }
265 
268 {
269  HouseID hid = GetHouseType(tile);
270 
271  /* For NewGRF house tiles we might not be drawing a foundation. We need to
272  * account for this, as other structures should
273  * draw the wall of the foundation in this case.
274  */
275  if (hid >= NEW_HOUSE_OFFSET) {
276  const HouseSpec *hs = HouseSpec::Get(hid);
278  uint32 callback_res = GetHouseCallback(CBID_HOUSE_DRAW_FOUNDATIONS, 0, 0, hid, Town::GetByTile(tile), tile);
279  if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
280  }
281  }
282  return FlatteningFoundation(tileh);
283 }
284 
291 static void AnimateTile_Town(TileIndex tile)
292 {
293  if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
294  AnimateNewHouseTile(tile);
295  return;
296  }
297 
298  if (_tick_counter & 3) return;
299 
300  /* If the house is not one with a lift anymore, then stop this animating.
301  * Not exactly sure when this happens, but probably when a house changes.
302  * Before this was just a return...so it'd leak animated tiles..
303  * That bug seems to have been here since day 1?? */
304  if (!(HouseSpec::Get(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
305  DeleteAnimatedTile(tile);
306  return;
307  }
308 
309  if (!LiftHasDestination(tile)) {
310  uint i;
311 
312  /* Building has 6 floors, number 0 .. 6, where 1 is illegal.
313  * This is due to the fact that the first floor is, in the graphics,
314  * the height of 2 'normal' floors.
315  * Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
316  do {
317  i = RandomRange(7);
318  } while (i == 1 || i * 6 == GetLiftPosition(tile));
319 
320  SetLiftDestination(tile, i);
321  }
322 
323  int pos = GetLiftPosition(tile);
324  int dest = GetLiftDestination(tile) * 6;
325  pos += (pos < dest) ? 1 : -1;
326  SetLiftPosition(tile, pos);
327 
328  if (pos == dest) {
329  HaltLift(tile);
330  DeleteAnimatedTile(tile);
331  }
332 
333  MarkTileDirtyByTile(tile);
334 }
335 
342 static bool IsCloseToTown(TileIndex tile, uint dist)
343 {
344  /* On a large map with many towns, it may be faster to check the surroundings of the tile.
345  * An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
346  if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
347  const int tx = TileX(tile);
348  const int ty = TileY(tile);
349  TileArea tile_area = TileArea(
350  TileXY(max(0, tx - (int) dist), max(0, ty - (int) dist)),
351  TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
352  );
353  TILE_AREA_LOOP(atile, tile_area) {
354  if (GetTileType(atile) == MP_HOUSE) {
355  Town *t = Town::GetByTile(atile);
356  if (DistanceManhattan(tile, t->xy) < dist) return true;
357  }
358  }
359  return false;
360  }
361 
362  const Town *t;
363 
364  FOR_ALL_TOWNS(t) {
365  if (DistanceManhattan(tile, t->xy) < dist) return true;
366  }
367  return false;
368 }
369 
375 {
376  Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
377  SetDParam(0, this->index);
378  SetDParam(1, this->cache.population);
379  this->cache.sign.UpdatePosition(pt.x, pt.y - 24 * ZOOM_LVL_BASE,
380  _settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_VIEWPORT_TOWN,
381  STR_VIEWPORT_TOWN);
382 
384 }
385 
388 {
389  Town *t;
390 
391  FOR_ALL_TOWNS(t) {
392  t->UpdateVirtCoord();
393  }
394 }
395 
401 static void ChangePopulation(Town *t, int mod)
402 {
403  t->cache.population += mod;
404  InvalidateWindowData(WC_TOWN_VIEW, t->index); // Cargo requirements may appear/vanish for small populations
405  t->UpdateVirtCoord();
406 
408 }
409 
416 {
417  uint32 pop = 0;
418  const Town *t;
419 
420  FOR_ALL_TOWNS(t) pop += t->cache.population;
421  return pop;
422 }
423 
429 {
430  assert(IsTileType(tile, MP_HOUSE));
431 
432  /* progress in construction stages */
434  if (GetHouseConstructionTick(tile) != 0) return;
435 
436  AnimateNewHouseConstruction(tile);
437 
438  if (IsHouseCompleted(tile)) {
439  /* Now that construction is complete, we can add the population of the
440  * building to the town. */
441  ChangePopulation(Town::GetByTile(tile), HouseSpec::Get(GetHouseType(tile))->population);
442  ResetHouseAge(tile);
443  }
444  MarkTileDirtyByTile(tile);
445 }
446 
452 {
453  uint flags = HouseSpec::Get(GetHouseType(tile))->building_flags;
454  if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
455  if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
456  if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
457  if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
458 }
459 
466 static void TileLoop_Town(TileIndex tile)
467 {
468  HouseID house_id = GetHouseType(tile);
469 
470  /* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
471  * doesn't exist any more, so don't continue here. */
472  if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
473 
474  if (!IsHouseCompleted(tile)) {
475  /* Construction is not completed. See if we can go further in construction*/
476  MakeTownHouseBigger(tile);
477  return;
478  }
479 
480  const HouseSpec *hs = HouseSpec::Get(house_id);
481 
482  /* If the lift has a destination, it is already an animated tile. */
483  if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
484  house_id < NEW_HOUSE_OFFSET &&
485  !LiftHasDestination(tile) &&
486  Chance16(1, 2)) {
487  AddAnimatedTile(tile);
488  }
489 
490  Town *t = Town::GetByTile(tile);
491  uint32 r = Random();
492 
493  StationFinder stations(TileArea(tile, 1, 1));
494 
496  for (uint i = 0; i < 256; i++) {
497  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
498 
499  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
500 
501  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
502  if (cargo == CT_INVALID) continue;
503 
504  uint amt = GB(callback, 0, 8);
505  if (amt == 0) continue;
506 
507  uint moved = MoveGoodsToStation(cargo, amt, ST_TOWN, t->index, stations.GetStations());
508 
509  const CargoSpec *cs = CargoSpec::Get(cargo);
510  t->supplied[cs->Index()].new_max += amt;
511  t->supplied[cs->Index()].new_act += moved;
512  }
513  } else {
514  if (GB(r, 0, 8) < hs->population) {
515  uint amt = GB(r, 0, 8) / 8 + 1;
516 
517  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
518  t->supplied[CT_PASSENGERS].new_max += amt;
519  t->supplied[CT_PASSENGERS].new_act += MoveGoodsToStation(CT_PASSENGERS, amt, ST_TOWN, t->index, stations.GetStations());
520  }
521 
522  if (GB(r, 8, 8) < hs->mail_generation) {
523  uint amt = GB(r, 8, 8) / 8 + 1;
524 
525  if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
526  t->supplied[CT_MAIL].new_max += amt;
527  t->supplied[CT_MAIL].new_act += MoveGoodsToStation(CT_MAIL, amt, ST_TOWN, t->index, stations.GetStations());
528  }
529  }
530 
531  Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
532 
533  if ((hs->building_flags & BUILDING_HAS_1_TILE) &&
535  CanDeleteHouse(tile) &&
536  GetHouseAge(tile) >= hs->minimum_life &&
537  --t->time_until_rebuild == 0) {
538  t->time_until_rebuild = GB(r, 16, 8) + 192;
539 
540  ClearTownHouse(t, tile);
541 
542  /* Rebuild with another house? */
543  if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
544  }
545 
546  cur_company.Restore();
547 }
548 
549 static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
550 {
551  if (flags & DC_AUTO) return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
552  if (!CanDeleteHouse(tile)) return CMD_ERROR;
553 
554  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
555 
557  cost.AddCost(hs->GetRemovalCost());
558 
559  int rating = hs->remove_rating_decrease;
560  Town *t = Town::GetByTile(tile);
561 
563  if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
564  SetDParam(0, t->index);
565  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
566  }
567  }
568 
569  ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
570  if (flags & DC_EXEC) {
571  ClearTownHouse(t, tile);
572  }
573 
574  return cost;
575 }
576 
577 static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
578 {
579  HouseID house_id = GetHouseType(tile);
580  const HouseSpec *hs = HouseSpec::Get(house_id);
581  Town *t = Town::GetByTile(tile);
582 
584  for (uint i = 0; i < 256; i++) {
585  uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
586 
587  if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
588 
589  CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grf_prop.grffile);
590 
591  if (cargo == CT_INVALID) continue;
592  produced[cargo]++;
593  }
594  } else {
595  if (hs->population > 0) {
596  produced[CT_PASSENGERS]++;
597  }
598  if (hs->mail_generation > 0) {
599  produced[CT_MAIL]++;
600  }
601  }
602 }
603 
604 static inline void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes *always_accepted)
605 {
606  if (cargo == CT_INVALID || amount == 0) return;
607  acceptance[cargo] += amount;
608  SetBit(*always_accepted, cargo);
609 }
610 
611 static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes *always_accepted)
612 {
613  const HouseSpec *hs = HouseSpec::Get(GetHouseType(tile));
614  CargoID accepts[lengthof(hs->accepts_cargo)];
615 
616  /* Set the initial accepted cargo types */
617  for (uint8 i = 0; i < lengthof(accepts); i++) {
618  accepts[i] = hs->accepts_cargo[i];
619  }
620 
621  /* Check for custom accepted cargo types */
623  uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
624  if (callback != CALLBACK_FAILED) {
625  /* Replace accepted cargo types with translated values from callback */
626  accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grf_prop.grffile);
627  accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grf_prop.grffile);
628  accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grf_prop.grffile);
629  }
630  }
631 
632  /* Check for custom cargo acceptance */
634  uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), Town::GetByTile(tile), tile);
635  if (callback != CALLBACK_FAILED) {
636  AddAcceptedCargoSetMask(accepts[0], GB(callback, 0, 4), acceptance, always_accepted);
637  AddAcceptedCargoSetMask(accepts[1], GB(callback, 4, 4), acceptance, always_accepted);
638  if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
639  /* The 'S' bit indicates food instead of goods */
640  AddAcceptedCargoSetMask(CT_FOOD, GB(callback, 8, 4), acceptance, always_accepted);
641  } else {
642  AddAcceptedCargoSetMask(accepts[2], GB(callback, 8, 4), acceptance, always_accepted);
643  }
644  return;
645  }
646  }
647 
648  /* No custom acceptance, so fill in with the default values */
649  for (uint8 i = 0; i < lengthof(accepts); i++) {
650  AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
651  }
652 }
653 
654 static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
655 {
656  const HouseID house = GetHouseType(tile);
657  const HouseSpec *hs = HouseSpec::Get(house);
658  bool house_completed = IsHouseCompleted(tile);
659 
660  td->str = hs->building_name;
661 
662  uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
663  if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
664  if (callback_res > 0x400) {
666  } else {
667  StringID new_name = GetGRFStringID(hs->grf_prop.grffile->grfid, 0xD000 + callback_res);
668  if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
669  td->str = new_name;
670  }
671  }
672  }
673 
674  if (!house_completed) {
675  SetDParamX(td->dparam, 0, td->str);
676  td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
677  }
678 
679  if (hs->grf_prop.grffile != NULL) {
680  const GRFConfig *gc = GetGRFConfig(hs->grf_prop.grffile->grfid);
681  td->grf = gc->GetName();
682  }
683 
684  td->owner[0] = OWNER_TOWN;
685 }
686 
687 static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
688 {
689  /* not used */
690  return 0;
691 }
692 
693 static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
694 {
695  /* not used */
696 }
697 
702 {
703  t->cargo_accepted_total = 0;
704 
705  const TileArea &area = t->cargo_accepted.GetArea();
706  TILE_AREA_LOOP(tile, area) {
707  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
708  t->cargo_accepted_total |= t->cargo_accepted[tile];
709  }
710  }
711 }
712 
719 static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total = true)
720 {
721  CargoArray accepted, produced;
722  CargoTypes dummy = 0;
723 
724  /* Gather acceptance for all houses in an area around the start tile.
725  * The area is composed of the square the tile is in, extended one square in all
726  * directions as the coverage area of a single station is bigger than just one square. */
728  TILE_AREA_LOOP(tile, area) {
729  if (!IsTileType(tile, MP_HOUSE) || GetTownIndex(tile) != t->index) continue;
730 
731  AddAcceptedCargo_Town(tile, accepted, &dummy);
732  AddProducedCargo_Town(tile, produced);
733  }
734 
735  /* Create bitmap of produced and accepted cargoes. */
736  CargoTypes acc = 0;
737  for (uint cid = 0; cid < NUM_CARGO; cid++) {
738  if (accepted[cid] >= 8) SetBit(acc, cid);
739  if (produced[cid] > 0) SetBit(t->cargo_produced, cid);
740  }
741  t->cargo_accepted[start] = acc;
742 
743  if (update_total) UpdateTownCargoTotal(t);
744 }
745 
750 {
751  t->cargo_produced = 0;
752 
753  const TileArea &area = t->cargo_accepted.GetArea();
754  if (area.tile == INVALID_TILE) return;
755 
756  /* Update acceptance for each grid square. */
757  TILE_AREA_LOOP(tile, area) {
758  if (TileX(tile) % AcceptanceMatrix::GRID == 0 && TileY(tile) % AcceptanceMatrix::GRID == 0) {
759  UpdateTownCargoes(t, tile, false);
760  }
761  }
762 
763  /* Update the total acceptance. */
765 }
766 
769 {
770  Town *town;
772 
773  FOR_ALL_TOWNS(town) {
775  }
776 }
777 
778 static bool GrowTown(Town *t);
779 
780 static void TownTickHandler(Town *t)
781 {
782  if (HasBit(t->flags, TOWN_IS_GROWING)) {
783  int i = (int)t->grow_counter - 1;
784  if (i < 0) {
785  if (GrowTown(t)) {
786  i = t->growth_rate;
787  } else {
788  /* If growth failed wait a bit before retrying */
789  i = min(t->growth_rate, TOWN_GROWTH_TICKS - 1);
790  }
791  }
792  t->grow_counter = i;
793  }
794 }
795 
796 void OnTick_Town()
797 {
798  if (_game_mode == GM_EDITOR) return;
799 
800  Town *t;
801  FOR_ALL_TOWNS(t) {
802  TownTickHandler(t);
803  }
804 }
805 
815 {
816  if (IsRoadDepotTile(tile) || IsStandardRoadStopTile(tile)) return ROAD_NONE;
817 
818  return GetAnyRoadBits(tile, ROADTYPE_ROAD, true);
819 }
820 
831 static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
832 {
833  if (!IsValidTile(tile)) return false;
834 
835  /* Lookup table for the used diff values */
836  const TileIndexDiff tid_lt[3] = {
840  };
841 
842  dist_multi = (dist_multi + 1) * 4;
843  for (uint pos = 4; pos < dist_multi; pos++) {
844  /* Go (pos / 4) tiles to the left or the right */
845  TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
846 
847  /* Use the current tile as origin, or go one tile backwards */
848  if (pos & 2) cur += tid_lt[2];
849 
850  /* Test for roadbit parallel to dir and facing towards the middle axis */
851  if (IsValidTile(tile + cur) &&
852  GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
853  }
854  return false;
855 }
856 
865 static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
866 {
867  if (DistanceFromEdge(tile) == 0) return false;
868 
869  /* Prevent towns from building roads under bridges along the bridge. Looks silly. */
870  if (IsBridgeAbove(tile) && GetBridgeAxis(tile) == DiagDirToAxis(dir)) return false;
871 
872  /* Check if there already is a road at this point? */
873  if (GetTownRoadBits(tile) == ROAD_NONE) {
874  /* No, try if we are able to build a road piece there.
875  * If that fails clear the land, and if that fails exit.
876  * This is to make sure that we can build a road here later. */
877  if (DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_Y : ROAD_X), 0, DC_AUTO, CMD_BUILD_ROAD).Failed() &&
878  DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR).Failed()) {
879  return false;
880  }
881  }
882 
884  bool ret = !IsNeighborRoadTile(tile, dir, t->layout == TL_ORIGINAL ? 1 : 2);
885  if (cur_slope == SLOPE_FLAT) return ret;
886 
887  /* If the tile is not a slope in the right direction, then
888  * maybe terraform some. */
889  Slope desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
890  if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
891  if (Chance16(1, 8)) {
892  CommandCost res = CMD_ERROR;
893  if (!_generating_world && Chance16(1, 10)) {
894  /* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
895  res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
897  }
898  if (res.Failed() && Chance16(1, 3)) {
899  /* We can consider building on the slope, though. */
900  return ret;
901  }
902  }
903  return false;
904  }
905  return ret;
906 }
907 
908 static bool TerraformTownTile(TileIndex tile, int edges, int dir)
909 {
910  assert(tile < MapSize());
911 
912  CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
913  if (r.Failed() || r.GetCost() >= (_price[PR_TERRAFORM] + 2) * 8) return false;
914  DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
915  return true;
916 }
917 
918 static void LevelTownLand(TileIndex tile)
919 {
920  assert(tile < MapSize());
921 
922  /* Don't terraform if land is plain or if there's a house there. */
923  if (IsTileType(tile, MP_HOUSE)) return;
924  Slope tileh = GetTileSlope(tile);
925  if (tileh == SLOPE_FLAT) return;
926 
927  /* First try up, then down */
928  if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
929  TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
930  }
931 }
932 
943 {
944  /* align the grid to the downtown */
945  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
946  RoadBits rcmd = ROAD_NONE;
947 
948  switch (t->layout) {
949  default: NOT_REACHED();
950 
951  case TL_2X2_GRID:
952  if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
953  if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
954  break;
955 
956  case TL_3X3_GRID:
957  if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
958  if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
959  break;
960  }
961 
962  /* Optimise only X-junctions */
963  if (rcmd != ROAD_ALL) return rcmd;
964 
965  RoadBits rb_template;
966 
967  switch (GetTileSlope(tile)) {
968  default: rb_template = ROAD_ALL; break;
969  case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
970  case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
971  case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
972  case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
973  case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
974  case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
975  case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
976  case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
977  case SLOPE_STEEP_W:
978  case SLOPE_STEEP_S:
979  case SLOPE_STEEP_E:
980  case SLOPE_STEEP_N:
981  rb_template = ROAD_NONE;
982  break;
983  }
984 
985  /* Stop if the template is compatible to the growth dir */
986  if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
987  /* If not generate a straight road in the direction of the growth */
989 }
990 
1002 {
1003  /* We can't look further than that. */
1004  if (DistanceFromEdge(tile) == 0) return false;
1005 
1006  uint counter = 0; // counts the house neighbor tiles
1007 
1008  /* Check the tiles E,N,W and S of the current tile for houses */
1009  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1010  /* Count both void and house tiles for checking whether there
1011  * are enough houses in the area. This to make it likely that
1012  * houses get build up to the edge of the map. */
1013  switch (GetTileType(TileAddByDiagDir(tile, dir))) {
1014  case MP_HOUSE:
1015  case MP_VOID:
1016  counter++;
1017  break;
1018 
1019  default:
1020  break;
1021  }
1022 
1023  /* If there are enough neighbors stop here */
1024  if (counter >= 3) {
1025  if (BuildTownHouse(t, tile)) {
1026  _grow_town_result = GROWTH_SUCCEED;
1027  return true;
1028  }
1029  return false;
1030  }
1031  }
1032  return false;
1033 }
1034 
1043 static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
1044 {
1045  if (DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD).Succeeded()) {
1046  _grow_town_result = GROWTH_SUCCEED;
1047  return true;
1048  }
1049  return false;
1050 }
1051 
1062 static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
1063 {
1064  assert(bridge_dir < DIAGDIR_END);
1065 
1066  const Slope slope = GetTileSlope(tile);
1067 
1068  /* Make sure the direction is compatible with the slope.
1069  * Well we check if the slope has an up bit set in the
1070  * reverse direction. */
1071  if (slope != SLOPE_FLAT && slope & InclinedSlope(bridge_dir)) return false;
1072 
1073  /* Assure that the bridge is connectable to the start side */
1074  if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
1075 
1076  /* We are in the right direction */
1077  uint8 bridge_length = 0; // This value stores the length of the possible bridge
1078  TileIndex bridge_tile = tile; // Used to store the other waterside
1079 
1080  const int delta = TileOffsByDiagDir(bridge_dir);
1081 
1082  if (slope == SLOPE_FLAT) {
1083  /* Bridges starting on flat tiles are only allowed when crossing rivers, rails or one-way roads. */
1084  do {
1085  if (bridge_length++ >= 4) {
1086  /* Allow to cross rivers, not big lakes, nor large amounts of rails or one-way roads. */
1087  return false;
1088  }
1089  bridge_tile += delta;
1090  } while (IsValidTile(bridge_tile) && ((IsWaterTile(bridge_tile) && !IsSea(bridge_tile)) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1091  } else {
1092  do {
1093  if (bridge_length++ >= 11) {
1094  /* Max 11 tile long bridges */
1095  return false;
1096  }
1097  bridge_tile += delta;
1098  } while (IsValidTile(bridge_tile) && (IsWaterTile(bridge_tile) || IsPlainRailTile(bridge_tile) || (IsNormalRoadTile(bridge_tile) && GetDisallowedRoadDirections(bridge_tile) != DRD_NONE)));
1099  }
1100 
1101  /* no water tiles in between? */
1102  if (bridge_length == 1) return false;
1103 
1104  for (uint8 times = 0; times <= 22; times++) {
1105  byte bridge_type = RandomRange(MAX_BRIDGES - 1);
1106 
1107  /* Can we actually build the bridge? */
1108  if (DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, CommandFlagsToDCFlags(GetCommandFlags(CMD_BUILD_BRIDGE)), CMD_BUILD_BRIDGE).Succeeded()) {
1110  _grow_town_result = GROWTH_SUCCEED;
1111  return true;
1112  }
1113  }
1114  /* Quit if it selecting an appropriate bridge type fails a large number of times. */
1115  return false;
1116 }
1117 
1135 static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
1136 {
1137  RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
1138  TileIndex tile = *tile_ptr; // The main tile on which we base our growth
1139 
1140  assert(tile < MapSize());
1141 
1142  if (cur_rb == ROAD_NONE) {
1143  /* Tile has no road. First reset the status counter
1144  * to say that this is the last iteration. */
1145  _grow_town_result = GROWTH_SEARCH_STOPPED;
1146 
1149 
1150  /* Remove hills etc */
1151  if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
1152 
1153  /* Is a road allowed here? */
1154  switch (t1->layout) {
1155  default: NOT_REACHED();
1156 
1157  case TL_3X3_GRID:
1158  case TL_2X2_GRID:
1159  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1160  if (rcmd == ROAD_NONE) return;
1161  break;
1162 
1163  case TL_BETTER_ROADS:
1164  case TL_ORIGINAL:
1165  if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
1166 
1167  DiagDirection source_dir = ReverseDiagDir(target_dir);
1168 
1169  if (Chance16(1, 4)) {
1170  /* Randomize a new target dir */
1171  do target_dir = RandomDiagDir(); while (target_dir == source_dir);
1172  }
1173 
1174  if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
1175  /* A road is not allowed to continue the randomized road,
1176  * return if the road we're trying to build is curved. */
1177  if (target_dir != ReverseDiagDir(source_dir)) return;
1178 
1179  /* Return if neither side of the new road is a house */
1182  return;
1183  }
1184 
1185  /* That means that the road is only allowed if there is a house
1186  * at any side of the new road. */
1187  }
1188 
1189  rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
1190  break;
1191  }
1192 
1193  } else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
1194  /* Continue building on a partial road.
1195  * Should be always OK, so we only generate
1196  * the fitting RoadBits */
1197  _grow_town_result = GROWTH_SEARCH_STOPPED;
1198 
1200 
1201  switch (t1->layout) {
1202  default: NOT_REACHED();
1203 
1204  case TL_3X3_GRID:
1205  case TL_2X2_GRID:
1206  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1207  break;
1208 
1209  case TL_BETTER_ROADS:
1210  case TL_ORIGINAL:
1211  rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
1212  break;
1213  }
1214  } else {
1215  bool allow_house = true; // Value which decides if we want to construct a house
1216 
1217  /* Reached a tunnel/bridge? Then continue at the other side of it, unless
1218  * it is the starting tile. Half the time, we stay on this side then.*/
1219  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1220  if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD && (target_dir != DIAGDIR_END || Chance16(1, 2))) {
1221  *tile_ptr = GetOtherTunnelBridgeEnd(tile);
1222  }
1223  return;
1224  }
1225 
1226  /* Possibly extend the road in a direction.
1227  * Randomize a direction and if it has a road, bail out. */
1228  target_dir = RandomDiagDir();
1229  RoadBits target_rb = DiagDirToRoadBits(target_dir);
1230  TileIndex house_tile; // position of a possible house
1231 
1232  if (cur_rb & target_rb) {
1233  /* If it's a road turn possibly build a house in a corner.
1234  * Use intersection with straight road as an indicator
1235  * that we randomed corner house position.
1236  * A turn (and we check for that later) always has only
1237  * one common bit with a straight road so it has the same
1238  * chance to be chosen as the house on the side of a road.
1239  */
1240  if ((cur_rb & ROAD_X) != target_rb) return;
1241 
1242  /* Check whether it is a turn and if so determine
1243  * position of the corner tile */
1244  switch (cur_rb) {
1245  case ROAD_N:
1246  house_tile = TileAddByDir(tile, DIR_S);
1247  break;
1248  case ROAD_S:
1249  house_tile = TileAddByDir(tile, DIR_N);
1250  break;
1251  case ROAD_E:
1252  house_tile = TileAddByDir(tile, DIR_W);
1253  break;
1254  case ROAD_W:
1255  house_tile = TileAddByDir(tile, DIR_E);
1256  break;
1257  default:
1258  return; // not a turn
1259  }
1260  target_dir = DIAGDIR_END;
1261  } else {
1262  house_tile = TileAddByDiagDir(tile, target_dir);
1263  }
1264 
1265  /* Don't walk into water. */
1266  if (HasTileWaterGround(house_tile)) return;
1267 
1268  if (!IsValidTile(house_tile)) return;
1269 
1271  switch (t1->layout) {
1272  default: NOT_REACHED();
1273 
1274  case TL_3X3_GRID: // Use 2x2 grid afterwards!
1275  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1276  FALLTHROUGH;
1277 
1278  case TL_2X2_GRID:
1279  rcmd = GetTownRoadGridElement(t1, tile, target_dir);
1280  allow_house = (rcmd & target_rb) == ROAD_NONE;
1281  break;
1282 
1283  case TL_BETTER_ROADS: // Use original afterwards!
1284  GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
1285  FALLTHROUGH;
1286 
1287  case TL_ORIGINAL:
1288  /* Allow a house at the edge. 60% chance or
1289  * always ok if no road allowed. */
1290  rcmd = target_rb;
1291  allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
1292  break;
1293  }
1294  }
1295 
1296  if (allow_house) {
1297  /* Build a house, but not if there already is a house there. */
1298  if (!IsTileType(house_tile, MP_HOUSE)) {
1299  /* Level the land if possible */
1300  if (Chance16(1, 6)) LevelTownLand(house_tile);
1301 
1302  /* And build a house.
1303  * Set result to -1 if we managed to build it. */
1304  if (BuildTownHouse(t1, house_tile)) {
1305  _grow_town_result = GROWTH_SUCCEED;
1306  }
1307  }
1308  return;
1309  }
1310 
1311  _grow_town_result = GROWTH_SEARCH_STOPPED;
1312  }
1313 
1314  /* Return if a water tile */
1315  if (HasTileWaterGround(tile)) return;
1316 
1317  /* Make the roads look nicer */
1318  rcmd = CleanUpRoadBits(tile, rcmd);
1319  if (rcmd == ROAD_NONE) return;
1320 
1321  /* Only use the target direction for bridges to ensure they're connected.
1322  * The target_dir is as computed previously according to town layout, so
1323  * it will match it perfectly. */
1324  if (GrowTownWithBridge(t1, tile, target_dir)) return;
1325 
1326  GrowTownWithRoad(t1, tile, rcmd);
1327 }
1328 
1336 static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
1337 {
1338  TileIndex target_tile = tile + TileOffsByDiagDir(dir);
1339  if (!IsValidTile(target_tile)) return false;
1340  if (HasTileWaterGround(target_tile)) return false;
1341 
1342  RoadBits target_rb = GetTownRoadBits(target_tile);
1344  /* Check whether a road connection exists or can be build. */
1345  switch (GetTileType(target_tile)) {
1346  case MP_ROAD:
1347  return target_rb != ROAD_NONE;
1348 
1349  case MP_STATION:
1350  return IsDriveThroughStopTile(target_tile);
1351 
1352  case MP_TUNNELBRIDGE:
1353  return GetTunnelBridgeTransportType(target_tile) == TRANSPORT_ROAD;
1354 
1355  case MP_HOUSE:
1356  case MP_INDUSTRY:
1357  case MP_OBJECT:
1358  return false;
1359 
1360  default:
1361  /* Checked for void and water earlier */
1362  return true;
1363  }
1364  } else {
1365  /* Check whether a road connection already exists,
1366  * and it leads somewhere else. */
1367  RoadBits back_rb = DiagDirToRoadBits(ReverseDiagDir(dir));
1368  return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1369  }
1370 }
1371 
1378 static bool GrowTownAtRoad(Town *t, TileIndex tile)
1379 {
1380  /* Special case.
1381  * @see GrowTownInTile Check the else if
1382  */
1383  DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
1384 
1385  assert(tile < MapSize());
1386 
1387  /* Number of times to search.
1388  * Better roads, 2X2 and 3X3 grid grow quite fast so we give
1389  * them a little handicap. */
1390  switch (t->layout) {
1391  case TL_BETTER_ROADS:
1392  _grow_town_result = 10 + t->cache.num_houses * 2 / 9;
1393  break;
1394 
1395  case TL_3X3_GRID:
1396  case TL_2X2_GRID:
1397  _grow_town_result = 10 + t->cache.num_houses * 1 / 9;
1398  break;
1399 
1400  default:
1401  _grow_town_result = 10 + t->cache.num_houses * 4 / 9;
1402  break;
1403  }
1404 
1405  do {
1406  RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
1407 
1408  /* Try to grow the town from this point */
1409  GrowTownInTile(&tile, cur_rb, target_dir, t);
1410  if (_grow_town_result == GROWTH_SUCCEED) return true;
1411 
1412  /* Exclude the source position from the bitmask
1413  * and return if no more road blocks available */
1414  if (IsValidDiagDirection(target_dir)) cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
1415  if (cur_rb == ROAD_NONE) return false;
1416 
1417  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1418  /* Only build in the direction away from the tunnel or bridge. */
1419  target_dir = ReverseDiagDir(GetTunnelBridgeDirection(tile));
1420  } else {
1421  /* Select a random bit from the blockmask, walk a step
1422  * and continue the search from there. */
1423  do {
1424  if (cur_rb == ROAD_NONE) return false;
1425  RoadBits target_bits;
1426  do {
1427  target_dir = RandomDiagDir();
1428  target_bits = DiagDirToRoadBits(target_dir);
1429  } while (!(cur_rb & target_bits));
1430  cur_rb &= ~target_bits;
1431  } while (!CanFollowRoad(tile, target_dir));
1432  }
1433  tile = TileAddByDiagDir(tile, target_dir);
1434 
1435  if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
1436  /* Don't allow building over roads of other cities */
1437  if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && Town::GetByTile(tile) != t) {
1438  return false;
1439  } else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
1440  /* If we are in the SE, and this road-piece has no town owner yet, it just found an
1441  * owner :) (happy happy happy road now) */
1443  SetTownIndex(tile, t->index);
1444  }
1445  }
1446 
1447  /* Max number of times is checked. */
1448  } while (--_grow_town_result >= 0);
1449 
1450  return false;
1451 }
1452 
1461 {
1462  uint32 r = Random();
1463  uint a = GB(r, 0, 2);
1464  uint b = GB(r, 8, 2);
1465  if (a == b) b ^= 2;
1466  return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
1467 }
1468 
1474 static bool GrowTown(Town *t)
1475 {
1476  static const TileIndexDiffC _town_coord_mod[] = {
1477  {-1, 0},
1478  { 1, 1},
1479  { 1, -1},
1480  {-1, -1},
1481  {-1, 0},
1482  { 0, 2},
1483  { 2, 0},
1484  { 0, -2},
1485  {-1, -1},
1486  {-2, 2},
1487  { 2, 2},
1488  { 2, -2},
1489  { 0, 0}
1490  };
1491 
1492  /* Current "company" is a town */
1493  Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1494 
1495  TileIndex tile = t->xy; // The tile we are working with ATM
1496 
1497  /* Find a road that we can base the construction on. */
1498  const TileIndexDiffC *ptr;
1499  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1500  if (GetTownRoadBits(tile) != ROAD_NONE) {
1501  bool success = GrowTownAtRoad(t, tile);
1502  cur_company.Restore();
1503  return success;
1504  }
1505  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1506  }
1507 
1508  /* No road available, try to build a random road block by
1509  * clearing some land and then building a road there. */
1511  tile = t->xy;
1512  for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
1513  /* Only work with plain land that not already has a house */
1514  if (!IsTileType(tile, MP_HOUSE) && IsTileFlat(tile)) {
1515  if (DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded()) {
1517  cur_company.Restore();
1518  return true;
1519  }
1520  }
1521  tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
1522  }
1523  }
1524 
1525  cur_company.Restore();
1526  return false;
1527 }
1528 
1529 void UpdateTownRadius(Town *t)
1530 {
1531  static const uint32 _town_squared_town_zone_radius_data[23][5] = {
1532  { 4, 0, 0, 0, 0}, // 0
1533  { 16, 0, 0, 0, 0},
1534  { 25, 0, 0, 0, 0},
1535  { 36, 0, 0, 0, 0},
1536  { 49, 0, 4, 0, 0},
1537  { 64, 0, 4, 0, 0}, // 20
1538  { 64, 0, 9, 0, 1},
1539  { 64, 0, 9, 0, 4},
1540  { 64, 0, 16, 0, 4},
1541  { 81, 0, 16, 0, 4},
1542  { 81, 0, 16, 0, 4}, // 40
1543  { 81, 0, 25, 0, 9},
1544  { 81, 36, 25, 0, 9},
1545  { 81, 36, 25, 16, 9},
1546  { 81, 49, 0, 25, 9},
1547  { 81, 64, 0, 25, 9}, // 60
1548  { 81, 64, 0, 36, 9},
1549  { 81, 64, 0, 36, 16},
1550  {100, 81, 0, 49, 16},
1551  {100, 81, 0, 49, 25},
1552  {121, 81, 0, 49, 25}, // 80
1553  {121, 81, 0, 49, 25},
1554  {121, 81, 0, 49, 36}, // 88
1555  };
1556 
1557  if (t->cache.num_houses < 92) {
1558  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));
1559  } else {
1560  int mass = t->cache.num_houses / 8;
1561  /* Actually we are proportional to sqrt() but that's right because we are covering an area.
1562  * The offsets are to make sure the radii do not decrease in size when going from the table
1563  * to the calculated value.*/
1564  t->cache.squared_town_zone_radius[0] = mass * 15 - 40;
1565  t->cache.squared_town_zone_radius[1] = mass * 9 - 15;
1566  t->cache.squared_town_zone_radius[2] = 0;
1567  t->cache.squared_town_zone_radius[3] = mass * 5 - 5;
1568  t->cache.squared_town_zone_radius[4] = mass * 3 + 5;
1569  }
1570 }
1571 
1572 void UpdateTownMaxPass(Town *t)
1573 {
1574  t->supplied[CT_PASSENGERS].old_max = t->cache.population >> 3;
1575  t->supplied[CT_MAIL].old_max = t->cache.population >> 4;
1576 }
1577 
1578 static void UpdateTownGrowthRate(Town *t);
1579 static void UpdateTownGrowth(Town *t);
1580 
1592 static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
1593 {
1594  t->xy = tile;
1595  t->cache.num_houses = 0;
1596  t->time_until_rebuild = 10;
1597  UpdateTownRadius(t);
1598  t->flags = 0;
1599  t->cache.population = 0;
1600  /* Spread growth across ticks so even if there are many
1601  * similar towns they're unlikely to grow all in one tick */
1603  t->growth_rate = TownTicksToGameTicks(250);
1604 
1605  /* Set the default cargo requirement for town growth */
1607  case LT_ARCTIC:
1609  break;
1610 
1611  case LT_TROPIC:
1614  break;
1615  }
1616 
1617  t->fund_buildings_months = 0;
1618 
1619  for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1620 
1621  t->have_ratings = 0;
1623  t->exclusive_counter = 0;
1624  t->statues = 0;
1625 
1626  extern int _nb_orig_names;
1628  /* Original town name */
1629  t->townnamegrfid = 0;
1630  t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
1631  } else {
1632  /* Newgrf town name */
1633  t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
1634  t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
1635  }
1636  t->townnameparts = townnameparts;
1637 
1638  t->UpdateVirtCoord();
1640 
1641  t->InitializeLayout(layout);
1642 
1643  t->larger_town = city;
1644 
1645  int x = (int)size * 16 + 3;
1646  if (size == TSZ_RANDOM) x = (Random() & 0xF) + 8;
1647  /* Don't create huge cities when founding town in-game */
1648  if (city && (!manual || _game_mode == GM_EDITOR)) x *= _settings_game.economy.initial_city_size;
1649 
1650  t->cache.num_houses += x;
1651  UpdateTownRadius(t);
1652 
1653  int i = x * 4;
1654  do {
1655  GrowTown(t);
1656  } while (--i);
1657 
1658  t->cache.num_houses -= x;
1659  UpdateTownRadius(t);
1661  UpdateTownMaxPass(t);
1663 }
1664 
1671 {
1672  /* Check if too close to the edge of map */
1673  if (DistanceFromEdge(tile) < 12) {
1674  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP_SUB);
1675  }
1676 
1677  /* Check distance to all other towns. */
1678  if (IsCloseToTown(tile, 20)) {
1679  return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
1680  }
1681 
1682  /* Can only build on clear flat areas, possibly with trees. */
1683  if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || !IsTileFlat(tile)) {
1684  return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
1685  }
1686 
1687  return CommandCost(EXPENSES_OTHER);
1688 }
1689 
1695 static bool IsUniqueTownName(const char *name)
1696 {
1697  const Town *t;
1698 
1699  FOR_ALL_TOWNS(t) {
1700  if (t->name != NULL && strcmp(t->name, name) == 0) return false;
1701  }
1702 
1703  return true;
1704 }
1705 
1718 CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1719 {
1720  TownSize size = Extract<TownSize, 0, 2>(p1);
1721  bool city = HasBit(p1, 2);
1722  TownLayout layout = Extract<TownLayout, 3, 3>(p1);
1724  bool random = HasBit(p1, 6);
1725  uint32 townnameparts = p2;
1726 
1727  if (size >= TSZ_END) return CMD_ERROR;
1728  if (layout >= NUM_TLS) return CMD_ERROR;
1729 
1730  /* Some things are allowed only in the scenario editor and for game scripts. */
1731  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) {
1733  if (size == TSZ_LARGE) return CMD_ERROR;
1734  if (random) return CMD_ERROR;
1736  return CMD_ERROR;
1737  }
1738  } else if (_current_company == OWNER_DEITY && random) {
1739  /* Random parameter is not allowed for Game Scripts. */
1740  return CMD_ERROR;
1741  }
1742 
1743  if (StrEmpty(text)) {
1744  /* If supplied name is empty, townnameparts has to generate unique automatic name */
1745  if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1746  } else {
1747  /* If name is not empty, it has to be unique custom name */
1749  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1750  }
1751 
1752  /* Allocate town struct */
1753  if (!Town::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_TOWNS);
1754 
1755  if (!random) {
1756  CommandCost ret = TownCanBePlacedHere(tile);
1757  if (ret.Failed()) return ret;
1758  }
1759 
1760  static const byte price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
1761  /* multidimensional arrays have to have defined length of non-first dimension */
1762  assert_compile(lengthof(price_mult[0]) == 4);
1763 
1764  CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
1765  byte mult = price_mult[city][size];
1766 
1767  cost.MultiplyCost(mult);
1768 
1769  /* Create the town */
1770  if (flags & DC_EXEC) {
1771  if (cost.GetCost() > GetAvailableMoneyForCommand()) {
1772  _additional_cash_required = cost.GetCost();
1773  return CommandCost(EXPENSES_OTHER);
1774  }
1775 
1776  Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
1778  Town *t;
1779  if (random) {
1780  t = CreateRandomTown(20, townnameparts, size, city, layout);
1781  if (t == NULL) {
1782  cost = CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN);
1783  } else {
1784  _new_town_id = t->index;
1785  }
1786  } else {
1787  t = new Town(tile);
1788  DoCreateTown(t, tile, townnameparts, size, city, layout, true);
1789  }
1791  old_generating_world.Restore();
1792 
1793  if (t != NULL && !StrEmpty(text)) {
1794  t->name = stredup(text);
1795  t->UpdateVirtCoord();
1796  }
1797 
1798  if (_game_mode != GM_EDITOR) {
1799  /* 't' can't be NULL since 'random' is false outside scenedit */
1800  assert(!random);
1801 
1802  if (_current_company == OWNER_DEITY) {
1803  SetDParam(0, t->index);
1804  AddTileNewsItem(STR_NEWS_NEW_TOWN_UNSPONSORED, NT_INDUSTRY_OPEN, tile);
1805  } else {
1806  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
1808  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1809 
1810  char *cn = stredup(company_name);
1811  SetDParamStr(0, cn);
1812  SetDParam(1, t->index);
1813 
1814  AddTileNewsItem(STR_NEWS_NEW_TOWN, NT_INDUSTRY_OPEN, tile, cn);
1815  }
1816  AI::BroadcastNewEvent(new ScriptEventTownFounded(t->index));
1817  Game::NewEvent(new ScriptEventTownFounded(t->index));
1818  }
1819  }
1820  return cost;
1821 }
1822 
1833 {
1834  switch (layout) {
1835  case TL_2X2_GRID: return TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
1836  case TL_3X3_GRID: return TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
1837  default: return tile;
1838  }
1839 }
1840 
1851 {
1852  switch (layout) {
1853  case TL_2X2_GRID: return TileX(tile) % 3 == 0 && TileY(tile) % 3 == 0;
1854  case TL_3X3_GRID: return TileX(tile) % 4 == 0 && TileY(tile) % 4 == 0;
1855  default: return true;
1856  }
1857 }
1858 
1862 struct SpotData {
1864  uint max_dist;
1866 };
1867 
1884 static bool FindFurthestFromWater(TileIndex tile, void *user_data)
1885 {
1886  SpotData *sp = (SpotData*)user_data;
1887  uint dist = GetClosestWaterDistance(tile, true);
1888 
1889  if (IsTileType(tile, MP_CLEAR) &&
1890  IsTileFlat(tile) &&
1891  IsTileAlignedToGrid(tile, sp->layout) &&
1892  dist > sp->max_dist) {
1893  sp->tile = tile;
1894  sp->max_dist = dist;
1895  }
1896 
1897  return false;
1898 }
1899 
1906 static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
1907 {
1908  return IsTileType(tile, MP_CLEAR);
1909 }
1910 
1924 {
1925  SpotData sp = { INVALID_TILE, 0, layout };
1926 
1927  TileIndex coast = tile;
1928  if (CircularTileSearch(&coast, 40, FindNearestEmptyLand, NULL)) {
1929  CircularTileSearch(&coast, 10, FindFurthestFromWater, &sp);
1930  return sp.tile;
1931  }
1932 
1933  /* if we get here just give up */
1934  return INVALID_TILE;
1935 }
1936 
1937 static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
1938 {
1939  assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN
1940 
1941  if (!Town::CanAllocateItem()) return NULL;
1942 
1943  do {
1944  /* Generate a tile index not too close from the edge */
1945  TileIndex tile = AlignTileToGrid(RandomTile(), layout);
1946 
1947  /* if we tried to place the town on water, slide it over onto
1948  * the nearest likely-looking spot */
1949  if (IsTileType(tile, MP_WATER)) {
1950  tile = FindNearestGoodCoastalTownSpot(tile, layout);
1951  if (tile == INVALID_TILE) continue;
1952  }
1953 
1954  /* Make sure town can be placed here */
1955  if (TownCanBePlacedHere(tile).Failed()) continue;
1956 
1957  /* Allocate a town struct */
1958  Town *t = new Town(tile);
1959 
1960  DoCreateTown(t, tile, townnameparts, size, city, layout, false);
1961 
1962  /* if the population is still 0 at the point, then the
1963  * placement is so bad it couldn't grow at all */
1964  if (t->cache.population > 0) return t;
1965 
1966  Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
1968  cur_company.Restore();
1969  assert(rc.Succeeded());
1970 
1971  /* We already know that we can allocate a single town when
1972  * entering this function. However, we create and delete
1973  * a town which "resets" the allocation checks. As such we
1974  * need to check again when assertions are enabled. */
1975  assert(Town::CanAllocateItem());
1976  } while (--attempts != 0);
1977 
1978  return NULL;
1979 }
1980 
1981 static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
1982 
1991 {
1992  uint current_number = 0;
1993  uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
1994  uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
1995  total = min(TownPool::MAX_SIZE, total);
1996  uint32 townnameparts;
1997  TownNames town_names;
1998 
2000 
2001  /* First attempt will be made at creating the suggested number of towns.
2002  * Note that this is really a suggested value, not a required one.
2003  * We would not like the system to lock up just because the user wanted 100 cities on a 64*64 map, would we? */
2004  do {
2007  /* Get a unique name for the town. */
2008  if (!GenerateTownName(&townnameparts, &town_names)) continue;
2009  /* try 20 times to create a random-sized town for the first loop. */
2010  if (CreateRandomTown(20, townnameparts, TSZ_RANDOM, city, layout) != NULL) current_number++; // If creation was successful, raise a flag.
2011  } while (--total);
2012 
2013  town_names.clear();
2014 
2015  if (current_number != 0) return true;
2016 
2017  /* If current_number is still zero at this point, it means that not a single town has been created.
2018  * So give it a last try, but now more aggressive */
2019  if (GenerateTownName(&townnameparts) &&
2020  CreateRandomTown(10000, townnameparts, TSZ_RANDOM, _settings_game.economy.larger_towns != 0, layout) != NULL) {
2021  return true;
2022  }
2023 
2024  /* If there are no towns at all and we are generating new game, bail out */
2025  if (Town::GetNumItems() == 0 && _game_mode != GM_EDITOR) {
2026  ShowErrorMessage(STR_ERROR_COULD_NOT_CREATE_TOWN, INVALID_STRING_ID, WL_CRITICAL);
2027  }
2028 
2029  return false; // we are still without a town? we failed, simply
2030 }
2031 
2032 
2039 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
2040 {
2041  uint dist = DistanceSquare(tile, t->xy);
2042 
2043  if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
2044 
2045  HouseZonesBits smallest = HZB_TOWN_EDGE;
2046  for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2047  if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2048  }
2049 
2050  return smallest;
2051 }
2052 
2063 static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
2064 {
2066 
2067  assert(cc.Succeeded());
2068 
2069  IncreaseBuildingCount(t, type);
2070  MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
2071  if (HouseSpec::Get(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
2072 
2073  MarkTileDirtyByTile(tile);
2074 }
2075 
2076 
2087 static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
2088 {
2089  BuildingFlags size = HouseSpec::Get(type)->building_flags;
2090 
2091  ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
2092  if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
2093  if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
2094  if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
2095 }
2096 
2097 
2105 static inline bool CanBuildHouseHere(TileIndex tile, bool noslope)
2106 {
2107  /* cannot build on these slopes... */
2108  Slope slope = GetTileSlope(tile);
2109  if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
2110 
2111  /* building under a bridge? */
2112  if (IsBridgeAbove(tile)) return false;
2113 
2114  /* can we clear the land? */
2115  return DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR).Succeeded();
2116 }
2117 
2118 
2127 static inline bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
2128 {
2129  if (!CanBuildHouseHere(tile, noslope)) return false;
2130 
2131  /* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
2132  if (GetTileMaxZ(tile) != z) return false;
2133 
2134  return true;
2135 }
2136 
2137 
2146 static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
2147 {
2148  /* we need to check this tile too because we can be at different tile now */
2149  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2150 
2151  for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
2152  tile += TileOffsByDiagDir(d);
2153  if (!CheckBuildHouseSameZ(tile, z, noslope)) return false;
2154  }
2155 
2156  return true;
2157 }
2158 
2159 
2167 static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
2168 {
2169  /* Allow towns everywhere when we don't build roads */
2171 
2172  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2173 
2174  switch (t->layout) {
2175  case TL_2X2_GRID:
2176  if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
2177  break;
2178 
2179  case TL_3X3_GRID:
2180  if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
2181  break;
2182 
2183  default:
2184  break;
2185  }
2186 
2187  return true;
2188 }
2189 
2190 
2198 static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
2199 {
2200  /* Allow towns everywhere when we don't build roads */
2202 
2203  /* Compute relative position of tile. (Positive offsets are towards north) */
2204  TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
2205 
2206  switch (t->layout) {
2207  case TL_2X2_GRID:
2208  grid_pos.x %= 3;
2209  grid_pos.y %= 3;
2210  if ((grid_pos.x != 2 && grid_pos.x != -1) ||
2211  (grid_pos.y != 2 && grid_pos.y != -1)) return false;
2212  break;
2213 
2214  case TL_3X3_GRID:
2215  if ((grid_pos.x & 3) < 2 || (grid_pos.y & 3) < 2) return false;
2216  break;
2217 
2218  default:
2219  break;
2220  }
2221 
2222  return true;
2223 }
2224 
2225 
2235 static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
2236 {
2237  /* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
2238 
2239  TileIndex tile2 = *tile + TileOffsByDiagDir(second);
2240  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) return true;
2241 
2242  tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
2243  if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, maxz, noslope)) {
2244  *tile = tile2;
2245  return true;
2246  }
2247 
2248  return false;
2249 }
2250 
2251 
2260 static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
2261 {
2262  TileIndex tile2 = *tile;
2263 
2264  for (DiagDirection d = DIAGDIR_SE;; d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
2265  if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, maxz, noslope)) {
2266  *tile = tile2;
2267  return true;
2268  }
2269  if (d == DIAGDIR_END) break;
2270  tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
2271  }
2272 
2273  return false;
2274 }
2275 
2276 
2283 static bool BuildTownHouse(Town *t, TileIndex tile)
2284 {
2285  /* forbidden building here by town layout */
2286  if (!TownLayoutAllowsHouseHere(t, tile)) return false;
2287 
2288  /* no house allowed at all, bail out */
2289  if (!CanBuildHouseHere(tile, false)) return false;
2290 
2291  Slope slope = GetTileSlope(tile);
2292  int maxz = GetTileMaxZ(tile);
2293 
2294  /* Get the town zone type of the current tile, as well as the climate.
2295  * This will allow to easily compare with the specs of the new house to build */
2296  HouseZonesBits rad = GetTownRadiusGroup(t, tile);
2297 
2298  /* Above snow? */
2300  if (land == LT_ARCTIC && maxz > HighestSnowLine()) land = -1;
2301 
2302  uint bitmask = (1 << rad) + (1 << (land + 12));
2303 
2304  /* bits 0-4 are used
2305  * bits 11-15 are used
2306  * bits 5-10 are not used. */
2307  HouseID houses[NUM_HOUSES];
2308  uint num = 0;
2309  uint probs[NUM_HOUSES];
2310  uint probability_max = 0;
2311 
2312  /* Generate a list of all possible houses that can be built. */
2313  for (uint i = 0; i < NUM_HOUSES; i++) {
2314  const HouseSpec *hs = HouseSpec::Get(i);
2315 
2316  /* Verify that the candidate house spec matches the current tile status */
2317  if ((~hs->building_availability & bitmask) != 0 || !hs->enabled || hs->grf_prop.override != INVALID_HOUSE_ID) continue;
2318 
2319  /* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
2320  if (hs->class_id != HOUSE_NO_CLASS) {
2321  /* id_count is always <= class_count, so it doesn't need to be checked */
2322  if (t->cache.building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
2323  } else {
2324  /* If the house has no class, check id_count instead */
2325  if (t->cache.building_counts.id_count[i] == UINT16_MAX) continue;
2326  }
2327 
2328  /* Without NewHouses, all houses have probability '1' */
2329  uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
2330  probability_max += cur_prob;
2331  probs[num] = cur_prob;
2332  houses[num++] = (HouseID)i;
2333  }
2334 
2335  TileIndex baseTile = tile;
2336 
2337  while (probability_max > 0) {
2338  /* Building a multitile building can change the location of tile.
2339  * The building would still be built partially on that tile, but
2340  * its northern tile would be elsewhere. However, if the callback
2341  * fails we would be basing further work from the changed tile.
2342  * So a next 1x1 tile building could be built on the wrong tile. */
2343  tile = baseTile;
2344 
2345  uint r = RandomRange(probability_max);
2346  uint i;
2347  for (i = 0; i < num; i++) {
2348  if (probs[i] > r) break;
2349  r -= probs[i];
2350  }
2351 
2352  HouseID house = houses[i];
2353  probability_max -= probs[i];
2354 
2355  /* remove tested house from the set */
2356  num--;
2357  houses[i] = houses[num];
2358  probs[i] = probs[num];
2359 
2360  const HouseSpec *hs = HouseSpec::Get(house);
2361 
2363  _game_mode != GM_EDITOR && (hs->extra_flags & BUILDING_IS_HISTORICAL) != 0) {
2364  continue;
2365  }
2366 
2367  if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
2368 
2369  /* Special houses that there can be only one of. */
2370  uint oneof = 0;
2371 
2372  if (hs->building_flags & BUILDING_IS_CHURCH) {
2373  SetBit(oneof, TOWN_HAS_CHURCH);
2374  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2375  SetBit(oneof, TOWN_HAS_STADIUM);
2376  }
2377 
2378  if (t->flags & oneof) continue;
2379 
2380  /* Make sure there is no slope? */
2381  bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
2382  if (noslope && slope != SLOPE_FLAT) continue;
2383 
2384  if (hs->building_flags & TILE_SIZE_2x2) {
2385  if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
2386  } else if (hs->building_flags & TILE_SIZE_2x1) {
2387  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
2388  } else if (hs->building_flags & TILE_SIZE_1x2) {
2389  if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
2390  } else {
2391  /* 1x1 house checks are already done */
2392  }
2393 
2394  byte random_bits = Random();
2395 
2397  uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile, true, random_bits);
2398  if (callback_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_ALLOW_CONSTRUCTION, callback_res)) continue;
2399  }
2400 
2401  /* build the house */
2402  t->cache.num_houses++;
2403 
2404  /* Special houses that there can be only one of. */
2405  t->flags |= oneof;
2406 
2407  byte construction_counter = 0;
2408  byte construction_stage = 0;
2409 
2410  if (_generating_world || _game_mode == GM_EDITOR) {
2411  uint32 r = Random();
2412 
2413  construction_stage = TOWN_HOUSE_COMPLETED;
2414  if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
2415 
2416  if (construction_stage == TOWN_HOUSE_COMPLETED) {
2417  ChangePopulation(t, hs->population);
2418  } else {
2419  construction_counter = GB(r, 2, 2);
2420  }
2421  }
2422 
2423  MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2424  UpdateTownRadius(t);
2426  UpdateTownCargoes(t, tile);
2427 
2428  return true;
2429  }
2430 
2431  return false;
2432 }
2433 
2440 static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
2441 {
2442  assert(IsTileType(tile, MP_HOUSE));
2443  DecreaseBuildingCount(t, house);
2444  DoClearSquare(tile);
2445  DeleteAnimatedTile(tile);
2446 
2447  DeleteNewGRFInspectWindow(GSF_HOUSES, tile);
2448 }
2449 
2458 {
2459  if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
2460  if (HouseSpec::Get(house - 1)->building_flags & TILE_SIZE_2x1) {
2461  house--;
2462  return TileDiffXY(-1, 0);
2463  } else if (HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2464  house--;
2465  return TileDiffXY(0, -1);
2466  } else if (HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2467  house -= 2;
2468  return TileDiffXY(-1, 0);
2469  } else if (HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2470  house -= 3;
2471  return TileDiffXY(-1, -1);
2472  }
2473  }
2474  return 0;
2475 }
2476 
2477 void ClearTownHouse(Town *t, TileIndex tile)
2478 {
2479  assert(IsTileType(tile, MP_HOUSE));
2480 
2481  HouseID house = GetHouseType(tile);
2482 
2483  /* need to align the tile to point to the upper left corner of the house */
2484  tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
2485 
2486  const HouseSpec *hs = HouseSpec::Get(house);
2487 
2488  /* Remove population from the town if the house is finished. */
2489  if (IsHouseCompleted(tile)) {
2490  ChangePopulation(t, -hs->population);
2491  }
2492 
2493  t->cache.num_houses--;
2494 
2495  /* Clear flags for houses that only may exist once/town. */
2496  if (hs->building_flags & BUILDING_IS_CHURCH) {
2498  } else if (hs->building_flags & BUILDING_IS_STADIUM) {
2500  }
2501 
2502  /* Do the actual clearing of tiles */
2503  uint eflags = hs->building_flags;
2504  DoClearTownHouseHelper(tile, t, house);
2505  if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
2506  if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
2507  if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
2508 
2509  UpdateTownRadius(t);
2510 
2511  /* Update cargo acceptance. */
2512  UpdateTownCargoes(t, tile);
2513 }
2514 
2524 CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2525 {
2526  Town *t = Town::GetIfValid(p1);
2527  if (t == NULL) return CMD_ERROR;
2528 
2529  bool reset = StrEmpty(text);
2530 
2531  if (!reset) {
2533  if (!IsUniqueTownName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
2534  }
2535 
2536  if (flags & DC_EXEC) {
2537  free(t->name);
2538  t->name = reset ? NULL : stredup(text);
2539 
2540  t->UpdateVirtCoord();
2543  }
2544  return CommandCost();
2545 }
2546 
2553 {
2554  const CargoSpec *cs;
2555  FOR_ALL_CARGOSPECS(cs) {
2556  if (cs->town_effect == effect) return cs;
2557  }
2558  return NULL;
2559 }
2560 
2572 CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2573 {
2574  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2575 
2576  TownEffect te = (TownEffect)GB(p1, 16, 8);
2577  if (te < TE_BEGIN || te >= TE_END) return CMD_ERROR;
2578 
2579  uint16 index = GB(p1, 0, 16);
2580  Town *t = Town::GetIfValid(index);
2581  if (t == NULL) return CMD_ERROR;
2582 
2583  /* Validate if there is a cargo which is the requested TownEffect */
2584  const CargoSpec *cargo = FindFirstCargoWithTownEffect(te);
2585  if (cargo == NULL) return CMD_ERROR;
2586 
2587  if (flags & DC_EXEC) {
2588  t->goal[te] = p2;
2589  UpdateTownGrowth(t);
2591  }
2592 
2593  return CommandCost();
2594 }
2595 
2605 CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2606 {
2607  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2608  Town *t = Town::GetIfValid(p1);
2609  if (t == NULL) return CMD_ERROR;
2610 
2611  if (flags & DC_EXEC) {
2612  free(t->text);
2613  t->text = StrEmpty(text) ? NULL : stredup(text);
2615  }
2616 
2617  return CommandCost();
2618 }
2619 
2629 CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2630 {
2631  if (_current_company != OWNER_DEITY) return CMD_ERROR;
2632  if (GB(p2, 16, 16) != 0) return CMD_ERROR;
2633 
2634  Town *t = Town::GetIfValid(p1);
2635  if (t == NULL) return CMD_ERROR;
2636 
2637  if (flags & DC_EXEC) {
2638  if (p2 == 0) {
2639  /* Just clear the flag, UpdateTownGrowth will determine a proper growth rate */
2641  } else {
2642  uint old_rate = t->growth_rate;
2643  if (t->grow_counter >= old_rate) {
2644  /* This also catches old_rate == 0 */
2645  t->grow_counter = p2;
2646  } else {
2647  /* Scale grow_counter, so half finished houses stay half finished */
2648  t->grow_counter = t->grow_counter * p2 / old_rate;
2649  }
2650  t->growth_rate = p2;
2652  }
2653  UpdateTownGrowth(t);
2655  }
2656 
2657  return CommandCost();
2658 }
2659 
2669 CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2670 {
2671  if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR;
2672  Town *t = Town::GetIfValid(p1);
2673  if (t == NULL) return CMD_ERROR;
2674 
2675  if (flags & DC_EXEC) {
2676  /* The more houses, the faster we grow */
2677  if (p2 == 0) {
2678  uint amount = RandomRange(ClampToU16(t->cache.num_houses / 10)) + 3;
2679  t->cache.num_houses += amount;
2680  UpdateTownRadius(t);
2681 
2682  uint n = amount * 10;
2683  do GrowTown(t); while (--n);
2684 
2685  t->cache.num_houses -= amount;
2686  } else {
2687  for (; p2 > 0; p2--) {
2688  /* Try several times to grow, as we are really suppose to grow */
2689  for (uint i = 0; i < 25; i++) if (GrowTown(t)) break;
2690  }
2691  }
2692  UpdateTownRadius(t);
2693 
2694  UpdateTownMaxPass(t);
2695  }
2696 
2697  return CommandCost();
2698 }
2699 
2709 CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2710 {
2711  if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR;
2712  Town *t = Town::GetIfValid(p1);
2713  if (t == NULL) return CMD_ERROR;
2714 
2715  /* Stations refer to towns. */
2716  const Station *st;
2717  FOR_ALL_STATIONS(st) {
2718  if (st->town == t) {
2719  /* Non-oil rig stations are always a problem. */
2720  if (!(st->facilities & FACIL_AIRPORT) || st->airport.type != AT_OILRIG) return CMD_ERROR;
2721  /* We can only automatically delete oil rigs *if* there's no vehicle on them. */
2722  CommandCost ret = DoCommand(st->airport.tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2723  if (ret.Failed()) return ret;
2724  }
2725  }
2726 
2727  /* Depots refer to towns. */
2728  const Depot *d;
2729  FOR_ALL_DEPOTS(d) {
2730  if (d->town == t) return CMD_ERROR;
2731  }
2732 
2733  /* Check all tiles for town ownership. */
2734  for (TileIndex tile = 0; tile < MapSize(); ++tile) {
2735  bool try_clear = false;
2736  switch (GetTileType(tile)) {
2737  case MP_ROAD:
2738  try_clear = HasTownOwnedRoad(tile) && GetTownIndex(tile) == t->index;
2739  break;
2740 
2741  case MP_TUNNELBRIDGE:
2742  try_clear = IsTileOwner(tile, OWNER_TOWN) && ClosestTownFromTile(tile, UINT_MAX) == t;
2743  break;
2744 
2745  case MP_HOUSE:
2746  try_clear = GetTownIndex(tile) == t->index;
2747  break;
2748 
2749  case MP_INDUSTRY:
2750  try_clear = Industry::GetByTile(tile)->town == t;
2751  break;
2752 
2753  case MP_OBJECT:
2754  if (Town::GetNumItems() == 1) {
2755  /* No towns will be left, remove it! */
2756  try_clear = true;
2757  } else {
2758  Object *o = Object::GetByTile(tile);
2759  if (o->town == t) {
2760  if (o->type == OBJECT_STATUE) {
2761  /* Statue... always remove. */
2762  try_clear = true;
2763  } else {
2764  /* Tell to find a new town. */
2765  if (flags & DC_EXEC) o->town = NULL;
2766  }
2767  }
2768  }
2769  break;
2770 
2771  default:
2772  break;
2773  }
2774  if (try_clear) {
2775  CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2776  if (ret.Failed()) return ret;
2777  }
2778  }
2779 
2780  /* The town destructor will delete the other things related to the town. */
2781  if (flags & DC_EXEC) delete t;
2782 
2783  return CommandCost();
2784 }
2785 
2791  2, 4, 9, 35, 48, 53, 117, 175
2792 };
2793 
2794 static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
2795 {
2796  if (flags & DC_EXEC) {
2797  ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
2798  }
2799  return CommandCost();
2800 }
2801 
2802 static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
2803 {
2804  if (flags & DC_EXEC) {
2805  ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
2806  }
2807  return CommandCost();
2808 }
2809 
2810 static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
2811 {
2812  if (flags & DC_EXEC) {
2813  ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
2814  }
2815  return CommandCost();
2816 }
2817 
2818 static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
2819 {
2820  /* Check if the company is allowed to fund new roads. */
2822 
2823  if (flags & DC_EXEC) {
2824  t->road_build_months = 6;
2825 
2826  char company_name[MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH];
2828  GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
2829 
2830  char *cn = stredup(company_name);
2831  SetDParam(0, t->index);
2832  SetDParamStr(1, cn);
2833 
2834  AddNewsItem(STR_NEWS_ROAD_REBUILDING, NT_GENERAL, NF_NORMAL, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cn);
2835  AI::BroadcastNewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2836  Game::NewEvent(new ScriptEventRoadReconstruction((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2837  }
2838  return CommandCost();
2839 }
2840 
2846 static bool TryClearTile(TileIndex tile)
2847 {
2848  Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2850  cur_company.Restore();
2851  return r.Succeeded();
2852 }
2853 
2858 
2859  StatueBuildSearchData(TileIndex best_pos, int count) : best_position(best_pos), tile_count(count) { }
2860 };
2861 
2868 static bool SearchTileForStatue(TileIndex tile, void *user_data)
2869 {
2870  static const int STATUE_NUMBER_INNER_TILES = 25; // Number of tiles int the center of the city, where we try to protect houses.
2871 
2872  StatueBuildSearchData *statue_data = (StatueBuildSearchData *)user_data;
2873  statue_data->tile_count++;
2874 
2875  /* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
2876  if (IsSteepSlope(GetTileSlope(tile))) return false;
2877  /* Don't build statues under bridges. */
2878  if (IsBridgeAbove(tile)) return false;
2879 
2880  /* A clear-able open space is always preferred. */
2881  if ((IsTileType(tile, MP_CLEAR) || IsTileType(tile, MP_TREES)) && TryClearTile(tile)) {
2882  statue_data->best_position = tile;
2883  return true;
2884  }
2885 
2886  bool house = IsTileType(tile, MP_HOUSE);
2887 
2888  /* Searching inside the inner circle. */
2889  if (statue_data->tile_count <= STATUE_NUMBER_INNER_TILES) {
2890  /* Save first house in inner circle. */
2891  if (house && statue_data->best_position == INVALID_TILE && TryClearTile(tile)) {
2892  statue_data->best_position = tile;
2893  }
2894 
2895  /* If we have reached the end of the inner circle, and have a saved house, terminate the search. */
2896  return statue_data->tile_count == STATUE_NUMBER_INNER_TILES && statue_data->best_position != INVALID_TILE;
2897  }
2898 
2899  /* Searching outside the circle, just pick the first possible spot. */
2900  statue_data->best_position = tile; // Is optimistic, the condition below must also hold.
2901  return house && TryClearTile(tile);
2902 }
2903 
2912 {
2913  if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
2914 
2915  TileIndex tile = t->xy;
2916  StatueBuildSearchData statue_data(INVALID_TILE, 0);
2917  if (!CircularTileSearch(&tile, 9, SearchTileForStatue, &statue_data)) return_cmd_error(STR_ERROR_STATUE_NO_SUITABLE_PLACE);
2918 
2919  if (flags & DC_EXEC) {
2920  Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
2921  DoCommand(statue_data.best_position, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
2922  cur_company.Restore();
2924  SetBit(t->statues, _current_company); // Once found and built, "inform" the Town.
2925  MarkTileDirtyByTile(statue_data.best_position);
2926  }
2927  return CommandCost();
2928 }
2929 
2930 static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
2931 {
2932  /* Check if it's allowed to buy the rights */
2934 
2935  if (flags & DC_EXEC) {
2936  /* And grow for 3 months */
2937  t->fund_buildings_months = 3;
2938 
2939  /* Enable growth (also checking GameScript's opinion) */
2940  UpdateTownGrowth(t);
2941 
2942  /* Build a new house, but add a small delay to make sure
2943  * that spamming funding doesn't let town grow any faster
2944  * than 1 house per 2 * TOWN_GROWTH_TICKS ticks.
2945  * Also emulate original behaviour when town was only growing in
2946  * TOWN_GROWTH_TICKS intervals, to make sure that it's not too
2947  * tick-perfect and gives player some time window where he can
2948  * spam funding with the exact same efficiency.
2949  */
2951 
2953  }
2954  return CommandCost();
2955 }
2956 
2957 static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
2958 {
2959  /* Check if it's allowed to buy the rights */
2961 
2962  if (flags & DC_EXEC) {
2963  t->exclusive_counter = 12;
2965 
2966  ModifyStationRatingAround(t->xy, _current_company, 130, 17);
2967 
2969 
2970  /* Spawn news message */
2971  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
2973  SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
2974  SetDParam(1, STR_NEWS_EXCLUSIVE_RIGHTS_DESCRIPTION);
2975  SetDParam(2, t->index);
2976  SetDParamStr(3, cni->company_name);
2977  AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_GENERAL, NF_COMPANY, NR_TOWN, t->index, NR_NONE, UINT32_MAX, cni);
2978  AI::BroadcastNewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2979  Game::NewEvent(new ScriptEventExclusiveTransportRights((ScriptCompany::CompanyID)(Owner)_current_company, t->index));
2980  }
2981  return CommandCost();
2982 }
2983 
2984 static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
2985 {
2986  if (flags & DC_EXEC) {
2987  if (Chance16(1, 14)) {
2988  /* set as unwanted for 6 months */
2989  t->unwanted[_current_company] = 6;
2990 
2991  /* set all close by station ratings to 0 */
2992  Station *st;
2993  FOR_ALL_STATIONS(st) {
2994  if (st->town == t && st->owner == _current_company) {
2995  for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
2996  }
2997  }
2998 
2999  /* only show error message to the executing player. All errors are handled command.c
3000  * but this is special, because it can only 'fail' on a DC_EXEC */
3001  if (IsLocalCompany()) ShowErrorMessage(STR_ERROR_BRIBE_FAILED, INVALID_STRING_ID, WL_INFO);
3002 
3003  /* decrease by a lot!
3004  * ChangeTownRating is only for stuff in demolishing. Bribe failure should
3005  * be independent of any cheat settings
3006  */
3007  if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
3008  t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
3010  }
3011  } else {
3012  ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
3013  }
3014  }
3015  return CommandCost();
3016 }
3017 
3018 typedef CommandCost TownActionProc(Town *t, DoCommandFlag flags);
3019 static TownActionProc * const _town_action_proc[] = {
3020  TownActionAdvertiseSmall,
3021  TownActionAdvertiseMedium,
3022  TownActionAdvertiseLarge,
3023  TownActionRoadRebuild,
3025  TownActionFundBuildings,
3026  TownActionBuyRights,
3027  TownActionBribe
3028 };
3029 
3037 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
3038 {
3039  int num = 0;
3040  TownActions buttons = TACT_NONE;
3041 
3042  /* Spectators and unwanted have no options */
3043  if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
3044 
3045  /* Things worth more than this are not shown */
3046  Money avail = Company::Get(cid)->money + _price[PR_STATION_VALUE] * 200;
3047 
3048  /* Check the action bits for validity and
3049  * if they are valid add them */
3050  for (uint i = 0; i != lengthof(_town_action_costs); i++) {
3051  const TownActions cur = (TownActions)(1 << i);
3052 
3053  /* Is the company not able to bribe ? */
3054  if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM)) continue;
3055 
3056  /* Is the company not able to buy exclusive rights ? */
3057  if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights) continue;
3058 
3059  /* Is the company not able to fund buildings ? */
3060  if (cur == TACT_FUND_BUILDINGS && !_settings_game.economy.fund_buildings) continue;
3061 
3062  /* Is the company not able to fund local road reconstruction? */
3063  if (cur == TACT_ROAD_REBUILD && !_settings_game.economy.fund_roads) continue;
3064 
3065  /* Is the company not able to build a statue ? */
3066  if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid)) continue;
3067 
3068  if (avail >= _town_action_costs[i] * _price[PR_TOWN_ACTION] >> 8) {
3069  buttons |= cur;
3070  num++;
3071  }
3072  }
3073  }
3074 
3075  if (nump != NULL) *nump = num;
3076  return buttons;
3077 }
3078 
3090 CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
3091 {
3092  Town *t = Town::GetIfValid(p1);
3093  if (t == NULL || p2 >= lengthof(_town_action_proc)) return CMD_ERROR;
3094 
3095  if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
3096 
3097  CommandCost cost(EXPENSES_OTHER, _price[PR_TOWN_ACTION] * _town_action_costs[p2] >> 8);
3098 
3099  CommandCost ret = _town_action_proc[p2](t, flags);
3100  if (ret.Failed()) return ret;
3101 
3102  if (flags & DC_EXEC) {
3104  }
3105 
3106  return cost;
3107 }
3108 
3109 static void UpdateTownRating(Town *t)
3110 {
3111  /* Increase company ratings if they're low */
3112  const Company *c;
3113  FOR_ALL_COMPANIES(c) {
3114  if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
3116  }
3117  }
3118 
3119  const Station *st;
3120  FOR_ALL_STATIONS(st) {
3121  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3122  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3123  if (Company::IsValidID(st->owner)) {
3124  int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3125  t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
3126  }
3127  } else {
3128  if (Company::IsValidID(st->owner)) {
3129  int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3130  t->ratings[st->owner] = max(new_rating, INT16_MIN);
3131  }
3132  }
3133  }
3134  }
3135 
3136  /* clamp all ratings to valid values */
3137  for (uint i = 0; i < MAX_COMPANIES; i++) {
3138  t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
3139  }
3140 
3142 }
3143 
3144 
3151 static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
3152 {
3153  if (t->growth_rate == TOWN_GROWTH_RATE_NONE) return;
3154  if (prev_growth_rate == TOWN_GROWTH_RATE_NONE) {
3156  return;
3157  }
3158  t->grow_counter = RoundDivSU((uint32)t->grow_counter * (t->growth_rate + 1), prev_growth_rate + 1);
3159 }
3160 
3167 {
3168  int n = 0;
3169  const Station *st;
3170  FOR_ALL_STATIONS(st) {
3171  if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[0]) {
3172  if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3173  n++;
3174  }
3175  }
3176  }
3177  return n;
3178 }
3179 
3186 static uint GetNormalGrowthRate(Town *t)
3187 {
3188  static const uint16 _grow_count_values[2][6] = {
3189  { 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
3190  { 320, 420, 300, 220, 160, 100 } // Normal values
3191  };
3192 
3193  int n = CountActiveStations(t);
3194  uint16 m = _grow_count_values[t->fund_buildings_months != 0 ? 0 : 1][min(n, 5)];
3195 
3196  uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
3197 
3198  m >>= growth_multiplier;
3199  if (t->larger_town) m /= 2;
3200 
3201  return TownTicksToGameTicks(m / (t->cache.num_houses / 50 + 1));
3202 }
3203 
3209 {
3210  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) return;
3211  uint old_rate = t->growth_rate;
3213  UpdateTownGrowCounter(t, old_rate);
3215 }
3216 
3221 static void UpdateTownGrowth(Town *t)
3222 {
3224 
3227 
3228  if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
3229 
3230  if (t->fund_buildings_months == 0) {
3231  /* Check if all goals are reached for this town to grow (given we are not funding it) */
3232  for (int i = TE_BEGIN; i < TE_END; i++) {
3233  switch (t->goal[i]) {
3234  case TOWN_GROWTH_WINTER:
3235  if (TileHeight(t->xy) >= GetSnowLine() && t->received[i].old_act == 0 && t->cache.population > 90) return;
3236  break;
3237  case TOWN_GROWTH_DESERT:
3238  if (GetTropicZone(t->xy) == TROPICZONE_DESERT && t->received[i].old_act == 0 && t->cache.population > 60) return;
3239  break;
3240  default:
3241  if (t->goal[i] > t->received[i].old_act) return;
3242  break;
3243  }
3244  }
3245  }
3246 
3247  if (HasBit(t->flags, TOWN_CUSTOM_GROWTH)) {
3250  return;
3251  }
3252 
3253  if (t->fund_buildings_months == 0 && CountActiveStations(t) == 0 && !Chance16(1, 12)) return;
3254 
3257 }
3258 
3259 static void UpdateTownAmounts(Town *t)
3260 {
3261  for (CargoID i = 0; i < NUM_CARGO; i++) t->supplied[i].NewMonth();
3262  for (int i = TE_BEGIN; i < TE_END; i++) t->received[i].NewMonth();
3263  if (t->fund_buildings_months != 0) t->fund_buildings_months--;
3264 
3266 }
3267 
3268 static void UpdateTownUnwanted(Town *t)
3269 {
3270  const Company *c;
3271 
3272  FOR_ALL_COMPANIES(c) {
3273  if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
3274  }
3275 }
3276 
3284 {
3286 
3288  if (t == NULL) return CommandCost();
3289 
3290  if (t->ratings[_current_company] > RATING_VERYPOOR) return CommandCost();
3291 
3292  SetDParam(0, t->index);
3293  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3294 }
3295 
3305 {
3306  Town *t;
3307  uint best = threshold;
3308  Town *best_town = NULL;
3309 
3310  FOR_ALL_TOWNS(t) {
3311  uint dist = DistanceManhattan(tile, t->xy);
3312  if (dist < best) {
3313  best = dist;
3314  best_town = t;
3315  }
3316  }
3317 
3318  return best_town;
3319 }
3320 
3329 Town *ClosestTownFromTile(TileIndex tile, uint threshold)
3330 {
3331  switch (GetTileType(tile)) {
3332  case MP_ROAD:
3333  if (IsRoadDepot(tile)) return CalcClosestTownFromTile(tile, threshold);
3334 
3335  if (!HasTownOwnedRoad(tile)) {
3336  TownID tid = GetTownIndex(tile);
3337 
3338  if (tid == INVALID_TOWN) {
3339  /* in the case we are generating "many random towns", this value may be INVALID_TOWN */
3340  if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
3341  assert(Town::GetNumItems() == 0);
3342  return NULL;
3343  }
3344 
3345  assert(Town::IsValidID(tid));
3346  Town *town = Town::Get(tid);
3347 
3348  if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
3349 
3350  return town;
3351  }
3352  FALLTHROUGH;
3353 
3354  case MP_HOUSE:
3355  return Town::GetByTile(tile);
3356 
3357  default:
3358  return CalcClosestTownFromTile(tile, threshold);
3359  }
3360 }
3361 
3362 static bool _town_rating_test = false;
3364 
3370 void SetTownRatingTestMode(bool mode)
3371 {
3372  static int ref_count = 0; // Number of times test-mode is switched on.
3373  if (mode) {
3374  if (ref_count == 0) {
3375  _town_test_ratings.Clear();
3376  }
3377  ref_count++;
3378  } else {
3379  assert(ref_count > 0);
3380  ref_count--;
3381  }
3382  _town_rating_test = !(ref_count == 0);
3383 }
3384 
3390 static int GetRating(const Town *t)
3391 {
3392  if (_town_rating_test) {
3393  SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
3394  if (it != _town_test_ratings.End()) {
3395  return it->second;
3396  }
3397  }
3398  return t->ratings[_current_company];
3399 }
3400 
3409 {
3410  /* if magic_bulldozer cheat is active, town doesn't penalize for removing stuff */
3411  if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
3413  (_cheats.magic_bulldozer.value && add < 0)) {
3414  return;
3415  }
3416 
3417  int rating = GetRating(t);
3418  if (add < 0) {
3419  if (rating > max) {
3420  rating += add;
3421  if (rating < max) rating = max;
3422  }
3423  } else {
3424  if (rating < max) {
3425  rating += add;
3426  if (rating > max) rating = max;
3427  }
3428  }
3429  if (_town_rating_test) {
3430  _town_test_ratings[t] = rating;
3431  } else {
3433  t->ratings[_current_company] = rating;
3435  }
3436 }
3437 
3446 {
3447  /* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
3448  if (t == NULL || !Company::IsValidID(_current_company) ||
3450  return CommandCost();
3451  }
3452 
3453  /* minimum rating needed to be allowed to remove stuff */
3454  static const int needed_rating[][TOWN_RATING_CHECK_TYPE_COUNT] = {
3455  /* ROAD_REMOVE, TUNNELBRIDGE_REMOVE */
3459  };
3460 
3461  /* check if you're allowed to remove the road/bridge/tunnel
3462  * owned by a town no removal if rating is lower than ... depends now on
3463  * difficulty setting. Minimum town rating selected by difficulty level
3464  */
3465  int needed = needed_rating[_settings_game.difficulty.town_council_tolerance][type];
3466 
3467  if (GetRating(t) < needed) {
3468  SetDParam(0, t->index);
3469  return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
3470  }
3471 
3472  return CommandCost();
3473 }
3474 
3475 void TownsMonthlyLoop()
3476 {
3477  Town *t;
3478 
3479  FOR_ALL_TOWNS(t) {
3480  if (t->road_build_months != 0) t->road_build_months--;
3481 
3482  if (t->exclusive_counter != 0) {
3483  if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
3484  }
3485 
3486  UpdateTownAmounts(t);
3487  UpdateTownGrowth(t);
3488  UpdateTownRating(t);
3489  UpdateTownUnwanted(t);
3490  UpdateTownCargoes(t);
3491  }
3492 
3494 }
3495 
3496 void TownsYearlyLoop()
3497 {
3498  /* Increment house ages */
3499  for (TileIndex t = 0; t < MapSize(); t++) {
3500  if (!IsTileType(t, MP_HOUSE)) continue;
3501  IncrementHouseAge(t);
3502  }
3503 }
3504 
3505 static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3506 {
3507  if (AutoslopeEnabled()) {
3508  HouseID house = GetHouseType(tile);
3509  GetHouseNorthPart(house); // modifies house to the ID of the north tile
3510  const HouseSpec *hs = HouseSpec::Get(house);
3511 
3512  /* Here we differ from TTDP by checking TILE_NOT_SLOPED */
3513  if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
3514  (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
3515  bool allow_terraform = true;
3516 
3517  /* Call the autosloping callback per tile, not for the whole building at once. */
3518  house = GetHouseType(tile);
3519  hs = HouseSpec::Get(house);
3521  /* If the callback fails, allow autoslope. */
3522  uint16 res = GetHouseCallback(CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
3523  if (res != CALLBACK_FAILED && ConvertBooleanCallback(hs->grf_prop.grffile, CBID_HOUSE_AUTOSLOPE, res)) allow_terraform = false;
3524  }
3525 
3526  if (allow_terraform) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3527  }
3528  }
3529 
3530  return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3531 }
3532 
3534 extern const TileTypeProcs _tile_type_town_procs = {
3535  DrawTile_Town, // draw_tile_proc
3536  GetSlopePixelZ_Town, // get_slope_z_proc
3537  ClearTile_Town, // clear_tile_proc
3538  AddAcceptedCargo_Town, // add_accepted_cargo_proc
3539  GetTileDesc_Town, // get_tile_desc_proc
3540  GetTileTrackStatus_Town, // get_tile_track_status_proc
3541  NULL, // click_tile_proc
3542  AnimateTile_Town, // animate_tile_proc
3543  TileLoop_Town, // tile_loop_proc
3544  ChangeTileOwner_Town, // change_tile_owner_proc
3545  AddProducedCargo_Town, // add_produced_cargo_proc
3546  NULL, // vehicle_enter_tile_proc
3547  GetFoundation_Town, // get_foundation_proc
3548  TerraformTile_Town, // terraform_tile_proc
3549 };
3550 
3551 
3552 HouseSpec _house_specs[NUM_HOUSES];
3553 
3554 void ResetHouses()
3555 {
3556  memset(&_house_specs, 0, sizeof(_house_specs));
3557  memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
3558 
3559  /* Reset any overrides that have been set. */
3560  _house_mngr.ResetOverride();
3561 }
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:113
Number of town layouts.
Definition: town_type.h:91
Functions related to OTTD&#39;s strings.
static TileType GetTileType(TileIndex tile)
Get the tiletype of a given tile.
Definition: tile_map.h:98
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:36
don&#39;t allow building on structures
Definition: command_type.h:346
Functions/types related to NewGRF debugging.
AcceptanceMatrix cargo_accepted
Bitmap of cargoes accepted by houses for each 4*4 map square of the town.
Definition: town.h:89
byte type
Type of this airport,.
Definition: station_base.h:309
the north corner of the tile is raised
Definition: slope_type.h:55
do not change town rating
Definition: command_type.h:355
uint16 custom_town_number
manually entered number of towns
#define RandomTile()
Get a valid random tile.
Definition: map_func.h:437
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:45
static const int TOWN_GROWTH_TICKS
cycle duration for towns trying to grow. (this originates from the size of the town array in TTD ...
Definition: date_type.h:39
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:151
There can be only one stadium by town.
Definition: town.h:167
Source/destination is a town.
Definition: cargo_type.h:150
static Year GetHouseAge(TileIndex t)
Get the age of the house.
Definition: town_map.h:251
byte probability
Relative probability of appearing (16 is the standard value)
Definition: house.h:119
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:77
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:143
static void UpdateTownCargoes(Town *t, TileIndex start, bool update_total=true)
Update accepted town cargoes around a specific tile.
Definition: town_cmd.cpp:719
Definition of stuff that is very close to a company, like the company struct itself.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:257
static void ChangePopulation(Town *t, int mod)
Change the towns population.
Definition: town_cmd.cpp:401
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1443
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
Definition: town_cmd.cpp:1001
void FillData(const struct Company *c, const struct Company *other=NULL)
Fill the CompanyNewsInformation struct with the required data.
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
Definition: town_cmd.cpp:1135
static TropicZone GetTropicZone(TileIndex tile)
Get the tropic zone.
Definition: tile_map.h:240
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
static TransportType GetTunnelBridgeTransportType(TileIndex t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile.
Definition: town_cmd.cpp:814
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:80
static TileArea GetAreaForTile(TileIndex tile, uint extend=0)
Get the area of the matrix square that contains a specific tile.
Tile information, used while rendering the tile.
Definition: tile_cmd.h:44
bool bribe
enable bribing the local authority
static const byte TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition: house.h:25
CompanyMask statues
which companies have a statue?
Definition: town.h:70
south and east corner are raised
Definition: slope_type.h:59
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
Definition: town_cmd.cpp:1062
bool VerifyTownName(uint32 r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
Definition: townname.cpp:84
void InitializeLayout(TownLayout layout)
Assigns town layout.
Definition: town_cmd.cpp:131
bool GenerateTowns(TownLayout layout)
This function will generate a certain amount of towns, with a certain layout It can be called from th...
Definition: town_cmd.cpp:1990
the west corner of the tile is raised
Definition: slope_type.h:52
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3201
byte landscape
the landscape we&#39;re currently in
void AddAnimatedTile(TileIndex tile)
Add the given tile to the animated tile table (if it does not exist on that table yet)...
Geometric 3x3 grid algorithm.
Definition: town_type.h:87
decides accepted types
Tile is desert.
Definition: tile_type.h:73
Sprites to use and how to display them for town tiles.
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:2063
TownLayout layout
tells us what kind of town we&#39;re building
Definition: town_cmd.cpp:1865
East.
TownFoundingByte found_town
town founding,
Part of an industry.
Definition: tile_type.h:51
const Pair * Find(const T &key) const
Finds given key in this map.
EconomySettings economy
settings to change the economy
uint32 squared_town_zone_radius[HZB_END]
UpdateTownRadius updates this given the house count.
Definition: town.h:50
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:156
static bool IsRoadOwner(TileIndex t, RoadType rt, Owner o)
Check if a specific road type is owned by an owner.
Definition: road_map.h:237
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
Money GetAvailableMoneyForCommand()
Definition: command.cpp:518
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
Checks if current town layout allows 2x2 building here.
Definition: town_cmd.cpp:2198
Functions related to dates.
const char * grf
newGRF used for the tile contents
Definition: tile_cmd.h:63
Town * town
Town the object is built in.
Definition: object_base.h:27
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:97
CompanyByte exclusivity
which company has exclusivity
Definition: town.h:75
Basic road type.
Definition: road_type.h:24
Called to determine if one can alter the ground below a house tile.
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
Checks if current town layout allows building here.
Definition: town_cmd.cpp:2167
Town * town
Nearest town.
Definition: industry.h:43
TileIndex best_position
Best position found so far.
Definition: town_cmd.cpp:2856
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:387
byte flags
See TownFlags.
Definition: town.h:66
terraform a tile
Definition: command_type.h:188
uint8 unwanted[MAX_COMPANIES]
how many months companies aren&#39;t wanted by towns (bribe)
Definition: town.h:74
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
Definition: town_cmd.cpp:3221
CargoID GetCargoTranslation(uint8 cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
static bool _town_rating_test
If true, town rating is in test-mode.
Definition: town_cmd.cpp:3362
A tile with road (or tram tracks)
Definition: tile_type.h:45
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:25
Slope tileh
Slope of the tile.
Definition: tile_cmd.h:47
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:20
Maximal number of cargo types in a game.
Definition: cargo_type.h:66
static uint ScaleByMapSize(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:124
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:61
byte cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:109
Functions used internally by the roads.
no flag is set
Definition: command_type.h:344
CargoTypes cargo_produced
Bitmap of all cargoes produced by houses in this town.
Definition: town.h:88
Specification of a cargo type.
Definition: cargotype.h:56
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
Definition: town_cmd.cpp:3208
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
Definition: town_cmd.cpp:342
bool population_in_label
show the population of a town in his label?
Implementation of simple mapping class.
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:110
bool GenerateTownName(uint32 *townnameparts, TownNames *town_names)
Generates valid town name.
Definition: townname.cpp:122
static bool HasTileWaterGround(TileIndex t)
Checks whether the tile has water at the ground.
Definition: water_map.h:344
Build a statue.
Definition: town.h:206
static void MakeHouseTile(TileIndex t, TownID tid, byte counter, byte stage, HouseID type, byte random_bits)
Make the tile a house.
Definition: town_map.h:354
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:207
South-west part.
Definition: road_type.h:58
Town(TileIndex tile=INVALID_TILE)
Creates a new town.
Definition: town.h:109
static TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:384
static int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height) ...
Definition: slope_func.h:162
Base for all depots (except hangars)
void Clear()
Remove all items from the list.
TownLayoutByte town_layout
select town layout,
static bool HasTileRoadType(TileIndex t, RoadType rt)
Check if a tile has a specific road type.
Definition: road_map.h:188
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
Definition: town_land.h:29
Opening of industries.
Definition: news_type.h:28
Defines the internal data of a functional industry.
Definition: industry.h:41
demolish a tile
Definition: command_type.h:182
Tile description for the &#39;land area information&#39; tool.
Definition: tile_cmd.h:53
DifficultySettings difficulty
settings related to the difficulty
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:263
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
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:2146
the east corner of the tile is raised
Definition: slope_type.h:54
static bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition: slope_func.h:38
uint16 time_until_rebuild
time until we rebuild a house
Definition: town.h:92
CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Do a town action.
Definition: town_cmd.cpp:3090
Helper functions to extract data from command parameters.
Cargo behaves water-like.
Definition: cargotype.h:31
build a "half" road
Definition: command_type.h:203
Used as the user_data for FindFurthestFromWater.
Definition: town_cmd.cpp:1862
void NewMonth()
Update stats for a new month.
Definition: town_type.h:121
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
The client is spectating.
Definition: company_type.h:37
void UpdateVirtCoord()
Resize the sign(label) of the town after changes in population (creation or growth or else) ...
Definition: town_cmd.cpp:374
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Data that needs to be stored for company news messages.
Definition: news_type.h:150
A railway.
Definition: tile_type.h:44
Called to determine which cargoes a town building should accept.
byte dist_local_authority
distance for town local authority, default 20
Functions related to world/map generation.
initial rating
Definition: town_type.h:46
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:84
Contains objects such as transmitters and owned land.
Definition: tile_type.h:53
static bool BuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
Definition: town_cmd.cpp:2283
south and west corner are raised
Definition: slope_type.h:58
Common return value for all commands.
Definition: command_type.h:25
static bool LiftHasDestination(TileIndex t)
Check if the lift of this animated house has a destination.
Definition: town_map.h:84
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
Definition: station_map.h:224
Used for iterations.
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Definition: viewport.cpp:1280
uint16 callback_mask
Bitmask of house callbacks that have to be called.
Definition: house.h:117
CommandFlags GetCommandFlags(uint32 cmd)
Definition: command.cpp:383
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
static bool IsDriveThroughStopTile(TileIndex t)
Is tile t a drive through road stop station?
Definition: station_map.h:234
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Town directory; Window numbers:
Definition: window_type.h:249
Town * town
The town this station is associated with.
uint16 HouseID
OpenTTD ID of house types.
Definition: house_type.h:15
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
uint32 population
Current population of people.
Definition: town.h:47
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Definition: command_type.h:75
static RoadBits GenRandomRoadBits()
Generate a random road block.
Definition: town_cmd.cpp:1460
Tstorage new_act
Actually transported this month.
Definition: town_type.h:116
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:102
decides amount of cargo acceptance
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:1923
const SmallPair< T, U > * End() const
Get the pointer behind the last valid item (const)
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
Definition: subsidy.cpp:153
a flat tile
Definition: slope_type.h:51
static SmallMap< const Town *, int, 4 > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
Definition: town_cmd.cpp:3363
int z
Height.
Definition: tile_cmd.h:49
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:472
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
static byte GetLiftDestination(TileIndex t)
Get the current destination for this lift.
Definition: town_map.h:106
static uint32 RandomRange(uint32 limit)
Pick a random number between 0 and limit - 1, inclusive.
Definition: random_func.hpp:83
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:31
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
Definition: landscape.cpp:472
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:64
Owner owner[4]
Name of the owner(s)
Definition: tile_cmd.h:55
static int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
Definition: math_func.hpp:338
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
Definition: town_cmd.cpp:831
Rebuild the roads.
Definition: town.h:205
this house will only appear during town generation in random games, thus the historical ...
Definition: house.h:92
north and east corner are raised
Definition: slope_type.h:60
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
Definition: town_cmd.cpp:2440
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:112
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
Called to determine the type (if any) of foundation to draw for house tile.
Functions related to (drawing on) viewports.
Pseudo random number generator.
char company_name[64]
The name of the company.
Definition: news_type.h:151
byte population
population (Zero on other tiles in multi tile house.)
Definition: house.h:104
The object is owned by a superuser / goal script.
Definition: company_type.h:29
static byte GetHouseBuildingStage(TileIndex t)
House Construction Scheme.
Definition: town_map.h:185
uint32 goal[NUM_TE]
Amount of cargo required for the town to grow.
Definition: town.h:81
Invalid cargo type.
Definition: cargo_type.h:70
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile.
Definition: town_cmd.cpp:3283
static bool IsHouseCompleted(TileIndex t)
Get the completion of this house.
Definition: town_map.h:147
int16 y
The y value of the coordinate.
Definition: map_type.h:61
Slope GetTileSlope(TileIndex tile, int *h)
Return the slope of a given tile inside the map.
Definition: tile_map.cpp:61
CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Expand a town (scenario editor only).
Definition: town_cmd.cpp:2669
static void AnimateTile_Town(TileIndex tile)
Animate a tile for a town Only certain houses can be animated The newhouses animation supersedes regu...
Definition: town_cmd.cpp:291
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:87
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
Definition: tile_map.h:163
bool exclusive_rights
allow buying exclusive rights
static bool IsBridgeAbove(TileIndex t)
checks if a bridge is set above the ground of this tile
Definition: bridge_map.h:45
TownActions
Town actions of a company.
Definition: town.h:199
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:88
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:26
town buildings
Definition: transparency.h:27
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=NULL, uint textref_stack_size=0, const uint32 *textref_stack=NULL)
Display an error message in a window.
Definition: error_gui.cpp:378
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:216
static void DrawTile_Town(TileInfo *ti)
House Tile drawing handler.
Definition: town_cmd.cpp:212
static uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
Definition: tile_map.h:336
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
uint max_dist
holds the distance that tile is from the water
Definition: town_cmd.cpp:1864
Base for all objects.
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
Definition: town_cmd.cpp:1043
Header of Action 04 "universal holder" structure and functions.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:282
90 degrees right
static byte GetHouseConstructionTick(TileIndex t)
Gets the construction stage of a house.
Definition: town_map.h:197
Tile animation!
static Slope ComplementSlope(Slope s)
Return the complement of a slope.
Definition: slope_func.h:78
TownEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:25
Functions related to low-level strings.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Definition: strings_type.h:20
static RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Definition: road_func.h:144
uint x
X position of the tile in unit coordinates.
Definition: tile_cmd.h:45
None of the directions are disallowed.
Definition: road_map.h:256
byte rating
Station rating for this cargo.
Definition: station_base.h:235
Full 4-way crossing.
Definition: road_type.h:69
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:343
Called on the Get Tile Description for an house tile.
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition: tilearea_type.h:96
Foundation
Enumeration for Foundations.
Definition: slope_type.h:95
Types related to cheating.
TileIndex xy
town center tile
Definition: town.h:56
static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Does the actual town creation.
Definition: town_cmd.cpp:1592
byte mail_generation
mail generation multiplier (tile based, as the acceptances below)
Definition: house.h:108
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:152
ViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:48
static CommandCost TownCanBePlacedHere(TileIndex tile)
Checks if it&#39;s possible to place a town at given tile.
Definition: town_cmd.cpp:1670
TileIndex tile
Tile index.
Definition: tile_cmd.h:48
Functions related to errors.
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
Checks if 2x2 building is allowed here, also takes into account current town layout Also...
Definition: town_cmd.cpp:2260
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:440
static bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
Checks if a house can be built at this tile, must have the same max z as parameter.
Definition: town_cmd.cpp:2127
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:3329
The tile is leveled up to a flat slope.
Definition: slope_type.h:97
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout Also...
Definition: town_cmd.cpp:2235
static DiagDirection RandomDiagDir()
Return a random direction.
Definition: town_cmd.cpp:202
TownSize
Supported initial town sizes.
Definition: town_type.h:21
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:267
West.
HouseClassID class_id
defines the class this house has (not grf file based)
Definition: house.h:121
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3408
Information about GRF, used in the game and (part of it) in savegames.
Geometric 2x2 grid algorithm.
Definition: town_type.h:86
Simple pair of data.
static bool IsUniqueTownName(const char *name)
Verifies this custom name is unique.
Definition: town_cmd.cpp:1695
static void SetRoadOwner(TileIndex t, RoadType rt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:220
int16 ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:77
Generate towns.
Definition: genworld.h:73
Fund new buildings.
Definition: town.h:207
static bool HasTownOwnedRoad(TileIndex t)
Checks if given tile has town owned road.
Definition: road_map.h:249
North.
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:24
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
Functions related to NewGRF houses.
bool ConvertBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
custom cargo production
DoCommandFlag
List of flags for a command.
Definition: command_type.h:343
Southeast.
Southwest.
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:76
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:152
rating needed, "Permissive" difficulty settings
Definition: town_type.h:68
General news (from towns)
Definition: news_type.h:38
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
Definition: town_cmd.cpp:3186
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
#define TILE_AREA_LOOP(var, ta)
A loop which iterates over the tiles of a TileArea.
Definition of base types and functions in a cross-platform compatible way.
when a town grows, all companies have rating increased a bit ...
Definition: town_type.h:54
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:116
Road at the two southern edges.
Definition: road_type.h:66
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including &#39;\0&#39;.
Definition: company_type.h:42
Map accessors for object tiles.
#define TILE_ADDXY(tile, x, y)
Adds a given offset to a tile.
Definition: map_func.h:260
A number of safeguards to prevent using unsafe methods.
Road at the two eastern edges.
Definition: road_type.h:65
bool value
tells if the bool cheat is active or not
Definition: cheat_type.h:20
int16 x
The x value of the coordinate.
Definition: map_type.h:60
Number of available town sizes.
Definition: town_type.h:27
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
static Town * GetRandom()
Return a random valid town.
Definition: town_cmd.cpp:145
Water tile.
Definition: tile_type.h:49
uint y
Y position of the tile in unit coordinates.
Definition: tile_cmd.h:46
static byte GetLiftPosition(TileIndex t)
Get the position of the lift on this animated house.
Definition: town_map.h:127
static bool IsRoadDepotTile(TileIndex t)
Return whether a tile is a road depot tile.
Definition: road_map.h:99
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:55
BuildingCounts< uint16 > building_counts
The number of each type of building in the town.
Definition: town.h:51
An object, such as transmitter, on the map.
Definition: object_base.h:25
Used for iterations.
rating needed, "Permissive" difficulty settings
Definition: town_type.h:61
Empty reference.
Definition: news_type.h:52
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
No road-part is build.
Definition: road_type.h:56
void UpdateTownCargoBitmap()
Updates the bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:768
bool fund_roads
allow funding local road reconstruction
Represents the covered area of e.g.
Definition: tilearea_type.h:18
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
delete a town
Definition: command_type.h:268
Number of available town actions.
Definition: town.h:211
CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the growth rate of the town.
Definition: town_cmd.cpp:2629
Normal news item. (Newspaper with text only)
Definition: news_type.h:80
decides allowance of autosloping
static DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
don&#39;t allow building on water
Definition: command_type.h:348
Random town layout.
Definition: town_type.h:89
... up to RATING_MEDIOCRE
Definition: town_type.h:55
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
Definition: town_cmd.cpp:1884
North-east part.
Definition: road_type.h:60
static void IncHouseConstructionTick(TileIndex t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits...
Definition: town_map.h:210
uint32 GetWorldPopulation()
Determines the world population Basically, count population of all towns, one by one.
Definition: town_cmd.cpp:415
Tstorage new_max
Maximum amount this month.
Definition: town_type.h:114
This structure is the same for both Industries and Houses.
Definition: sprite.h:69
Money GetRemovalCost() const
Get the cost for removing this house.
Definition: town_cmd.cpp:169
The tile has no ownership.
Definition: company_type.h:27
Northwest.
static bool GrowTown(Town *t)
Grow the town.
Definition: town_cmd.cpp:1474
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:1785
static DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
Definition: command_func.h:62
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2457
Structure for storing data while searching the best place to build a statue.
Definition: town_cmd.cpp:2855
Station view; Window numbers:
Definition: window_type.h:340
StringID building_name
building name
Definition: house.h:106
const TileArea & GetArea() const
Get the total covered area.
StationFacilityByte facilities
The facilities that this station has.
CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Delete a town (scenario editor or worldgen only).
Definition: town_cmd.cpp:2709
DiagDirection
Enumeration for diagonal directions.
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
bit mask containing all &#39;simple&#39; slopes
Definition: slope_type.h:63
static uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:318
static bool IsWaterTile(TileIndex t)
Is it a water tile with plain water?
Definition: water_map.h:184
CargoTypes _town_cargoes_accepted
Bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:56
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:500
static Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition: slope_func.h:371
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
RoadBits GetAnyRoadBits(TileIndex tile, RoadType rt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition: road_map.cpp:35
CargoTypes cargo_accepted_total
NOSAVE: Bitmap of all cargoes accepted by houses in this town.
Definition: town.h:90
static void SetLiftDestination(TileIndex t, byte dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit...
Definition: town_map.h:95
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planed tile.
Definition: road.cpp:46
Functions related to autoslope.
Year max_year
last year it can be built
Definition: house.h:103
static DiagDirection GetTunnelBridgeDirection(TileIndex t)
Get the direction pointing to the other end.
static bool IsPlainRailTile(TileIndex t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:61
byte number_towns
the amount of towns
Definition: settings_type.h:57
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16 cbid, uint16 cb_res)
Converts a callback result into a boolean.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:18
static bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition: autoslope.h:46
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition: map.cpp:219
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Returns "growth" if a house was built, or no if the build failed.
Definition: town_cmd.cpp:1378
bool build_on_slopes
allow building on slopes
bool Failed() const
Did this command fail?
Definition: command_type.h:161
const struct SpriteGroup * spritegroup[Tcnt]
pointer to the different sprites of the entity
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2039
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:111
Maximum number of companies.
Definition: company_type.h:25
a steep slope falling to east (from west)
Definition: slope_type.h:68
static Axis GetBridgeAxis(TileIndex t)
Get the axis of the bridge that goes over the tile.
Definition: bridge_map.h:68
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:654
uint8 town_growth_rate
town growth rate
bool has_newhouses
Set if there are any newhouses loaded.
Definition: newgrf.h:164
Empty action set.
Definition: town.h:200
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:35
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3304
Number of town checking action types.
Definition: town.h:154
Base class for all pools.
Definition: pool_type.hpp:83
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:139
North-west part.
Definition: road_type.h:57
static bool IsSea(TileIndex t)
Is it a sea water tile?
Definition: water_map.h:152
Company news item. (Newspaper with face)
Definition: news_type.h:82
Road related functions.
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
Definition: town_cmd.cpp:865
Determine whether the house can be built on the specified tile.
static bool Chance16(const uint a, const uint b)
Flips a coin with given probability.
South-east part.
Definition: road_type.h:59
int tile_count
Number of tiles tried.
Definition: town_cmd.cpp:2857
uint16 override
id of the entity been replaced by
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
OwnerByte owner
The owner of this station.
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:30
uint64 dparam[2]
Parameters of the str string.
Definition: tile_cmd.h:64
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Definition: map.cpp:342
A pair-construct of a TileIndexDiff.
Definition: map_type.h:59
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don&#39;t get linker errors.
Definition: pool_func.hpp:226
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1146
Construction costs.
Definition: economy_type.h:151
static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
Write house information into the map.
Definition: town_cmd.cpp:2087
static Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
static void MakeTownHouseBigger(TileIndex tile)
Make the house advance in its construction stages until completion.
Definition: town_cmd.cpp:451
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between to tiles from a TileIndexDiffC struct.
Definition: map_func.h:232
static TileIndex GetOtherTunnelBridgeEnd(TileIndex t)
Determines type of the wormhole and returns its other end.
char * text
General text with additional information.
Definition: town.h:83
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:31
execute the given command
Definition: command_type.h:345
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, the function returns the same as GetTileSlope.
Definition: landscape.cpp:424
static void MakeSingleHouseBigger(TileIndex tile)
Helper function for house completion stages progression.
Definition: town_cmd.cpp:428
CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the cargo goal of a town.
Definition: town_cmd.cpp:2572
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:37
static Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Definition: slope_func.h:258
uint16 growth_rate
town growth rate
Definition: town.h:95
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:2911
static void HaltLift(TileIndex t)
Stop the lift of this animated house from moving.
Definition: town_map.h:117
Tile got trees.
Definition: tile_type.h:47
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:1336
GRFConfig * GetGRFConfig(uint32 grfid, uint32 mask)
Retrieve a NewGRF from the current config by its grfid.
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:113
static uint MapSize()
Get the size of the map.
Definition: map_func.h:94
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
Definition: cargotype.h:67
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Class for storing amounts of cargo.
Definition: cargo_type.h:83
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:61
static bool IsNormalRoadTile(TileIndex t)
Return whether a tile is a normal road tile.
Definition: road_map.h:57
static void TileLoop_Town(TileIndex tile)
Tile callback function.
Definition: town_cmd.cpp:466
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
There can be only one church by town.
Definition: town.h:166
Town authority; Window numbers:
Definition: window_type.h:189
GUISettings gui
settings related to the GUI
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:52
HouseExtraFlags extra_flags
some more flags
Definition: house.h:120
Invisible tiles at the SW and SE border.
Definition: tile_type.h:50
Reference town. Scroll to town when clicking on the news.
Definition: news_type.h:57
uint32 SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:19
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:143
static void SetLiftPosition(TileIndex t, byte pos)
Set the position of the lift on this animated house.
Definition: town_map.h:137
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:312
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
CompanyByte _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
Set of callback functions for performing tile operations of a given tile type.
Definition: tile_cmd.h:144
Oilrig airport.
Definition: airport.h:40
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:80
Functions related to objects.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:159
Cargo support for NewGRFs.
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
Definition: town_cmd.cpp:3390
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:276
A town owns the tile, or a town is expanding.
Definition: company_type.h:26
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=NULL)
Add a new newsitem to be shown.
Definition: news_gui.cpp:659
static bool FindNearestEmptyLand(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the nearest land tile.
Definition: town_cmd.cpp:1906
byte minimum_life
The minimum number of years this house will survive before the town rebuilds it.
Definition: house.h:124
Buy exclusive transport rights.
Definition: town.h:208
uint16 remove_rating_decrease
rating decrease if removed
Definition: house.h:107
static HouseID GetHouseType(TileIndex t)
Get the type of this house, which is an index into the house spec array.
Definition: town_map.h:61
north and west corner are raised
Definition: slope_type.h:57
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:217
Random size, bigger than small, smaller than large.
Definition: town_type.h:25
Cheat magic_bulldozer
dynamite industries, objects
Definition: cheat_type.h:29
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:71
The tile has no foundation, the slope remains unchanged.
Definition: slope_type.h:96
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3445
TileIndex xy
Base tile of the station.
TileArea location
Location of the object.
Definition: object_base.h:28
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:36
TransportType
Available types of transport.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
TownLayout
Town Layouts.
Definition: town_type.h:82
uint8 initial_city_size
multiplier for the initial size of the cities compared to towns
ObjectType type
Type of the object.
Definition: object_base.h:26
Slope
Enumeration for the slope-type.
Definition: slope_type.h:50
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Checks if a house can be built here.
Definition: town_cmd.cpp:2105
Town view; Window numbers:
Definition: window_type.h:328
Growth rate is controlled by GS.
Definition: town.h:168
A tile of a station.
Definition: tile_type.h:48
Forbidden.
Definition: town_type.h:100
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:2790
TownCache cache
Container for all cacheable data.
Definition: town.h:58
uint8 larger_towns
the number of cities to build. These start off larger and grow twice as fast
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:30
static uint MapMaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition: map_func.h:113
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:412
Town data structure.
Definition: town.h:55
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
Definition: town_cmd.cpp:942
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:76
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:216
Transport by road vehicle.
static const uint16 TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:38
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=NULL, uint8 view=0)
Actually build the object.
Definition: object_cmd.cpp:85
Functions related to OTTD&#39;s landscape.
static void ResetHouseAge(TileIndex t)
Sets the age of the house to zero.
Definition: town_map.h:228
byte town_name
the town name generator used for town names
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:85
Base functions for all Games.
End of town effects.
Definition: cargotype.h:33
Allowed, with custom town layout.
Definition: town_type.h:102
Functions related to commands.
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:100
char * name
Custom town name. If NULL, the town was not renamed and uses the generated name.
Definition: town.h:64
Coordinates of a point in 2D.
a steep slope falling to south (from north)
Definition: slope_type.h:71
Large town.
Definition: town_type.h:24
Struct holding parameters used to generate town name.
Definition: townname_type.h:29
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:570
byte GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:646
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-NULL) Titem.
Definition: pool_type.hpp:235
static uint TileHeight(TileIndex tile)
Returns the height of a tile.
Definition: tile_map.h:31
decides if default foundations need to be drawn
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
Definition: object_cmd.cpp:52
Original algorithm (min. 1 distance between roads)
Definition: town_type.h:84
build a bridge
Definition: command_type.h:183
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:32
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including &#39;\0&#39;.
Definition: town_type.h:108
TownLayoutByte layout
town specific road layout
Definition: town.h:101
static bool TryClearTile(TileIndex tile)
Check whether the land can be cleared.
Definition: town_cmd.cpp:2846
ConstructionSettings construction
construction of things in-game
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:19
Functions that have tunnels and bridges in common.
static TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:181
static const HouseSpec _original_house_specs[]
House specifications from original data.
Definition: town_land.h:1821
Base of all industries.
static DisallowedRoadDirections GetDisallowedRoadDirections(TileIndex t)
Gets the disallowed directions.
Definition: road_map.h:271
const char * GetName() const
Get the name of this grf.
static TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition: map_func.h:372
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale)
Add a child sprite to a parent sprite.
Definition: viewport.cpp:809
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:114
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:116
Airport airport
Tile area the airport covers.
Definition: station_base.h:460
when a town grows, company gains reputation for all well serviced stations ...
Definition: town_type.h:56
void ResetOverride()
Resets the override, which is used while initializing game.
const struct GRFFile * grffile
grf file that introduced this entity
South.
StringID str
Description of the tile.
Definition: tile_cmd.h:54
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:23
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
Get a list of available actions to do at a town.
Definition: town_cmd.cpp:3037
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Tile callback routine.
Definition: town_cmd.cpp:267
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Town name generator stuff.
void Restore()
Restore the variable.
Base functions for all AIs.
Try to bribe the council.
Definition: town.h:209
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:1832
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:85
Base of the town class.
TileIndex tile
holds the tile that was found
Definition: town_cmd.cpp:1863
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
Definition: town_cmd.cpp:3166
TransportedCargoStat< uint32 > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition: town.h:79
GameCreationSettings game_creation
settings used during the creation of a game (map)
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:43
int _nb_orig_names
Number of original town names.
A house by a town.
Definition: tile_type.h:46
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:62
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
static uint MapMaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition: map_func.h:104
bool fund_buildings
allow funding new buildings
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the &#39;Square&#39; distance between the two given tiles.
Definition: map.cpp:176
static bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren&#39;t in the game menu (there&#39;s never transpar...
Definition: transparency.h:61
Other expenses.
Definition: economy_type.h:163
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:112
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town...
Owner
Enum for all companies/owners.
Definition: company_type.h:20
Window functions not directly related to making/drawing windows.
Called to determine how much cargo a town building produces.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
uint32 num_houses
Amount of houses.
Definition: town.h:46
a steep slope falling to west (from east)
Definition: slope_type.h:70
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:77
void UpdateTownCargoTotal(Town *t)
Update the total cargo acceptance of the whole town.
Definition: town_cmd.cpp:701
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:165
town rating does not disallow you from building
Definition: command_type.h:350
decide whether the house can be built on a given tile
#define TILE_ADD(x, y)
Adds to tiles together.
Definition: map_func.h:246
SpriteID sprite
The &#39;real&#39; sprite.
Definition: gfx_type.h:25
Called to decide how much cargo a town building can accept.
static bool SearchTileForStatue(TileIndex tile, void *user_data)
Search callback function for TownActionBuildStatue.
Definition: town_cmd.cpp:2868
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3229
static void SetDParamX(uint64 *s, uint n, uint64 v)
Set a string parameter v at index n in a given array s.
Definition: strings_func.h:191
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
Functions related to news.
Structure contains cached list of stations nearby.
Definition: station_type.h:100
CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Set a custom text in the Town window.
Definition: town_cmd.cpp:2605
byte road_build_months
fund road reconstruction in action?
Definition: town.h:98
CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Rename a town (server-only).
Definition: town_cmd.cpp:2524
Base classes/functions for stations.
static void SetTownIndex(TileIndex t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:36
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
90 degrees left
An invalid company.
Definition: company_type.h:32
static 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:100
bool allow_town_level_crossings
towns are allowed to build level crossings
the south corner of the tile is raised
Definition: slope_type.h:53
uint16 grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:94
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
... but loses for badly serviced stations
Definition: town_type.h:57
Class for backupping variables and making sure they are restored later.
static uint16 ClampToU16(const uint64 a)
Reduce an unsigned 64-bit int to an unsigned 16-bit one.
Definition: math_func.hpp:215
Station data structure.
Definition: station_base.h:446
static bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren&#39;t in the game menu (there&#39;s never transpar...
Definition: transparency.h:50
static bool IsRoadDepot(TileIndex t)
Return whether a tile is a road depot.
Definition: road_map.h:89
Functions related to subsidies.
CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Create a new town.
Definition: town_cmd.cpp:1718
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:1850
Station with an airport.
Definition: station_type.h:57
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:165
static TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
Definition: map_func.h:318
static void UpdateTownGrowCounter(Town *t, uint16 prev_growth_rate)
Updates town grow counter after growth rate change.
Definition: town_cmd.cpp:3151
static void IncrementHouseAge(TileIndex t)
Increments the age of the house.
Definition: town_map.h:239
const CargoSpec * FindFirstCargoWithTownEffect(TownEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2552
a steep slope falling to north (from south)
Definition: slope_type.h:69
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
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:3301
Tstorage old_act
Actually transported last month.
Definition: town_type.h:115
CompanyMask have_ratings
which companies have a rating
Definition: town.h:73
byte HighestSnowLine()
Get the highest possible snow line height, either variable or static.
Definition: landscape.cpp:660
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1463
Cheats _cheats
All the cheats.
Definition: cheat.cpp:18
static int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:306
Road at the two northern edges.
Definition: road_type.h:64
Road at the two western edges.
Definition: road_type.h:67
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:201
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:26
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:3370