OpenTTD Source  1.10.0-RC1
town.h
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #ifndef TOWN_H
11 #define TOWN_H
12 
13 #include "viewport_type.h"
14 #include "town_map.h"
15 #include "subsidy_type.h"
16 #include "newgrf_storage.h"
17 #include "cargotype.h"
18 #include "tilematrix_type.hpp"
19 #include <list>
20 
21 template <typename T>
23  T id_count[NUM_HOUSES];
24  T class_count[HOUSE_CLASS_MAX];
25 };
26 
28 
29 static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY = 4;
30 static const uint CUSTOM_TOWN_MAX_NUMBER = 5000;
31 
32 static const TownID INVALID_TOWN = 0xFFFF;
33 
34 static const uint TOWN_GROWTH_WINTER = 0xFFFFFFFE;
35 static const uint TOWN_GROWTH_DESERT = 0xFFFFFFFF;
36 static const uint16 TOWN_GROWTH_RATE_NONE = 0xFFFF;
37 static const uint16 MAX_TOWN_GROWTH_TICKS = 930;
38 
40 extern TownPool _town_pool;
41 
43 struct TownCache {
44  uint32 num_houses;
45  uint32 population;
48  uint32 squared_town_zone_radius[HZB_END];
50 };
51 
53 struct Town : TownPool::PoolItem<&_town_pool> {
55 
57 
58  /* Town name */
59  uint32 townnamegrfid;
60  uint16 townnametype;
61  uint32 townnameparts;
62  char *name;
63  mutable std::string cached_name;
64 
65  byte flags;
66 
67  uint16 noise_reached;
68 
69  CompanyMask statues;
70 
71  /* Company ratings. */
72  CompanyMask have_ratings;
73  uint8 unwanted[MAX_COMPANIES];
76  int16 ratings[MAX_COMPANIES];
77 
80  uint32 goal[NUM_TE];
81 
82  char *text;
83 
84  inline byte GetPercentTransported(CargoID cid) const { return this->supplied[cid].old_act * 256 / (this->supplied[cid].old_max + 1); }
85 
86  /* Cargo production and acceptance stats. */
87  CargoTypes cargo_produced;
89  CargoTypes cargo_accepted_total;
91 
93 
94  uint16 grow_counter;
95  uint16 growth_rate;
96 
99 
100  bool larger_town;
102 
103  bool show_zone;
104 
105  std::list<PersistentStorage *> psa_list;
106 
111  Town(TileIndex tile = INVALID_TILE) : xy(tile) { }
112 
114  ~Town();
115 
116  void InitializeLayout(TownLayout layout);
117 
124  inline uint16 MaxTownNoise() const
125  {
126  if (this->cache.population == 0) return 0; // no population? no noise
127 
128  /* 3 is added (the noise of the lowest airport), so the user can at least build a small airfield. */
130  }
131 
132  void UpdateVirtCoord();
133 
134  inline const char *GetCachedName() const
135  {
136  if (this->name != nullptr) return this->name;
137  if (this->cached_name.empty()) this->FillCachedName();
138  return this->cached_name.c_str();
139  }
140 
141  static inline Town *GetByTile(TileIndex tile)
142  {
143  return Town::Get(GetTownIndex(tile));
144  }
145 
146  static Town *GetRandom();
147  static void PostDestructor(size_t index);
148 
149 private:
150  void FillCachedName() const;
151 };
152 
153 uint32 GetWorldPopulation();
154 
156 void ClearAllTownCachedNames();
157 void ShowTownViewWindow(TownID town);
158 void ExpandTown(Town *t);
159 
160 void RebuildTownKdtree();
161 
162 
171 };
172 
175  TDIWD_FORCE_REBUILD,
176  TDIWD_POPULATION_CHANGE,
177  TDIWD_FORCE_RESORT,
178 };
179 
187 enum TownFlags {
192 };
193 
195 
196 
198 
199 Town *CalcClosestTownFromTile(TileIndex tile, uint threshold = UINT_MAX);
200 
201 void ResetHouses();
202 
203 void ClearTownHouse(Town *t, TileIndex tile);
204 void UpdateTownMaxPass(Town *t);
205 void UpdateTownRadius(Town *t);
206 void UpdateTownCargoes(Town *t);
207 void UpdateTownCargoTotal(Town *t);
208 void UpdateTownCargoBitmap();
210 Town *ClosestTownFromTile(TileIndex tile, uint threshold);
211 void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags);
212 HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile);
213 void SetTownRatingTestMode(bool mode);
214 uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t);
215 bool GenerateTowns(TownLayout layout);
217 
220  TACT_NONE = 0x00,
221 
229  TACT_BRIBE = 0x80,
230 
232 
237 };
239 
240 extern const byte _town_action_costs[TACT_COUNT];
241 extern TownID _new_town_id;
242 
248 template <class T>
249 void MakeDefaultName(T *obj)
250 {
251  /* We only want to set names if it hasn't been set before, or when we're calling from afterload. */
252  assert(obj->name == nullptr || obj->town_cn == UINT16_MAX);
253 
254  obj->town = ClosestTownFromTile(obj->xy, UINT_MAX);
255 
256  /* Find first unused number belonging to this town. This can never fail,
257  * as long as there can be at most 65535 waypoints/depots in total.
258  *
259  * This does 'n * m' search, but with 32bit 'used' bitmap, it needs at
260  * most 'n * (1 + ceil(m / 32))' steps (n - number of waypoints in pool,
261  * m - number of waypoints near this town).
262  * Usually, it needs only 'n' steps.
263  *
264  * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
265  * but this way it is faster */
266 
267  uint32 used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
268  uint32 next = 0; // first number in the bitmap
269  uint32 idx = 0; // index where we will stop
270  uint32 cid = 0; // current index, goes to T::GetPoolSize()-1, then wraps to 0
271 
272  do {
273  T *lobj = T::GetIfValid(cid);
274 
275  /* check only valid waypoints... */
276  if (lobj != nullptr && obj != lobj) {
277  /* only objects within the same city and with the same type */
278  if (lobj->town == obj->town && lobj->IsOfType(obj)) {
279  /* if lobj->town_cn < next, uint will overflow to '+inf' */
280  uint i = (uint)lobj->town_cn - next;
281 
282  if (i < 32) {
283  SetBit(used, i); // update bitmap
284  if (i == 0) {
285  /* shift bitmap while the lowest bit is '1';
286  * increase the base of the bitmap too */
287  do {
288  used >>= 1;
289  next++;
290  } while (HasBit(used, 0));
291  /* when we are at 'idx' again at end of the loop and
292  * 'next' hasn't changed, then no object had town_cn == next,
293  * so we can safely use it */
294  idx = cid;
295  }
296  }
297  }
298  }
299 
300  cid++;
301  if (cid == T::GetPoolSize()) cid = 0; // wrap to zero...
302  } while (cid != idx);
303 
304  obj->town_cn = (uint16)next; // set index...
305 }
306 
307 /*
308  * Converts original town ticks counters to plain game ticks. Note that
309  * tick 0 is a valid tick so actual amount is one more than the counter value.
310  */
311 static inline uint16 TownTicksToGameTicks(uint16 ticks) {
312  return (min(ticks, MAX_TOWN_GROWTH_TICKS) + 1) * TOWN_GROWTH_TICKS - 1;
313 }
314 
315 
316 extern CargoTypes _town_cargoes_accepted;
317 
318 RoadType GetTownRoadType(const Town *t);
319 
320 #endif /* TOWN_H */
Owner
Enum for all companies/owners.
Definition: company_type.h:18
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:34
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
Definition: town_cmd.cpp:2618
AcceptanceMatrix cargo_accepted
Bitmap of cargoes accepted by houses for each 4*4 map square of the town.
Definition: town.h:88
DECLARE_ENUM_AS_BIT_SET(GenderEthnicity) enum CompanyManagerFaceVariable
Bitgroups of the CompanyManagerFace variable.
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:37
There can be only one stadium by town.
Definition: town.h:190
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition: town.h:167
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
PartOfSubsidy part_of_subsidy
Is this town a source/destination of a subsidy?
Definition: town.h:47
void UpdateTownCargoes(Town *t)
Update cargo acceptance for the complete town.
Definition: town_cmd.cpp:835
CompanyMask statues
which companies have a statue?
Definition: town.h:69
basic types related to subsidies
static const uint CUSTOM_TOWN_MAX_NUMBER
this is the maximum number of towns a user can specify in customisation
Definition: town.h:30
void UpdateTownCargoTotal(Town *t)
Update the total cargo acceptance of the whole town.
Definition: town_cmd.cpp:787
EconomySettings economy
settings to change the economy
int32 TileIndexDiff
An offset value between to tiles.
Definition: map_func.h:154
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:329
byte fund_buildings_months
fund buildings program in action?
Definition: town.h:97
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition: town.h:63
Functionality related to the temporary and persistent storage arrays for NewGRFs. ...
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
byte flags
See TownFlags.
Definition: town.h:65
Maximal number of cargo types in a game.
Definition: cargo_type.h:64
CargoTypes cargo_produced
Bitmap of all cargoes produced by houses in this town.
Definition: town.h:87
Specification of a cargo type.
Definition: cargotype.h:55
Medium advertising campaign.
Definition: town.h:223
CargoTypes _town_cargoes_accepted
Bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:58
TownLayout
Town Layouts.
Definition: town_type.h:78
Build a statue.
Definition: town.h:226
Amount of town effects.
Definition: cargotype.h:33
Town(TileIndex tile=INVALID_TILE)
Creates a new town.
Definition: town.h:111
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:415
DifficultySettings difficulty
settings related to the difficulty
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition: town.h:103
uint16 time_until_rebuild
time until we rebuild a house
Definition: town.h:92
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:3575
Template for storing a value per area of the map.
TownDirectoryInvalidateWindowData
Special values for town list window for the data parameter of InvalidateWindowData.
Definition: town.h:174
Common return value for all commands.
Definition: command_type.h:23
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:2143
uint32 GetWorldPopulation()
Determines the world population Basically, count population of all towns, one by one.
Definition: town_cmd.cpp:448
RoadType
The different roadtypes we support.
Definition: road_type.h:22
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
uint16 HouseID
OpenTTD ID of house types.
Definition: house_type.h:13
uint32 population
Current population of people.
Definition: town.h:45
std::set< Station *, StationCompare > StationList
List of stations.
Definition: station_type.h:94
uint16 noise_reached
level of noise that all the airports are generating
Definition: town.h:67
const byte _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
Definition: town_cmd.cpp:2992
void UpdateTownCargoBitmap()
Updates the bitmap of all cargoes accepted by houses.
Definition: town_cmd.cpp:854
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
Rebuild the roads.
Definition: town.h:225
Specialised ViewportSign that tracks whether it is valid for entering into a Kdtree.
Definition: viewport_type.h:57
Types related to viewports.
Large advertising campaign.
Definition: town.h:224
TownActions
Town actions of a company.
Definition: town.h:219
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:3534
TownEffect
Town growth effect when delivering cargo.
Definition: cargotype.h:24
TileIndex xy
town center tile
Definition: town.h:54
void MakeDefaultName(T *obj)
Set the default name for a depot/waypoint.
Definition: town.h:249
Fund new buildings.
Definition: town.h:227
static const uint16 MAX_TOWN_GROWTH_TICKS
Max amount of original town ticks that still fit into uint16, about equal to UINT16_MAX / TOWN_GROWTH...
Definition: town.h:37
static TownID GetTownIndex(TileIndex t)
Get the index of which town this house/street is attached to.
Definition: town_map.h:22
All possible advertising actions.
Definition: town.h:233
DoCommandFlag
List of flags for a command.
Definition: command_type.h:344
All possible construction actions.
Definition: town.h:234
uint16 town_noise_population[3]
population to base decision on noise evaluation (
StationList stations_near
NOSAVE: List of nearby stations.
Definition: town.h:90
BuildingCounts< uint16 > building_counts
The number of each type of building in the town.
Definition: town.h:49
Number of available town actions.
Definition: town.h:231
const CargoSpec * FindFirstCargoWithTownEffect(TownEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:2716
All possible funding actions.
Definition: town.h:235
Small advertising campaign.
Definition: town.h:222
Accessors for towns.
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Definition: town_cmd.cpp:2195
CargoTypes cargo_accepted_total
NOSAVE: Bitmap of all cargoes accepted by houses in this town.
Definition: town.h:89
Base class for all PoolItems.
Definition: pool_type.hpp:226
uint16 MaxTownNoise() const
Calculate the max town noise.
Definition: town.h:124
Empty action set.
Definition: town.h:220
Number of town checking action types.
Definition: town.h:170
Base class for all pools.
Definition: pool_type.hpp:81
Removal of a tunnel or bridge owned by the towb.
Definition: town.h:169
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3516
char * text
General text with additional information.
Definition: town.h:82
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition: town.h:29
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:35
uint16 growth_rate
town growth rate
Definition: town.h:95
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:3495
Tstorage old_max
Maximum amount last month.
Definition: town_type.h:113
TownLayout layout
town specific road layout
Definition: town.h:101
There can be only one church by town.
Definition: town.h:189
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:78
static const uint HOUSE_CLASS_MAX
There can only be as many classes as there are new houses, plus one for NO_CLASS, as the original hou...
Definition: house.h:38
Buy exclusive transport rights.
Definition: town.h:228
byte town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
Definition: settings_type.h:69
Removal of a road owned by the town.
Definition: town.h:168
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
Get a list of available actions to do at a town.
Definition: town_cmd.cpp:3238
TownFlags
This enum is used in conjunction with town->flags.
Definition: town.h:187
All possible actions.
Definition: town.h:236
Growth rate is controlled by GS.
Definition: town.h:191
TownCache cache
Container for all cacheable data.
Definition: town.h:56
Maximum number of companies.
Definition: company_type.h:23
Town data structure.
Definition: town.h:53
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:75
static const uint16 TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:36
Types/functions related to cargoes.
bool larger_town
if this is a larger town and should grow more quickly
Definition: town.h:100
char * name
Custom town name. If nullptr, the town was not renamed and uses the generated name.
Definition: town.h:62
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition: town.h:46
Data structure with cached data of towns.
Definition: town.h:43
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Try to bribe the council.
Definition: town.h:229
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:83
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
PartOfSubsidy
What part of a subsidy is something?
Definition: subsidy_type.h:16
uint32 num_houses
Amount of houses.
Definition: town.h:44
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition: town.h:188
byte road_build_months
fund road reconstruction in action?
Definition: town.h:98
CompanyID exclusivity
which company has exclusivity
Definition: town.h:74
uint16 grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition: town.h:94
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
Definition: town_cmd.cpp:3650
Tstorage old_act
Actually transported last month.
Definition: town_type.h:115
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
Definition: town_cmd.cpp:3613
CompanyMask have_ratings
which companies have a rating
Definition: town.h:72