OpenTTD Source 20250205-master-gfd85ab1e2c
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"
15#include "town_map.h"
16#include "subsidy_type.h"
17#include "newgrf_storage.h"
18#include "cargotype.h"
19
20template <typename T>
22 std::vector<T> id_count;
23 std::vector<T> class_count;
24
25 auto operator<=>(const BuildingCounts &) const = default;
26};
27
28static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY = 4;
29static const uint CUSTOM_TOWN_MAX_NUMBER = 5000;
30
31static const uint TOWN_GROWTH_WINTER = 0xFFFFFFFE;
32static const uint TOWN_GROWTH_DESERT = 0xFFFFFFFF;
33static const uint16_t TOWN_GROWTH_RATE_NONE = 0xFFFF;
34static const uint16_t MAX_TOWN_GROWTH_TICKS = 930;
35
37extern TownPool _town_pool;
38
40struct TownCache {
41 uint32_t num_houses;
42 uint32_t population;
45 std::array<uint32_t, HZB_END> squared_town_zone_radius;
47
48 auto operator<=>(const TownCache &) const = default;
49};
50
52struct Town : TownPool::PoolItem<&_town_pool> {
54
56
57 /* Town name */
58 uint32_t townnamegrfid;
59 uint16_t townnametype;
60 uint32_t townnameparts;
61 std::string name;
62 mutable std::string cached_name;
63
64 uint8_t flags;
65
66 uint16_t noise_reached;
67
68 CompanyMask statues;
69
70 /* Company ratings. */
71 CompanyMask have_ratings;
76
79 uint32_t goal[NUM_TAE];
80
81 std::string text;
82
83 inline uint8_t GetPercentTransported(CargoType cargo_type) const
84 {
85 if (!IsValidCargoType(cargo_type)) return 0;
86 return this->supplied[cargo_type].old_act * 256 / (this->supplied[cargo_type].old_max + 1);
87 }
88
90
92
93 uint16_t grow_counter;
94 uint16_t growth_rate;
95
98
101
103
104 std::vector<PersistentStorage *> psa_list;
105
110 Town(TileIndex tile = INVALID_TILE) : xy(tile) { }
111
113 ~Town();
114
116
123 inline uint16_t MaxTownNoise() const
124 {
125 if (this->cache.population == 0) return 0; // no population? no noise
126
127 /* 3 is added (the noise of the lowest airport), so the user can at least build a small airfield. */
129 }
130
131 void UpdateVirtCoord();
132
133 inline const std::string &GetCachedName() const
134 {
135 if (!this->name.empty()) return this->name;
136 if (this->cached_name.empty()) this->FillCachedName();
137 return this->cached_name;
138 }
139
140 static inline Town *GetByTile(TileIndex tile)
141 {
142 return Town::Get(GetTownIndex(tile));
143 }
144
145 static Town *GetRandom();
146 static void PostDestructor(size_t index);
147
148private:
149 void FillCachedName() const;
150};
151
152uint32_t GetWorldPopulation();
153
156void ShowTownViewWindow(TownID town);
157void ExpandTown(Town *t);
158
159void RebuildTownKdtree();
160
163 TOWN_COUNCIL_LENIENT = 0,
164 TOWN_COUNCIL_TOLERANT = 1,
165 TOWN_COUNCIL_HOSTILE = 2,
166 TOWN_COUNCIL_PERMISSIVE = 3,
167};
168
178
181 TDIWD_FORCE_REBUILD,
182 TDIWD_POPULATION_CHANGE,
183 TDIWD_FORCE_RESORT,
184};
185
199
201
202
204
205Town *CalcClosestTownFromTile(TileIndex tile, uint threshold = UINT_MAX);
206
207void ResetHouses();
208
230
231void ClearTownHouse(Town *t, TileIndex tile);
232void UpdateTownMaxPass(Town *t);
233void UpdateTownRadius(Town *t);
235Town *ClosestTownFromTile(TileIndex tile, uint threshold);
236void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags);
237HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile);
238void SetTownRatingTestMode(bool mode);
240bool GenerateTowns(TownLayout layout);
243
244extern const uint8_t _town_action_costs[TACT_COUNT];
245
251template <class T>
252void MakeDefaultName(T *obj)
253{
254 /* We only want to set names if it hasn't been set before, or when we're calling from afterload. */
255 assert(obj->name.empty() || obj->town_cn == UINT16_MAX);
256
257 obj->town = ClosestTownFromTile(obj->xy, UINT_MAX);
258
259 /* Find first unused number belonging to this town. This can never fail,
260 * as long as there can be at most 65535 waypoints/depots in total.
261 *
262 * This does 'n * m' search, but with 32bit 'used' bitmap, it needs at
263 * most 'n * (1 + ceil(m / 32))' steps (n - number of waypoints in pool,
264 * m - number of waypoints near this town).
265 * Usually, it needs only 'n' steps.
266 *
267 * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
268 * but this way it is faster */
269
270 uint32_t used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
271 uint32_t next = 0; // first number in the bitmap
272 uint32_t idx = 0; // index where we will stop
273 uint32_t cid = 0; // current index, goes to T::GetPoolSize()-1, then wraps to 0
274
275 do {
276 T *lobj = T::GetIfValid(cid);
277
278 /* check only valid waypoints... */
279 if (lobj != nullptr && obj != lobj) {
280 /* only objects within the same city and with the same type */
281 if (lobj->town == obj->town && lobj->IsOfType(obj)) {
282 /* if lobj->town_cn < next, uint will overflow to '+inf' */
283 uint i = (uint)lobj->town_cn - next;
284
285 if (i < 32) {
286 SetBit(used, i); // update bitmap
287 if (i == 0) {
288 /* shift bitmap while the lowest bit is '1';
289 * increase the base of the bitmap too */
290 do {
291 used >>= 1;
292 next++;
293 } while (HasBit(used, 0));
294 /* when we are at 'idx' again at end of the loop and
295 * 'next' hasn't changed, then no object had town_cn == next,
296 * so we can safely use it */
297 idx = cid;
298 }
299 }
300 }
301 }
302
303 cid++;
304 if (cid == T::GetPoolSize()) cid = 0; // wrap to zero...
305 } while (cid != idx);
306
307 obj->town_cn = (uint16_t)next; // set index...
308}
309
310/*
311 * Converts original town ticks counters to plain game ticks. Note that
312 * tick 0 is a valid tick so actual amount is one more than the counter value.
313 */
314inline uint16_t TownTicksToGameTicks(uint16_t ticks)
315{
316 return (std::min(ticks, MAX_TOWN_GROWTH_TICKS) + 1) * Ticks::TOWN_GROWTH_TICKS - 1;
317}
318
319
321bool CheckTownRoadTypes();
322std::span<const DrawBuildingsTileStruct> GetTownDrawTileData();
323
324#endif /* TOWN_H */
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
bool IsValidCargoType(CargoType t)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:105
static const CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:74
Types/functions related to cargoes.
TownAcceptanceEffect
Town growth effect when delivering cargo.
Definition cargotype.h:22
@ NUM_TAE
Amount of town effects.
Definition cargotype.h:31
Common return value for all commands.
static constexpr TimerGameTick::Ticks TOWN_GROWTH_TICKS
Cycle duration for towns trying to grow (this originates from the size of the town array in TTD).
DoCommandFlag
List of flags for a command.
Owner
Enum for all companies/owners.
@ MAX_COMPANIES
Maximum number of companies.
#define DECLARE_ENUM_AS_BIT_SET(enum_type)
Operators to allow to work with enum as with type safe bit set in C++.
Definition enum_type.hpp:68
uint16_t HouseID
OpenTTD ID of house types.
Definition house_type.h:13
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
Functionality related to the temporary and persistent storage arrays for NewGRFs.
RoadType
The different roadtypes we support.
Definition road_type.h:25
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:57
std::set< Station *, StationCompare > StationList
List of stations.
Class for storing amounts of cargo.
Definition cargo_type.h:112
Specification of a cargo type.
Definition cargotype.h:77
uint8_t town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
uint16_t town_noise_population[4]
population to base decision on noise evaluation (
EconomySettings economy
settings to change the economy
DifficultySettings difficulty
settings related to the difficulty
Base class for all PoolItems.
Tindex index
Index of this pool item.
static Titem * Get(size_t index)
Returns Titem with given index.
Base class for all pools.
Definition pool_type.hpp:79
Data structure with cached data of towns.
Definition town.h:40
uint32_t population
Current population of people.
Definition town.h:42
uint32_t num_houses
Amount of houses.
Definition town.h:41
std::array< uint32_t, HZB_END > squared_town_zone_radius
UpdateTownRadius updates this given the house count.
Definition town.h:45
PartOfSubsidy part_of_subsidy
Is this town a source/destination of a subsidy?
Definition town.h:44
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition town.h:43
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
Definition town.h:46
Town data structure.
Definition town.h:52
bool larger_town
if this is a larger town and should grow more quickly
Definition town.h:99
Town(TileIndex tile=INVALID_TILE)
Creates a new town.
Definition town.h:110
TransportedCargoStat< uint32_t > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
Definition town.h:77
CompanyMask statues
which companies have a statue?
Definition town.h:68
uint16_t time_until_rebuild
time until we rebuild a house
Definition town.h:91
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition town.h:62
TileIndex xy
town center tile
Definition town.h:53
uint8_t fund_buildings_months
fund buildings program in action?
Definition town.h:96
uint16_t noise_reached
level of noise that all the airports are generating
Definition town.h:66
int16_t ratings[MAX_COMPANIES]
ratings of each company for this town
Definition town.h:75
TownLayout layout
town specific road layout
Definition town.h:100
TransportedCargoStat< uint16_t > received[NUM_TAE]
Cargo statistics about received cargotypes.
Definition town.h:78
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition town.h:123
static Town * GetRandom()
Return a random valid town.
Definition town_cmd.cpp:196
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition town.h:61
uint16_t grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition town.h:93
uint8_t flags
See TownFlags.
Definition town.h:64
TownCache cache
Container for all cacheable data.
Definition town.h:55
CompanyID exclusivity
which company has exclusivity
Definition town.h:73
void InitializeLayout(TownLayout layout)
Assign the town layout.
Definition town_cmd.cpp:182
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition town.h:102
uint32_t goal[NUM_TAE]
Amount of cargo required for the town to grow.
Definition town.h:79
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:74
void UpdateVirtCoord()
Resize the sign (label) of the town after it changes population.
Definition town_cmd.cpp:409
std::string text
General text with additional information.
Definition town.h:81
CompanyMask have_ratings
which companies have a rating
Definition town.h:71
~Town()
Destroy the town.
Definition town_cmd.cpp:110
uint8_t unwanted[MAX_COMPANIES]
how many months companies aren't wanted by towns (bribe)
Definition town.h:72
uint16_t growth_rate
town growth rate
Definition town.h:94
StationList stations_near
NOSAVE: List of nearby stations.
Definition town.h:89
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:167
uint8_t road_build_months
fund road reconstruction in action?
Definition town.h:97
Specialised ViewportSign that tracks whether it is valid for entering into a Kdtree.
Store the maximum and actually transported cargo amount for the current and the last month.
Definition town_type.h:115
Tstorage old_max
Maximum amount last month.
Definition town_type.h:116
Tstorage old_act
Actually transported last month.
Definition town_type.h:118
basic types related to subsidies
PartOfSubsidy
What part of a subsidy is something?
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
Definition of the tick-based game-timer.
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition town.h:31
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
void ClearTownHouse(Town *t, TileIndex tile)
Clear a town house.
TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
Get a list of available town authority actions.
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition town.h:32
TownDirectoryInvalidateWindowData
Special values for town list window for the data parameter of InvalidateWindowData.
Definition town.h:180
TownFlags
This enum is used in conjunction with town->flags.
Definition town.h:193
@ TOWN_HAS_CHURCH
There can be only one church by town.
Definition town.h:195
@ TOWN_HAS_STADIUM
There can be only one stadium by town.
Definition town.h:196
@ TOWN_IS_GROWING
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition town.h:194
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
Definition town.h:197
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition town.h:173
@ ROAD_REMOVE
Removal of a road owned by the town.
Definition town.h:174
@ TUNNELBRIDGE_REMOVE
Removal of a tunnel or bridge owned by the towb.
Definition town.h:175
@ TOWN_RATING_CHECK_TYPE_COUNT
Number of town checking action types.
Definition town.h:176
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
Definition town_cmd.cpp:462
static const uint CUSTOM_TOWN_MAX_NUMBER
this is the maximum number of towns a user can specify in customisation
Definition town.h:29
TownActions
Town actions of a company.
Definition town.h:210
@ TACT_BUILD_STATUE
Build a statue.
Definition town.h:217
@ TACT_CONSTRUCTION
All possible construction actions.
Definition town.h:225
@ TACT_ROAD_REBUILD
Rebuild the roads.
Definition town.h:216
@ TACT_ADVERTISE_MEDIUM
Medium advertising campaign.
Definition town.h:214
@ TACT_BUY_RIGHTS
Buy exclusive transport rights.
Definition town.h:219
@ TACT_BRIBE
Try to bribe the council.
Definition town.h:220
@ TACT_ADVERTISE
All possible advertising actions.
Definition town.h:224
@ TACT_COUNT
Number of available town actions.
Definition town.h:222
@ TACT_ALL
All possible actions.
Definition town.h:227
@ TACT_FUND_BUILDINGS
Fund new buildings.
Definition town.h:218
@ TACT_FUNDS
All possible funding actions.
Definition town.h:226
@ TACT_NONE
Empty action set.
Definition town.h:211
@ TACT_ADVERTISE_LARGE
Large advertising campaign.
Definition town.h:215
@ TACT_ADVERTISE_SMALL
Small advertising campaign.
Definition town.h:213
const uint8_t _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
void UpdateTownMaxPass(Town *t)
Update the maximum amount of montly passengers and mail for a town, based on its population.
CargoArray GetAcceptedCargoOfHouse(const HouseSpec *hs)
Get accepted cargo of a house prototype.
Definition town_cmd.cpp:860
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition town.h:28
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition town_cmd.cpp:435
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
RoadType GetTownRoadType()
Get the road type that towns should build at this current moment.
Definition town_cmd.cpp:960
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
bool CheckTownRoadTypes()
Check if towns are able to build road.
bool GenerateTowns(TownLayout layout)
Generate a number of towns with a given layout.
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
static const uint16_t MAX_TOWN_GROWTH_TICKS
Max amount of original town ticks that still fit into uint16_t, about equal to UINT16_MAX / TOWN_GROW...
Definition town.h:34
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
TownCouncilAttitudes
Settings for town council attitudes.
Definition town.h:162
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
void UpdateTownRadius(Town *t)
Update the cached town zone radii of a town, based on the number of houses.
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition town.h:33
void MakeDefaultName(T *obj)
Set the default name for a depot/waypoint.
Definition town.h:252
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition town_cmd.cpp:427
Accessors for towns.
TownID GetTownIndex(Tile t)
Get the index of which town this house/street is attached to.
Definition town_map.h:23
TownLayout
Town Layouts.
Definition town_type.h:81
Types related to viewports.