OpenTTD Source 20260711-master-g3fb3006dff
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#ifndef TOWN_H
11#define TOWN_H
12
13#include "misc/history_type.hpp"
14#include "viewport_type.h"
16#include "town_map.h"
17#include "subsidy_type.h"
18#include "newgrf_storage.h"
19#include "cargotype.h"
20
21template <typename T>
23 std::vector<T> id_count{};
24 std::vector<T> class_count{};
25
26 auto operator<=>(const BuildingCounts &) const = default;
27};
28
29static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY = 4;
30static const uint CUSTOM_TOWN_MAX_NUMBER = 5000;
31
32static const uint TOWN_GROWTH_WINTER = 0xFFFFFFFE;
33static const uint TOWN_GROWTH_DESERT = 0xFFFFFFFF;
34static const uint16_t TOWN_GROWTH_RATE_NONE = 0xFFFF;
35static const uint16_t MAX_TOWN_GROWTH_TICKS = 930;
36
37typedef Pool<Town, TownID, 64> TownPool;
38extern TownPool _town_pool;
39
41enum class TownFlag : uint8_t {
46};
47
50
52struct TownCache {
53 uint32_t num_houses = 0;
54 uint32_t population = 0;
57 std::array<uint32_t, NUM_HOUSE_ZONES> squared_town_zone_radius{};
59
60 auto operator<=>(const TownCache &) const = default;
61};
62
64struct Town : TownPool::PoolItem<&_town_pool> {
66
68
72 uint16_t townnametype = 0;
73 uint32_t townnameparts = 0;
74 std::string name{};
75 mutable std::string cached_name{};
77
79
80 uint16_t noise_reached = 0;
81
83
84 /* Company ratings. */
87 CompanyID exclusivity = CompanyID::Invalid();
88 uint8_t exclusive_counter = 0;
90
92 uint32_t production = 0;
93 uint32_t transported = 0;
94
95 uint8_t PctTransported() const
96 {
97 if (this->production == 0) return 0;
98 return ClampTo<uint8_t>(this->transported * 256 / this->production);
99 }
100 };
101
102 struct SuppliedCargo {
103 CargoType cargo = INVALID_CARGO;
105
106 SuppliedCargo() = default;
107 SuppliedCargo(CargoType cargo) : cargo(cargo) {}
108 };
109
112 uint32_t accepted = 0;
113 };
114
116 struct AcceptedCargo {
117 CargoType cargo = INVALID_CARGO;
119
120 AcceptedCargo() = default;
126 };
127
128 using SuppliedCargoes = std::vector<SuppliedCargo>;
129 using AcceptedCargoes = std::vector<AcceptedCargo>;
130
136
138
139 inline SuppliedCargo &GetOrCreateCargoSupplied(CargoType cargo)
140 {
141 assert(IsValidCargoType(cargo));
142 auto it = std::ranges::lower_bound(this->supplied, cargo, std::less{}, &SuppliedCargo::cargo);
143 if (it == std::end(this->supplied) || it->cargo != cargo) it = this->supplied.emplace(it, cargo);
144 return *it;
145 }
146
147 inline SuppliedCargoes::const_iterator GetCargoSupplied(CargoType cargo) const
148 {
149 if (!IsValidCargoType(cargo)) return std::end(this->supplied);
150 auto it = std::ranges::lower_bound(this->supplied, cargo, std::less{}, &SuppliedCargo::cargo);
151 if (it == std::end(this->supplied) || it->cargo != cargo) return std::end(this->supplied);
152 return it;
153 }
154
161 {
162 assert(IsValidCargoType(cargo));
163 auto it = std::ranges::lower_bound(this->accepted, cargo, std::less{}, &AcceptedCargo::cargo);
164 if (it == std::end(this->accepted) || it->cargo != cargo) it = this->accepted.emplace(it, cargo);
165 return *it;
166 }
167
173 inline AcceptedCargoes::const_iterator GetCargoAccepted(CargoType cargo) const
174 {
175 if (!IsValidCargoType(cargo)) return std::end(this->accepted);
176 auto it = std::ranges::lower_bound(this->accepted, cargo, std::less{}, &AcceptedCargo::cargo);
177 if (it == std::end(this->accepted) || it->cargo != cargo) return std::end(this->accepted);
178 return it;
179 }
180
181 inline uint8_t GetPercentTransported(CargoType cargo_type) const
182 {
183 auto it = this->GetCargoSupplied(cargo_type);
184 if (it == std::end(this->supplied)) return 0;
185
186 return it->history[LAST_MONTH].PctTransported();
187 }
188
190
191 uint16_t time_until_rebuild = 0;
192
193 uint16_t grow_counter = 0;
194 uint16_t growth_rate = 0;
195
197 uint8_t road_build_months = 0;
198
199 bool larger_town = false;
201
202 bool show_zone = false;
203
204 std::vector<PersistentStorage *> psa_list{};
205
211 Town(TownID index, TileIndex tile = INVALID_TILE) : TownPool::PoolItem<&_town_pool>(index), xy(tile) { }
212
214 ~Town();
215
217
224 inline uint16_t MaxTownNoise() const
225 {
226 if (this->cache.population == 0) return 0; // no population? no noise
227
228 /* 3 is added (the noise of the lowest airport), so the user can at least build a small airfield. */
229 return ClampTo<uint16_t>((this->cache.population / _settings_game.economy.town_noise_population[_settings_game.difficulty.town_council_tolerance]) + 3);
230 }
231
232 void UpdateVirtCoord();
233
234 inline const std::string &GetCachedName() const
235 {
236 if (!this->name.empty()) return this->name;
237 if (this->cached_name.empty()) this->FillCachedName();
238 return this->cached_name;
239 }
240
241 static inline Town *GetByTile(TileIndex tile)
242 {
243 return Town::Get(GetTownIndex(tile));
244 }
245
246 static Town *GetRandom();
247 static void PostDestructor(size_t index);
248
249private:
250 void FillCachedName() const;
251};
252
253uint32_t GetWorldPopulation();
254
257void ShowTownViewWindow(TownID town);
258void ExpandTown(Town *t);
259
260void RebuildTownKdtree();
261
264 TOWN_COUNCIL_LENIENT = 0,
265 TOWN_COUNCIL_TOLERANT = 1,
266 TOWN_COUNCIL_HOSTILE = 2,
267 TOWN_COUNCIL_PERMISSIVE = 3,
268};
269
279
282 TDIWD_FORCE_REBUILD,
283 TDIWD_POPULATION_CHANGE,
284 TDIWD_FORCE_RESORT,
285};
286
288
289
291
292Town *CalcClosestTownFromTile(TileIndex tile, uint threshold = UINT_MAX);
293
294void ResetHouses();
295
308
311
312void ClearTownHouse(Town *t, TileIndex tile);
313void UpdateTownMaxPass(Town *t);
314void UpdateTownRadius(Town *t);
316Town *ClosestTownFromTile(TileIndex tile, uint threshold);
317void ChangeTownRating(Town *t, int add, int max, DoCommandFlags flags);
319void SetTownRatingTestMode(bool mode);
320TownActions GetMaskOfTownActions(CompanyID cid, const Town *t);
322bool GenerateTowns(TownLayout layout, std::optional<uint> number = std::nullopt);
325
326uint8_t GetTownActionCost(TownAction action);
327
333template <class T>
335{
336 /* We only want to set names if it hasn't been set before, or when we're calling from afterload. */
337 assert(obj->name.empty() || obj->town_cn == UINT16_MAX);
338
339 obj->town = ClosestTownFromTile(obj->xy, UINT_MAX);
340
341 /* Find first unused number belonging to this town. This can never fail,
342 * as long as there can be at most 65535 waypoints/depots in total.
343 *
344 * This does 'n * m' search, but with 32bit 'used' bitmap, it needs at
345 * most 'n * (1 + ceil(m / 32))' steps (n - number of waypoints in pool,
346 * m - number of waypoints near this town).
347 * Usually, it needs only 'n' steps.
348 *
349 * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
350 * but this way it is faster */
351
352 uint32_t used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
353 uint32_t next = 0; // first number in the bitmap
354 uint32_t idx = 0; // index where we will stop
355 uint32_t cid = 0; // current index, goes to T::GetPoolSize()-1, then wraps to 0
356
357 do {
358 T *lobj = T::GetIfValid(cid);
359
360 /* check only valid waypoints... */
361 if (lobj != nullptr && obj != lobj) {
362 /* only objects within the same city and with the same type */
363 if (lobj->town == obj->town && lobj->IsOfType(obj)) {
364 /* if lobj->town_cn < next, uint will overflow to '+inf' */
365 uint i = (uint)lobj->town_cn - next;
366
367 if (i < 32) {
368 SetBit(used, i); // update bitmap
369 if (i == 0) {
370 /* shift bitmap while the lowest bit is '1';
371 * increase the base of the bitmap too */
372 do {
373 used >>= 1;
374 next++;
375 } while (HasBit(used, 0));
376 /* when we are at 'idx' again at end of the loop and
377 * 'next' hasn't changed, then no object had town_cn == next,
378 * so we can safely use it */
379 idx = cid;
380 }
381 }
382 }
383 }
384
385 cid++;
386 if (cid == T::GetPoolSize()) cid = 0; // wrap to zero...
387 } while (cid != idx);
388
389 obj->town_cn = (uint16_t)next; // set index...
390}
391
392/*
393 * Converts original town ticks counters to plain game ticks. Note that
394 * tick 0 is a valid tick so actual amount is one more than the counter value.
395 */
396inline uint16_t TownTicksToGameTicks(uint16_t ticks)
397{
398 return (std::min(ticks, MAX_TOWN_GROWTH_TICKS) + 1) * Ticks::TOWN_GROWTH_TICKS - 1;
399}
400
401
403bool CheckTownRoadTypes();
404std::span<const DrawBuildingsTileStruct> GetTownDrawTileData();
405
406#endif /* TOWN_H */
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:110
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
Types/functions related to cargoes.
TownAcceptanceEffect
Town growth effect when delivering cargo.
Definition cargotype.h:22
@ End
End of town effects.
Definition cargotype.h:30
Common return value for all commands.
Container for an encoded string, created by GetEncodedString.
Enum-as-bit-set wrapper.
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).
A sort-of mixin that implements 'at(pos)' and 'operator[](pos)' only for a specific type.
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
#define T
Climate temperate.
Definition engines.h:91
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Types for storing historical data.
std::array< T, HISTORY_RECORDS > HistoryData
Container type for storing history data.
uint64_t ValidHistoryMask
Mask of valid history records.
HouseZone
Concentric rings of zoning around the centre of a town.
Definition house.h:59
uint16_t HouseID
OpenTTD ID of house types.
Definition house_type.h:15
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
Functionality related to the temporary and persistent storage arrays for NewGRFs.
uint32_t GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:15
RoadType
The different roadtypes we support.
Definition road_type.h:23
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
std::set< Station *, StationCompare > StationList
List of stations.
Class for storing amounts of cargo.
Definition cargo_type.h:118
Specification of a cargo type.
Definition cargotype.h:77
static Town * Get(auto index)
Base class for all pools.
Data structure with cached data of towns.
Definition town.h:52
uint32_t population
Current population of people.
Definition town.h:54
uint32_t num_houses
Amount of houses.
Definition town.h:53
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
Definition town.h:55
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
Definition town.h:58
std::array< uint32_t, NUM_HOUSE_ZONES > squared_town_zone_radius
UpdateTownRadius updates this given the house count.
Definition town.h:57
PartsOfSubsidy part_of_subsidy
Is this town a source/destination of a subsidy?
Definition town.h:56
Storage for accepted cargo history.
Definition town.h:116
AcceptedCargo(CargoType cargo)
Construct AcceptedCargo.
Definition town.h:125
CargoType cargo
Cargo type of accepted cargo.
Definition town.h:117
HistoryData< AcceptedHistory > history
Histor data of accepted cargo.
Definition town.h:118
Individual data point for accepted cargo history.
Definition town.h:111
uint32_t accepted
Total accepted.
Definition town.h:112
uint32_t transported
Total transported.
Definition town.h:93
uint32_t production
Total produced.
Definition town.h:92
Town data structure.
Definition town.h:64
EncodedString text
General text with additional information.
Definition town.h:137
bool larger_town
if this is a larger town and should grow more quickly
Definition town.h:199
CompanyMask statues
which companies have a statue?
Definition town.h:82
uint16_t time_until_rebuild
time until we rebuild a house
Definition town.h:191
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
Definition town.h:75
TileIndex xy
town center tile
Definition town.h:65
uint8_t fund_buildings_months
fund buildings program in action?
Definition town.h:196
uint16_t noise_reached
level of noise that all the airports are generating
Definition town.h:80
SuppliedCargoes supplied
Cargo statistics about supplied cargo.
Definition town.h:131
TownLayout layout
town specific road layout
Definition town.h:200
AcceptedCargo & GetOrCreateCargoAccepted(CargoType cargo)
Get or create the storage for an accepted cargo.
Definition town.h:160
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition town.h:224
static Town * GetRandom()
Return a random valid town.
Definition town_cmd.cpp:204
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition town.h:74
Town(TownID index, TileIndex tile=INVALID_TILE)
Creates a new town.
Definition town.h:211
GrfID townnamegrfid
NewGRF id that contains the name. O is not used.
Definition town.h:71
uint16_t grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
Definition town.h:193
std::vector< AcceptedCargo > AcceptedCargoes
Type for storage of all accepted cargo history.
Definition town.h:129
uint32_t townnameparts
Random number that give unique town name when passed to generator.
Definition town.h:73
TownFlags flags
See TownFlags.
Definition town.h:78
TownCache cache
Container for all cacheable data.
Definition town.h:67
TypedIndexContainer< std::array< uint8_t, MAX_COMPANIES >, CompanyID > unwanted
how many months companies aren't wanted by towns (bribe)
Definition town.h:86
CompanyID exclusivity
which company has exclusivity
Definition town.h:87
ValidHistoryMask valid_history
Mask of valid history records.
Definition town.h:135
void InitializeLayout(TownLayout layout)
Assign the town layout.
Definition town_cmd.cpp:190
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
Definition town.h:202
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:88
void UpdateVirtCoord()
Resize the sign (label) of the town after it changes population.
Definition town_cmd.cpp:387
AcceptedCargoes::const_iterator GetCargoAccepted(CargoType cargo) const
Get iterator to the storage for an accepted cargo.
Definition town.h:173
EnumIndexArray< TransportedCargoStat< uint16_t >, TownAcceptanceEffect, TownAcceptanceEffect::End > received
Cargo statistics about received cargotypes.
Definition town.h:133
CompanyMask have_ratings
which companies have a rating
Definition town.h:85
~Town()
Destroy the town.
Definition town_cmd.cpp:115
AcceptedCargoes accepted
Cargo statistics about accepted cargo.
Definition town.h:132
TypedIndexContainer< std::array< int16_t, MAX_COMPANIES >, CompanyID > ratings
ratings of each company for this town
Definition town.h:89
std::vector< SuppliedCargo > SuppliedCargoes
Type for storage of all supplied cargo history.
Definition town.h:128
uint16_t growth_rate
town growth rate
Definition town.h:194
StationList stations_near
NOSAVE: List of nearby stations.
Definition town.h:189
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:175
uint8_t road_build_months
fund road reconstruction in action?
Definition town.h:197
EnumIndexArray< uint32_t, TownAcceptanceEffect, TownAcceptanceEffect::End > goal
Amount of cargo required for the town to grow.
Definition town.h:134
uint16_t townnametype
The style of the name.
Definition town.h:72
Specialised ViewportSign that tracks whether it is valid for entering into a Kdtree.
Basic types related to subsidies.
EnumBitSet< PartOfSubsidy, uint8_t > PartsOfSubsidy
Bitset of PartOfSubsidy elements.
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
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:32
void ChangeTownRating(Town *t, int add, int max, DoCommandFlags flags)
Changes town rating of the current company.
void ResetHouses()
Reset and initialise house specs.
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
Definition town.h:274
@ TunnelBridgeRemove
Removal of a tunnel or bridge owned by the town.
Definition town.h:276
@ RoadRemove
Removal of a road owned by the town.
Definition town.h:275
@ End
End marker.
Definition town.h:277
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
uint GetDefaultTownsForMapSize()
Calculate the number of towns which should be on the map according to the current "town density" newg...
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.
EnumBitSet< TownFlag, uint8_t > TownFlags
Bitset of TownFlag elements.
Definition town.h:49
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:33
TownDirectoryInvalidateWindowData
Special values for town list window for the data parameter of InvalidateWindowData.
Definition town.h:281
EnumBitSet< TownAction, uint8_t > TownActions
Bitset of TownAction elements.
Definition town.h:310
bool GenerateTowns(TownLayout layout, std::optional< uint > number=std::nullopt)
Generate a number of towns with a given layout.
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
Definition town_cmd.cpp:446
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 UpdateTownMaxPass(Town *t)
Update the maximum amount of monthly 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:837
uint8_t GetTownActionCost(TownAction action)
Get cost factors for a TownAction.
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Definition town.h:29
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition town_cmd.cpp:419
RoadType GetTownRoadType()
Get the road type that towns should build at this current moment.
Definition town_cmd.cpp:935
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
TownAction
Town actions of a company.
Definition town.h:297
@ RoadRebuild
Rebuild the roads.
Definition town.h:301
@ Bribe
Try to bribe the council.
Definition town.h:305
@ AdvertiseLarge
Large advertising campaign.
Definition town.h:300
@ BuildStatue
Build a statue.
Definition town.h:302
@ BuyRights
Buy exclusive transport rights.
Definition town.h:304
@ FundBuildings
Fund new buildings.
Definition town.h:303
@ AdvertiseMedium
Medium advertising campaign.
Definition town.h:299
@ AdvertiseSmall
Small advertising campaign.
Definition town.h:298
CommandCost CheckforTownRating(DoCommandFlags flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
HouseZone GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
bool CheckTownRoadTypes()
Check if towns are able to build road.
Definition town_cmd.cpp:985
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:35
TownCouncilAttitudes
Settings for town council attitudes.
Definition town.h:263
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.
TownFlag
Flags controlling various town behaviours.
Definition town.h:41
@ HasChurch
There can be only one church by town.
Definition town.h:43
@ CustomGrowth
Growth rate is controlled by GS.
Definition town.h:45
@ HasStadium
There can be only one stadium by town.
Definition town.h:44
@ IsGrowing
Conditions for town growth are met. Grow according to Town::growth_rate.
Definition town.h:42
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition town.h:34
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlags flags)
Checks whether the local authority allows construction of a new station (rail, road,...
void MakeDefaultName(T *obj)
Set the default name for a depot/waypoint.
Definition town.h:334
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition town_cmd.cpp:411
Map 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:83
Types related to viewports.