64#include "script/api/script_event_types.hpp"
70#include "table/strings.h"
76TownPool _town_pool(
"Town");
80TownKdtree _town_kdtree{};
82void RebuildTownKdtree()
84 std::vector<TownID> townids;
86 townids.push_back(town->index);
88 _town_kdtree.Build(townids.begin(), townids.end());
131 assert(i->town !=
this);
136 assert(o->town !=
this);
161 for (
auto &psa : this->psa_list) {
164 this->psa_list.clear();
212 size_t index = std::numeric_limits<size_t>::max();
228void Town::FillCachedName()
const
245static void TownDrawHouseLift(
const TileInfo *ti)
250typedef void TownDrawTileProc(
const TileInfo *ti);
251static TownDrawTileProc *
const _town_draw_tile_procs[1] = {
265 DrawNewHouseTile(ti, house_id);
293 if (proc >= 0) _town_draw_tile_procs[proc](ti);
325 AnimateNewHouseTile(tile);
356 pos += (pos < dest) ? 1 : -1;
375 if (_town_kdtree.Count() == 0)
return false;
385 if (this->
cache.sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(this->
index));
387 std::string town_string;
389 town_string =
GetString(
_settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_CITY_POP : STR_VIEWPORT_TOWN_CITY, this->index, this->cache.population);
391 town_string =
GetString(
_settings_client.gui.population_in_label ? STR_VIEWPORT_TOWN_POP : STR_TOWN_NAME, this->index, this->cache.population);
394 this->
cache.sign.UpdatePosition(pt.
x, pt.
y - 24 * ZOOM_BASE,
399 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeTown(this->
index));
408 t->UpdateVirtCoord();
416 t->cached_name.clear();
459 bool covers_area = st->TileIsInCatchment(tile);
460 if (flags.
Any(BUILDING_2_TILES_Y)) covers_area |= st->TileIsInCatchment(tile +
TileDiffXY(0, 1));
461 if (flags.
Any(BUILDING_2_TILES_X)) covers_area |= st->TileIsInCatchment(tile +
TileDiffXY(1, 0));
462 if (flags.
Any(BUILDING_HAS_4_TILES)) covers_area |= st->TileIsInCatchment(tile +
TileDiffXY(1, 1));
484 TriggerHouseAnimation_ConstructionStageChanged(tile,
false);
518 if (amount == 0)
return;
522 amount = (amount + 1) >> 1;
527 if (amount == 0)
return;
530 auto &supplied = t->GetOrCreateCargoSupplied(cargo);
531 supplied.history[THIS_MONTH].production += amount;
532 supplied.history[THIS_MONTH].transported += MoveGoodsToStation(cargo, amount, {t->index,
SourceType::Town}, stations.
GetStations());;
545 uint32_t r = Random();
546 if (
GB(r, 0, 8) < rate) {
566 uint32_t r = Random();
569 int genmax = (rate + 7) / 8;
570 uint32_t genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
604 Town *t = Town::GetByTile(tile);
605 uint32_t r = Random();
610 for (uint i = 0; i < 256; i++) {
618 uint amt =
GB(callback, 0, 8);
619 if (amt == 0)
continue;
651 CanDeleteHouse(tile) &&
659 if (
GB(r, 24, 8) >= 12) {
667 int x =
Clamp(grid_pos.
x, 0, 1);
668 int y =
Clamp(grid_pos.
y, 0, 1);
691 if (!CanDeleteHouse(tile))
return CommandCost(STR_ERROR_BUILDING_IS_PROTECTED);
699 Town *t = Town::GetByTile(tile);
704 if (rating > RATING_MAXIMUM) {
705 return CommandCost(STR_ERROR_BUILDING_IS_PROTECTED);
727 Town *t = Town::GetByTile(tile);
730 for (uint i = 0; i < 256; i++) {
743 produced[cs->Index()]++;
748 produced[cs->Index()]++;
764 acceptance[cargo] += amount;
765 always_accepted.
Set(cargo);
782 for (uint8_t i = 0; i <
lengthof(accepts); i++) {
814 for (uint8_t i = 0; i <
lengthof(accepts); i++) {
853 std::array<int32_t, 1> regs100;
857 if (callback_res == 0x40F) {
859 }
else if (callback_res > 0x400) {
864 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
869 if (!house_completed) {
871 td.
str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
937 const uint16_t assume_max_speed = 50;
948 if (best !=
nullptr) {
988 if (min_date < INT32_MAX) {
991 GetEncodedString(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_YET_EXPLANATION, min_date),
1022 dist_multi = (dist_multi + 1) * 4;
1023 for (uint pos = 4; pos < dist_multi; pos++) {
1028 if (pos & 2) cur += tid_lt[2];
1071 if (desired_slope != cur_slope &&
ComplementSlope(desired_slope) != cur_slope) {
1088static bool TerraformTownTile(
TileIndex tile,
Slope edges,
bool dir)
1098static void LevelTownLand(
TileIndex tile)
1128 default: NOT_REACHED();
1147 default: rb_template =
ROAD_ALL;
break;
1295 uint bridge_length = 0;
1302 const uint TOWN_BRIDGE_LENGTH_CAP = 11;
1303 uint base_bridge_length = 5;
1304 uint max_bridge_length = std::min(t->
cache.
population / 1000 + base_bridge_length, TOWN_BRIDGE_LENGTH_CAP);
1309 if (bridge_length++ >= base_bridge_length) {
1313 bridge_tile += delta;
1317 if (bridge_length++ >= max_bridge_length) {
1321 bridge_tile += delta;
1326 if (bridge_length == 1)
return false;
1346 for (uint8_t times = 0; times <= 22; times++) {
1382 int max_tunnel_length = 0;
1388 for (uint8_t tiles = 0; tiles < 4; tiles++) {
1392 slope_tile += delta;
1399 max_tunnel_length = 5;
1402 uint8_t tunnel_length = 0;
1407 if (tunnel_length++ >= max_tunnel_length)
return false;
1408 tunnel_tile += delta;
1413 if (tunnel_length == 1)
return false;
1436 static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1439 for (
const auto &ptr : tiles) {
1512 if (cur_rb.
None()) {
1524 default: NOT_REACHED();
1571 default: NOT_REACHED();
1584 bool allow_house =
true;
1601 if (cur_rb.
Any(target_rb)) {
1613 switch (cur_rb.
base()) {
1643 default: NOT_REACHED();
1653 allow_house = !rcmd.
Any(target_rb);
1677 if (
Chance16(1, 6)) LevelTownLand(house_tile);
1733 return target_rb.
Any();
1754 return target_rb.
Any(back_rb) && target_rb.
Reset(back_rb).Any();
1810 if (cur_rb.
None())
return false;
1819 if (cur_rb.
None())
return false;
1824 }
while (!cur_rb.
Any(target_bits));
1825 cur_rb.
Reset(target_bits);
1843 }
while (--iterations >= 0);
1857 uint32_t r = Random();
1858 uint a =
GB(r, 0, 2);
1859 uint b =
GB(r, 8, 2);
1894 for (
const auto &ptr : _town_coord_mod) {
1906 for (
const auto &ptr : _town_coord_mod) {
1928 static const std::array<std::array<uint32_t, NUM_HOUSE_ZONES>, 23> _town_squared_town_zone_radius_data = {{
1941 { 81, 36, 25, 0, 9},
1942 { 81, 36, 25, 16, 9},
1943 { 81, 49, 0, 25, 9},
1944 { 81, 64, 0, 25, 9},
1945 { 81, 64, 0, 36, 9},
1946 { 81, 64, 0, 36, 16},
1947 {100, 81, 0, 49, 16},
1948 {100, 81, 0, 49, 25},
1949 {121, 81, 0, 49, 25},
1950 {121, 81, 0, 49, 25},
1951 {121, 81, 0, 49, 36},
1954 if (t->
cache.
num_houses < std::size(_town_squared_town_zone_radius_data) * 4) {
1977 if (production == 0)
continue;
1979 auto &supplied = t->GetOrCreateCargoSupplied(cs->Index());
1980 supplied.history[LAST_MONTH].production = production;
1985 if (production == 0)
continue;
1987 auto &supplied = t->GetOrCreateCargoSupplied(cs->Index());
1988 supplied.history[LAST_MONTH].production = production;
2023 _town_kdtree.Insert(t->index);
2093 return CommandCost(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP);
2098 return CommandCost(STR_ERROR_TOO_CLOSE_TO_ANOTHER_TOWN);
2107 if (check_surrounding) {
2108 constexpr uint SEARCH_DIAMETER = 5;
2110 constexpr uint VALID_TILE_GOAL = (SEARCH_DIAMETER * SEARCH_DIAMETER) / 2;
2114 if (counter == VALID_TILE_GOAL)
break;
2131 bool elevation_similar = (
GetTileMaxZ(t) <= town_height + 1) && (
GetTileZ(t) >= town_height - 1);
2132 if (elevation_similar) counter++;
2135 if (counter < VALID_TILE_GOAL)
return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2149 if (!t->name.empty() && t->name == name)
return false;
2178 if (random_location)
return {
CMD_ERROR, 0, TownID::Invalid() };
2180 return {
CMD_ERROR, 0, TownID::Invalid() };
2184 return {
CMD_ERROR, 0, TownID::Invalid() };
2199 if (!random_location) {
2201 if (ret.
Failed())
return { ret, 0, TownID::Invalid() };
2208 uint8_t mult = city ? city_price_mult[size] : town_price_mult[size];
2213 TownID new_town = TownID::Invalid();
2222 if (random_location) {
2226 DoCreateTown(t, tile, townnameparts, size, city, layout,
true);
2230 old_generating_world.
Restore();
2232 if (t ==
nullptr)
return {
CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN), 0, TownID::Invalid() };
2234 new_town = t->index;
2236 if (!text.empty()) {
2243 assert(!random_location);
2255 return { cost, 0, new_town };
2272 default:
return tile;
2290 default:
return true;
2319 if (dist > max_dist) {
2342 default: NOT_REACHED();
2375 DoCreateTown(t, tile, townnameparts, size, city, layout,
false);
2390 }
while (--attempts != 0);
2402 static const uint8_t num_initial_towns[4] = {5, 11, 23, 46};
2418 uint current_number = 0;
2420 if (number.has_value()) {
2421 total = number.value();
2429 uint32_t townnameparts;
2430 TownNames town_names;
2436 town_names.insert(town->GetCachedName());
2447 bool city = (
_settings_game.economy.larger_towns != 0 && ((city_random_offset + current_number) %
_settings_game.economy.larger_towns) == 0);
2458 RebuildTownKdtree();
2460 if (current_number != 0)
return true;
2496 if (ret.
Failed())
continue;
2522 if (dist < t->cache.squared_town_zone_radius[
to_underlying(i)]) smallest = i;
2545 MakeHouseTile(tile, t->index, counter, stage, type, random_bits, is_protected);
2573 t->stations_near.insert(st);
2662 if ((grid_pos.
x % 3) == 0 || (grid_pos.
y % 3) == 0)
return false;
2666 if ((grid_pos.
x % 4) == 0 || (grid_pos.
y % 4) == 0)
return false;
2699 if ((grid_pos.
x != 2 && grid_pos.
x != -1) ||
2700 (grid_pos.
y != 2 && grid_pos.
y != -1))
return false;
2704 if ((grid_pos.
x & 3) < 2 || (grid_pos.
y & 3) < 2)
return false;
2784 uint8_t construction_counter = 0;
2785 uint8_t construction_stage = 0;
2788 uint32_t construction_random = Random();
2796 construction_counter =
GB(construction_random, 2, 2);
2800 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits, is_protected);
2806 TriggerHouseAnimation_ConstructionStageChanged(tile,
true);
2807 if (size.
Any(BUILDING_2_TILES_Y)) TriggerHouseAnimation_ConstructionStageChanged(tile +
TileDiffXY(0, 1),
true);
2808 if (size.
Any(BUILDING_2_TILES_X)) TriggerHouseAnimation_ConstructionStageChanged(tile +
TileDiffXY(1, 0),
true);
2809 if (size.
Any(BUILDING_HAS_4_TILES)) TriggerHouseAnimation_ConstructionStageChanged(tile +
TileDiffXY(1, 1),
true);
2844 static std::vector<std::pair<HouseID, uint>> probs;
2847 uint probability_max = 0;
2852 if (!hs.building_availability.All(zones) || !hs.enabled || hs.grf_prop.override_id != INVALID_HOUSE_ID)
continue;
2855 if (hs.class_id != HOUSE_NO_CLASS) {
2863 uint cur_prob = hs.probability;
2864 probability_max += cur_prob;
2865 probs.emplace_back(hs.Index(), cur_prob);
2870 while (probability_max > 0) {
2880 for (i = 0; i < probs.size(); i++) {
2881 if (probs[i].second > r)
break;
2882 r -= probs[i].second;
2885 HouseID house = probs[i].first;
2886 probability_max -= probs[i].second;
2889 probs[i] = probs.back();
2913 if (noslope && slope !=
SLOPE_FLAT)
continue;
2925 uint8_t random_bits = Random();
3001 bool house_completed =
_settings_game.economy.place_houses == PlaceHouses::AllowedConstructed;
3002 BuildTownHouse(t, tile, hs, house, Random(), house_completed, is_protected);
3039 bool had_success =
false;
3045 if (c !=
nullptr && limit-- <= 0)
break;
3048 last_error = std::move(ret);
3069 DoClearSquare(tile);
3087 }
else if (
HouseSpec::Get(house - 1)->building_flags.Any(BUILDING_2_TILES_Y)) {
3090 }
else if (
HouseSpec::Get(house - 2)->building_flags.Any(BUILDING_HAS_4_TILES)) {
3093 }
else if (
HouseSpec::Get(house - 3)->building_flags.Any(BUILDING_HAS_4_TILES)) {
3154 bool reset = text.empty();
3171 ClearAllStationCachedNames();
3172 ClearAllIndustryCachedNames();
3186 if (cs->town_acceptance_effect == effect)
return cs;
3213 t->
goal[tae] = goal;
3236 if (!text.empty()) t->
text = text;
3258 if (growth_rate == 0) {
3297 int16_t new_rating =
Clamp(rating, RATING_MINIMUM, RATING_MAXIMUM);
3299 t->
ratings[company_id] = new_rating;
3323 if (grow_amount == 0) {
3328 uint n = amount * 10;
3329 do GrowTown(t, modes);
while (--n);
3333 for (; grow_amount > 0; grow_amount--) {
3335 for (uint i = 0; i < 25; i++)
if (
GrowTown(t, modes))
break;
3360 if (st->town == t) {
3364 CommandCost ret = Command<Commands::LandscapeClear>::Do(flags, st->airport.tile);
3365 if (ret.
Failed())
return ret;
3385 CommandCost ret = Command<Commands::LandscapeClear>::Do(flags, current_tile);
3386 if (ret.
Failed())
return ret;
3392 bool try_clear =
false;
3428 CommandCost ret = Command<Commands::LandscapeClear>::Do(flags, current_tile);
3429 if (ret.
Failed())
return ret;
3435 _town_kdtree.Remove(t->index);
3436 if (t->
cache.
sign.
kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeTown(t->index));
3454 static const uint8_t town_action_costs[] = {
3455 2, 4, 9, 35, 48, 53, 117, 175
3459 assert(
to_underlying(action) < std::size(town_action_costs));
3538 return Command<Commands::LandscapeClear>::Do({}, tile).Succeeded();
3552 static const int STATUE_NUMBER_INNER_TILES = 25;
3555 uint tile_count = 0;
3566 best_position = tile;
3573 if (tile_count <= STATUE_NUMBER_INNER_TILES) {
3576 best_position = tile;
3580 if (tile_count == STATUE_NUMBER_INNER_TILES && best_position !=
INVALID_TILE)
break;
3585 best_position = tile;
3709static TownActionProc *
const _town_action_proc[] = {
3747 if (t->
ratings[cid] >= RATING_BRIBE_MAXIMUM) {
3793 if (ret.
Failed())
return ret;
3802template <
typename Func>
3803static void ForAllStationsNearTown(
Town *t, Func func)
3811 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[to_underlying(HouseZone::TownEdge)]) {
3830 ForAllStationsNearTown(t, [&](
const Station *st) {
3831 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3834 t->
ratings[st->
owner] = std::min<int>(new_rating, INT16_MAX);
3839 t->
ratings[st->
owner] = std::max(new_rating, INT16_MIN);
3845 for (
auto it = t->
ratings.begin(); it != t->
ratings.end(); ++it) {
3846 *it =
Clamp(*it, RATING_MINIMUM, RATING_MAXIMUM);
3877 ForAllStationsNearTown(t, [&](
const Station * st) {
3878 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3898 static const uint16_t _grow_count_values[2][6] = {
3899 { 120, 120, 120, 100, 80, 60 },
3900 { 320, 420, 300, 220, 160, 100 }
3908 m >>= growth_multiplier;
3943 switch (t->
goal[i]) {
4002 TownID tid = _town_kdtree.FindNearest(
TileX(tile),
TileY(tile));
4025 if (tid == TownID::Invalid()) {
4042 return Town::GetByTile(tile);
4059 static int ref_count = 0;
4061 if (ref_count == 0) {
4066 assert(ref_count > 0);
4100 (
_cheats.magic_bulldozer.value && add < 0)) {
4108 if (rating < max) rating = max;
4113 if (rating > max) rating = max;
4170 uint64_t production = std::accumulate(std::begin(history), std::end(history), 0, [](uint64_t r,
const auto &s) {
return r + s.production; });
4171 uint64_t transported = std::accumulate(std::begin(history), std::end(history), 0, [](uint64_t r,
const auto &s) {
return r + s.transported; });
4172 auto count = std::size(history);
4184 uint64_t accepted = std::accumulate(std::begin(history), std::end(history), 0, [](uint64_t r,
const auto &s) {
return r + s.accepted; });
4185 auto count = std::size(history);
4194 if (t->road_build_months != 0) t->road_build_months--;
4195 if (t->fund_buildings_months != 0) t->fund_buildings_months--;
4197 if (t->exclusive_counter != 0) {
4198 if (--t->exclusive_counter == 0) t->exclusivity = CompanyID::Invalid();
4203 if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
4211 for (
auto &received : t->received) received.NewMonth();
4240 bool allow_terraform =
true;
4255 return Command<Commands::LandscapeClear>::Do(flags, tile);
4272std::span<const DrawBuildingsTileStruct> GetTownDrawTileData()
Base functions for all AIs.
@ AT_OILRIG
Oilrig airport.
void AddAnimatedTile(TileIndex tile, bool mark_dirty)
Add the given tile to the animated tile table (if it does not exist yet).
void DeleteAnimatedTile(TileIndex tile, bool immediate)
Stops animation on the given tile.
@ None
Tile is not animated.
Functions related to autoslope.
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Axis GetBridgeAxis(Tile t)
Get the axis of the bridge that goes over the tile.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
static constexpr CargoLabel CT_FOOD
Cargo label for food.
CargoType
Cargo slots to indicate a cargo type within a game.
CargoType GetCargoTypeByLabel(CargoLabel label)
Get cargo assigned to a label.
static const uint TOWN_PRODUCTION_DIVISOR
By what factor divide town production.
TownProductionEffect
Town effect when producing cargo.
@ Mail
Cargo behaves mail-like for production.
@ Passengers
Cargo behaves passenger-like for production.
TownAcceptanceEffect
Town growth effect when delivering cargo.
@ Food
Cargo behaves food/fizzy-drinks-like.
@ Water
Cargo behaves water-like.
@ End
End of town effects.
Cheats _cheats
All the cheats.
Types related to cheating.
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=CompanyID::Invalid())
Broadcast a new event to all active AIs.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
Container for an encoded string, created by GetEncodedString.
Iterate a range of enum values.
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
An interval timer will fire every interval, and will continue to fire until it is deleted.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
TimerGameCalendar::Date introduction_date
Introduction date.
RoadTypeFlags flags
Bit mask of road type flags.
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Generate TileIndices around a center tile or tile area, with increasing distance.
Structure contains cached list of stations nearby.
const StationList & GetStations()
Run a tile loop to find stations around a tile, on demand.
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).
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static constexpr TimerGame< struct Calendar >::Date MAX_DATE
static Month month
Current month (0..11).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
StrongType::Typedef< int32_t, DateTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Date
Map accessors for 'clear' tiles.
ClearGround GetClearGround(Tile t)
Get the type of clear tile.
CommandFlags GetCommandFlags(Commands cmd)
Get the command flags associated with the given command.
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Functions related to commands.
CommandCost & ExtractCommandCost(Tret &ret)
Extract the CommandCost from a command proc result.
static constexpr DoCommandFlags CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Auto
don't allow building on structures
@ NoModifyTownRating
do not change town rating
@ NoWater
don't allow building on water
@ Execute
execute the given command
@ NoTestTownRating
town rating does not disallow you from building
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
static constexpr Owner OWNER_DEITY
The object is owned by a superuser / goal script.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
static constexpr Owner OWNER_NONE
The tile has no ownership.
Base for all depots (except hangars).
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
@ Right90
90 degrees right
DiagDirection
Enumeration for diagonal directions.
@ End
Used for iterations.
Prices _price
Prices and also the fractional part.
bool EconomyIsInRecession()
Is the economy in recession?
uint ScaleByCargoScale(uint num, bool town)
Scale a number by the cargo scale setting.
@ Construction
Construction costs.
@ Terraform
Price for terraforming land, e.g. rising, lowering and flattening.
@ BuildFoundation
Price for building foundation under other constructions e.g. roads, rails, depots,...
@ TownAction
Price for interaction with local authorities.
@ ClearHouse
Price for destroying houses and other town buildings.
@ BuildTown
Price for funding new towns and cities.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
@ Info
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Base functions for all Games.
bool _generating_world
Whether we are generating the map or not.
Functions related to world/map generation.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
uint8_t HighestSnowLine()
Get the highest possible snow line height, either variable or static.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static const SpriteID SPR_LIFT
void UpdateValidHistory(ValidHistoryMask &valid_history, const HistoryRange &hr, uint cur_month)
Update mask of valid records for a historical data.
Functions for storing historical data.
void RotateHistory(HistoryData< T > &history, ValidHistoryMask valid_history, const HistoryRange &hr, uint cur_month)
Rotate historical data.
Types for storing historical data.
@ BuildingIsHistorical
this house will only appear during town generation in random games, thus the historical
@ BuildingIsProtected
towns and AI will not remove this house, while human players will be able to
@ Size1x1
The building is a single tile.
@ Size2x2
The building is 2x2 tiles.
@ IsAnimated
The building uses animation.
@ NotSloped
The building can only be built on flat land; when not set foundations are placed.
@ Size2x1
The building is 2x1 tiles, i.e. wider on the X-axis.
@ IsChurch
The building functions as a church, i.e. only one can be built in a town.
@ IsStadium
The building functions as a stadium, i.e. only one can be built in a town.
@ Size1x2
The building is 1x2 tiles, i.e. wider on the Y-axis.
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
EnumBitSet< BuildingFlag, uint8_t > BuildingFlags
Bitset of BuildingFlag elements.
EnumBitSet< HouseZone, uint16_t > HouseZones
Bitset of HouseZone elements.
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
HouseZone
Concentric rings of zoning around the centre of a town.
@ TownOuterSuburb
Outer suburbs; roads with pavement.
@ ClimateSubarcticAboveSnow
Building can appear in sub-arctic climate above the snow line.
@ ClimateSubarcticBelowSnow
Building can appear in sub-arctic climate below the snow line.
@ TownInnerSuburb
Inner suburbs; roads with pavement and trees.
@ TownOutskirt
Outskirts of a town; roads without pavement.
@ TownEdge
Edge of the town; roads without pavement.
@ TownCentre
Centre of town; roads with pavement and streetlights.
@ ClimateTemperate
Building can appear in temperate climate.
@ ClimateToyland
Building can appear in toyland climate.
@ ClimateSubtropic
Building can appear in subtropical climate.
uint16_t HouseID
OpenTTD ID of house types.
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
std::tuple< Slope, int > GetFoundationSlope(TileIndex tile)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
const TileTypeProcs _tile_type_town_procs
TileTypeProcs definitions for TileType::Town tiles.
Functions related to OTTD's landscape.
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Command definitions related to landscape (slopes etc.).
@ Arctic
Landscape with snow levels.
@ Toyland
Landscape with funky industries and vehicles.
@ Tropic
Landscape with distinct rainforests and deserts,.
@ Temperate
Base landscape.
#define Point
Macro that prevents name conflicts between included headers.
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
Functions related to maps.
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
static uint TileY(TileIndex tile)
Get the Y component of a tile.
static uint TileX(TileIndex tile)
Get the X component of a tile.
constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset)
Adds a given offset to a tile.
#define RandomTile()
Get a valid random tile.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
int32_t TileIndexDiff
An offset value between two tiles.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
@ FakeTowns
Fake town GrfSpecFeature for NewGRF debugging (parent scope).
@ CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house tile.
@ CBID_HOUSE_CARGO_ACCEPTANCE
Called to decide how much cargo a town building can accept.
@ CBID_HOUSE_AUTOSLOPE
Called to determine if one can alter the ground below a house tile.
@ CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
@ CBID_HOUSE_ALLOW_CONSTRUCTION
Determine whether the house can be built on the specified tile.
@ CBID_HOUSE_ACCEPT_CARGO
Called to determine which cargoes a town building should accept.
@ CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
@ AllowConstruction
decide whether the house can be built on a given tile
@ AcceptCargo
decides accepted types
@ CargoAcceptance
decides amount of cargo acceptance
@ DrawFoundations
decides if default foundations need to be drawn
@ ProduceCargo
custom cargo production
@ Autoslope
decides allowance of autosloping
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
CargoType GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoType.
Cargo support for NewGRFs.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
GRFConfig * GetGRFConfig(GrfID grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Functions/types related to NewGRF debugging.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town.
uint16_t GetHouseCallback(CallbackID callback, uint32_t param1, uint32_t param2, HouseID house_id, Town *town, TileIndex tile, std::span< int32_t > regs100, bool not_yet_constructed, uint8_t initial_random_bits, CargoTypes watched_cargo_triggers, int view)
Get the result of a house callback.
void InitializeBuildingCounts()
Initialise global building counts and all town building counts.
Functions related to NewGRF houses.
StringID GetGRFStringID(GrfID grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Header of Action 04 "universal holder" structure and functions.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
@ General
General news (from towns).
@ IndustryOpen
Opening of industries.
@ Company
Company news item. (Newspaper with face).
@ Normal
Normal news item. (Newspaper with text only).
Functions related to objects.
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=nullptr, uint8_t view=0)
Actually build the object.
static const ObjectType OBJECT_STATUE
Statue in towns.
@ Editor
In the scenario editor.
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
@ INVALID_RAILTYPE
Flag for invalid railtype.
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
@ NoHouses
Bit number for setting this roadtype as not house friendly.
@ TownBuild
Bit number for allowing towns to build this roadtype.
RoadTypes GetMaskForRoadTramType(RoadTramType rtt)
Get the mask for road types of the given RoadTramType.
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
bool UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
Functions used internally by the roads.
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
RoadType GetRoadTypeRoad(Tile t)
Get the road type for RoadTramType being RoadTramType::Road.
static bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
static bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
static bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
bool IsRoadOwner(Tile t, RoadTramType rtt, Owner o)
Check if a specific road type is owned by an owner.
static constexpr RoadBits ROAD_W
Road at the two western edges.
static constexpr RoadBits ROAD_X
Full road along the x-axis (south-west + north-east).
EnumBitSet< RoadBit, uint8_t > RoadBits
Bitset of RoadBit elements.
static constexpr RoadBits ROAD_E
Road at the two eastern edges.
static constexpr RoadBits ROAD_ALL
Full 4-way crossing.
static constexpr RoadBits ROAD_Y
Full road along the y-axis (north-west + south-east).
static constexpr RoadBits ROAD_N
Road at the two northern edges.
RoadType
The different roadtypes we support.
@ INVALID_ROADTYPE
flag for invalid roadtype
@ ROADTYPE_ROAD
Basic road type.
static constexpr RoadBits ROAD_S
Road at the two southern edges.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
ClientSettings _settings_client
The current settings for this game.
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height).
static constexpr Slope RemoveHalftileSlope(Slope s)
Removes a halftile slope from a slope.
bool IsSlopeWithOneCornerRaised(Slope s)
Tests if a specific slope has exactly one corner raised.
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
static constexpr Slope RemoveSteepSlope(Slope s)
Removes a steep flag from a slope.
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
Slope ComplementSlope(Slope s)
Return the complement of a slope.
Slope
Enumeration for the slope-type.
@ SLOPE_W
the west corner of the tile is raised
@ SLOPE_ELEVATED
bit mask containing all 'simple' slopes
@ SLOPE_E
the east corner of the tile is raised
@ SLOPE_S
the south corner of the tile is raised
@ SLOPE_N
the north corner of the tile is raised
@ SLOPE_SW
south and west corner are raised
@ SLOPE_STEEP_W
a steep slope falling to east (from west)
@ SLOPE_NE
north and east corner are raised
@ SLOPE_STEEP_E
a steep slope falling to west (from east)
@ SLOPE_SE
south and east corner are raised
@ SLOPE_NW
north and west corner are raised
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
@ SLOPE_STEEP_S
a steep slope falling to north (from south)
Foundation
Enumeration for Foundations.
@ Leveled
The tile is leveled up to a flat slope.
@ None
The tile has no foundation, the slope remains unchanged.
@ Town
Source/destination is a town.
Base classes/functions for stations.
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
Functions related to stations.
Declarations for accessing the k-d tree of stations.
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
Axis GetDriveThroughStopAxis(Tile t)
Gets the axis of the drive through stop.
DiagDirection GetBayRoadStopDir(Tile t)
Gets the direction the bay road stop entrance points towards.
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
@ Airport
Station with an airport.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
Owner owner
The owner of this station.
Class for storing amounts of cargo.
static void InvalidateAllFrom(Source src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
Specification of a cargo type.
static EnumIndexArray< std::vector< const CargoSpec * >, TownProductionEffect, TownProductionEffect::End > town_production_cargoes
List of cargo specs for each Town Product Effect.
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
uint32_t build_object_limit
Amount of tiles we can (still) build objects on (times 65536). Also applies to buying land and placin...
This structure is the same for both Industries and Houses.
uint8_t draw_proc
This allows to specify a special drawing procedure.
Information about GRF, used in the game and (part of it) in savegames.
std::string GetName() const
Get the name of this grf.
GrfID grfid
grfid that introduced this entity.
const struct GRFFile * grffile
grf file that introduced this entity
bool HasGrfFile() const
Test if this entity was introduced by NewGRF.
Stores station stats for a single cargo.
uint8_t rating
Station rating for this cargo.
CargoType accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
SubstituteGRFFileProps grf_prop
Properties related the the grf file.
uint8_t removal_cost
cost multiplier for removing it
uint8_t mail_generation
mail generation multiplier (tile based, as the acceptances below)
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Money GetRemovalCost() const
Get the cost for removing this house.
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
TimerGameCalendar::Year max_year
last year it can be built
HouseCallbackMasks callback_mask
Bitmask of house callbacks that have to be called.
uint16_t remove_rating_decrease
rating decrease if removed
uint8_t population
population (Zero on other tiles in multi tile house.)
HouseExtraFlags extra_flags
some more flags
uint8_t cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
HouseID Index() const
Gets the index of this spec.
StringID building_name
building name
uint8_t minimum_life
The minimum number of years this house will survive before the town rebuilds it.
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
Defines the internal data of a functional industry.
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
static uint ScaleBySize(uint n)
Scales the given value by the map size, where the given value is for a 256 by 256 map.
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
static uint ScaleByLandProportion(uint n)
Scales the given value by the number of water tiles.
static uint Size()
Get the size of the map.
An object, such as transmitter, on the map.
ObjectType type
Type of the object.
Town * town
Town the object is built in.
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
SpriteID sprite
The 'real' sprite.
PaletteID pal
The palette (use PAL_NONE) if not needed).
static Pool::IterateWrapper< Town > Iterate(size_t from=0)
static size_t GetPoolSize()
static T * Create(Targs &&... args)
static Town * Get(auto index)
static size_t GetNumItems()
static bool CanAllocateItem(size_t n=1)
static bool IsValidID(auto index)
static bool CleaningPool()
static Company * GetIfValid(auto index)
static constexpr size_t MAX_SIZE
A location from where cargo can come from (or go to).
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
uint16_t subst_id
The id of the entity to replace.
Tile description for the 'land area information' tool.
std::optional< std::string > grf
newGRF used for the tile contents
StringID str
Description of the tile.
std::array< Owner, 4 > owner
Name of the owner(s).
uint64_t dparam
Parameter of the str string.
std::optional< bool > town_can_upgrade
Whether the town can upgrade this house during town growth.
A pair-construct of a TileIndexDiff.
int16_t x
The x value of the coordinate.
int16_t y
The y value of the coordinate.
Tile information, used while rendering the tile.
Slope tileh
Slope of the tile.
TileIndex tile
Tile index.
Set of callback functions for performing tile operations of a given tile type.
uint32_t population
Current population of people.
uint32_t num_houses
Amount of houses.
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
std::array< uint32_t, NUM_HOUSE_ZONES > squared_town_zone_radius
UpdateTownRadius updates this given the house count.
Struct holding parameters used to generate town name.
GrfID grfid
newgrf ID (0 if not used)
uint16_t type
town name style
Individual data point for accepted cargo history.
EncodedString text
General text with additional information.
bool larger_town
if this is a larger town and should grow more quickly
CompanyMask statues
which companies have a statue?
uint16_t time_until_rebuild
time until we rebuild a house
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
TileIndex xy
town center tile
uint8_t fund_buildings_months
fund buildings program in action?
TownLayout layout
town specific road layout
static Town * GetRandom()
Return a random valid town.
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Town(TownID index, TileIndex tile=INVALID_TILE)
Creates a new town.
GrfID townnamegrfid
NewGRF id that contains the name. O is not used.
uint16_t grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
uint32_t townnameparts
Random number that give unique town name when passed to generator.
TownFlags flags
See TownFlags.
TownCache cache
Container for all cacheable data.
TypedIndexContainer< std::array< uint8_t, MAX_COMPANIES >, CompanyID > unwanted
how many months companies aren't wanted by towns (bribe)
CompanyID exclusivity
which company has exclusivity
void InitializeLayout(TownLayout layout)
Assign the town layout.
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
uint8_t exclusive_counter
months till the exclusivity expires
void UpdateVirtCoord()
Resize the sign (label) of the town after it changes population.
EnumIndexArray< TransportedCargoStat< uint16_t >, TownAcceptanceEffect, TownAcceptanceEffect::End > received
Cargo statistics about received cargotypes.
CompanyMask have_ratings
which companies have a rating
TypedIndexContainer< std::array< int16_t, MAX_COMPANIES >, CompanyID > ratings
ratings of each company for this town
uint16_t growth_rate
town growth rate
StationList stations_near
NOSAVE: List of nearby stations.
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool.
uint8_t road_build_months
fund road reconstruction in action?
EnumIndexArray< uint32_t, TownAcceptanceEffect, TownAcceptanceEffect::End > goal
Amount of cargo required for the town to grow.
uint16_t townnametype
The style of the name.
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
Representation of a waypoint.
void DeleteSubsidyWith(Source source)
Delete the subsidies associated with a given cargo source type and id.
Functions related to subsidies.
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
static uint TileHeight(Tile tile)
Returns the height of a tile.
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
bool IsValidTile(Tile tile)
Checks if a tile is valid.
uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
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.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
static constexpr uint TILE_SIZE
Tile size in world coordinates.
@ TunnelBridge
Tunnel entry/exit and bridge heads.
@ Station
A tile of a station or airport.
@ Object
Contains objects such as transmitters and owned land.
@ Industry
Part of an industry.
@ Railway
A tile with railway.
@ Void
Invisible tiles at the SW and SE border.
@ Trees
Tile with one or more trees.
@ House
A house by a town.
@ Road
A tile with road and/or tram tracks.
@ Clear
A tile without any structures, i.e. grass, rocks, farm fields etc.
OrthoDiagonalTileArea CreateOrthoDiagonalArea(TileIndex corner1, TileIndex corner2, bool diagonal)
Create an Orthogonal/Diagonal tile area wrapper.
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Type for iterating a sprial tile area.
Type for storing the 'area' of something uses on the map.
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount).
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
EnumBitSet< TownFlag, uint8_t > TownFlags
Bitset of TownFlag elements.
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount).
EnumBitSet< TownAction, uint8_t > TownActions
Bitset of TownAction elements.
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
TownAction
Town actions of a company.
@ RoadRebuild
Rebuild the roads.
@ Bribe
Try to bribe the council.
@ BuildStatue
Build a statue.
@ BuyRights
Buy exclusive transport rights.
@ FundBuildings
Fund new buildings.
@ HasChurch
There can be only one church by town.
@ CustomGrowth
Growth rate is controlled by GS.
@ HasStadium
There can be only one stadium by town.
@ IsGrowing
Conditions for town growth are met. Grow according to Town::growth_rate.
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding road allows to build a house here.
static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
Checks if a house of size 2x2 can be built at this tile.
std::tuple< CommandCost, Money, TownID > CmdFoundTown(DoCommandFlags flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
Create a new town.
void ChangeTownRating(Town *t, int add, int max, DoCommandFlags flags)
Changes town rating of the current company.
HouseZones GetClimateMaskForLandscape()
Get the HouseZones climate mask for the current landscape type.
static bool GrowTownAtRoad(Town *t, TileIndex tile, TownExpandModes modes)
Try to grow a town at a given road tile.
static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoTypes &always_accepted)
Tile callback function signature for obtaining cargo acceptance of a tile.
static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlags flags)
Perform the "small advertising campaign" town action.
static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
Tile callback function signature of the terraforming callback.
static CommandCost TownActionFundBuildings(Town *t, DoCommandFlags flags)
Perform the "fund new buildings" town action.
static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
static CommandCost TownActionBuildStatue(Town *t, DoCommandFlags flags)
Perform a 9x9 tiles circular search from the center of the town in order to find a free tile to place...
static CommandCost TownActionBribe(Town *t, DoCommandFlags flags)
Perform the "bribe" town action.
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
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.
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
Get a list of available town authority actions.
static CommandCost TownActionBuyRights(Town *t, DoCommandFlags flags)
Perform the "buy exclusive transport rights" town action.
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
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.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
TownGrowthResult
The possible states of town growth.
@ Continue
The town hasn't grown yet, but try again.
@ Succeed
The town has grown.
@ SearchStopped
There is a reason not to try growing the town now.
static bool CanRoadContinueIntoNextTile(const Town *t, const TileIndex tile, const DiagDirection road_dir)
Checks if a town road can be continued into the next tile.
static bool TryBuildTownHouse(Town *t, TileIndex tile, TownExpandModes modes)
Tries to build a house at this tile.
static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
Updates town grow counter after growth rate change.
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
static bool IsNeighbourRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
static bool _generating_town
Set if a town is being generated.
static void MakeTownHouse(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool is_protected)
Write house information into the map.
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope, TownExpandModes modes)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
static void TileLoop_Town(TileIndex tile)
Tile callback function signature for running periodic tile updates.
static bool CanBuildHouseHere(TileIndex tile, bool noslope)
Check if a house can be built here, based on slope, whether there's a bridge above,...
static void AddProducedCargo_Town(TileIndex tile, CargoArray &produced)
Tile callback function signature for obtaining the produced cargo of a tile.
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile, TownExpandModes modes)
Checks if the current town layout allows building here.
bool GenerateTowns(TownLayout layout, std::optional< uint > number)
Generate a number of towns with a given layout.
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
CommandCost CmdDoTownAction(DoCommandFlags flags, TownID town_id, TownAction action)
Do a town action.
static void TownGenerateCargoBinomial(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the binomial algorithm.
static void UpdateTownRating(Town *t)
Monthly callback to update town and station ratings.
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile, TownExpandModes modes)
Checks if the current town layout allows a 2x2 building here.
static void AdvanceHouseConstruction(TileIndex tile)
Increase the construction stage of a house.
static bool TownCanGrowRoad(TileIndex tile)
Test if town can grow road onto a specific tile.
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
Grows the town with a tunnel.
static std::map< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlags flags)
Tile callback function signature for clearing a tile.
static bool CheckClearTile(TileIndex tile)
Check whether the land can be cleared.
static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlags flags)
Perform the "medium advertising campaign" town action.
static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the original algorithm.
static void ClearMakeHouseTile(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool is_protected)
Clears tile and builds a house or house part.
void UpdateTownMaxPass(Town *t)
Update the maximum amount of monthly passengers and mail for a town, based on its population.
static void ChangePopulation(Town *t, int mod)
Change the town's population as recorded in the town cache, town label, and town directory.
Town::SuppliedHistory SumHistory(std::span< const Town::SuppliedHistory > history)
Sum history for town supplied cargo.
CargoArray GetAcceptedCargoOfHouse(const HouseSpec *hs)
Get accepted cargo of a house prototype.
Town * TryGenerateNamedTownAroundTile(TileIndex target_tile, TownSize size, bool city, TownLayout layout, std::string_view name)
Try to generate a named town around a tile.
static void AddAcceptedCargoSetMask(CargoType cargo, uint amount, CargoArray &acceptance, CargoTypes &always_accepted)
Fill cargo acceptance array and always_accepted mask, if cargo type is valid.
static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
static Town * CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
Create a random town somewhere in the world.
static void RemoveNearbyStations(Town *t, TileIndex tile, BuildingFlags flags)
Remove stations from nearby station list if a town is no longer in the catchment area of each.
static bool IsUniqueTownName(std::string_view name)
Verifies this custom name is unique.
uint8_t GetTownActionCost(TownAction action)
Get cost factors for a TownAction.
static const IntervalTimer< TimerGameEconomy > _economy_towns_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Town}, [](auto) { for(Town *t :Town::Iterate()) { if(t->road_build_months !=0) t->road_build_months--;if(t->fund_buildings_months !=0) t->fund_buildings_months--;if(t->exclusive_counter !=0) { if(--t->exclusive_counter==0) t->exclusivity=CompanyID::Invalid();} for(const Company *c :Company::Iterate()) { if(t->unwanted[c->index] > 0) t->unwanted[c->index]--;} UpdateValidHistory(t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);for(auto &s :t->supplied) RotateHistory(s.history, t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);for(auto &a :t->accepted) RotateHistory(a.history, t->valid_history, HISTORY_YEAR, TimerGameEconomy::month);for(auto &received :t->received) received.NewMonth();UpdateTownGrowth(t);UpdateTownRating(t);SetWindowDirty(WindowClass::TownView, t->index);} })
Economy monthly timer for towns.
CommandCost CmdTownSetText(DoCommandFlags flags, TownID town_id, const EncodedString &text)
Set a custom text in the Town window.
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
CommandCost CmdTownGrowthRate(DoCommandFlags flags, TownID town_id, uint16_t growth_rate)
Change the growth rate of the town.
static TownGrowthResult GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1, TownExpandModes modes)
Grows the given town.
static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlags flags)
Perform the "local road reconstruction" town action.
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
CommandCost CmdDeleteTown(DoCommandFlags flags, TownID town_id)
Delete a town (scenario editor or worldgen only).
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Tile callback function signature for getting the foundation of a tile.
static TimerGameCalendar::Date GetTownRoadTypeFirstIntroductionDate()
Get the calendar date of the earliest town-buildable road type.
static void AnimateTile_Town(TileIndex tile)
Tile callback function signature for animating a tile.
CommandCost CmdPlaceHouse(DoCommandFlags flags, TileIndex tile, HouseID house, bool is_protected, bool replace)
Place an individual house.
RoadType GetTownRoadType()
Get the road type that towns should build at this current moment.
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile, ignoring depot and bay road stops.
CommandCost CmdRenameTown(DoCommandFlags flags, TownID town_id, const std::string &text)
Rename a town (server-only).
CommandCost CmdTownCargoGoal(DoCommandFlags flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
Change the cargo goal of a town.
static void GetTileDesc_Town(TileIndex tile, TileDesc &td)
Tile callback function signature for obtaining a tile description.
static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Actually create a town.
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.
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second, TownExpandModes modes)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
static CommandCost TownCanBePlacedHere(TileIndex tile, bool check_surrounding)
Check if it's possible to place a town on a given tile.
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
Check if a town 'owns' a bridge.
void OnTick_Town()
Iterate through all towns and call their tick handler.
static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlags flags)
Perform the "large advertising campaign" town action.
bool CheckTownRoadTypes()
Check if towns are able to build road.
static bool GrowTown(Town *t, TownExpandModes modes)
Grow the town.
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
static void AdvanceSingleHouseConstruction(TileIndex tile)
Helper function for house construction stage progression.
static void TownTickHandler(Town *t)
Handle the town tick for a single town, by growing the town if desired.
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
static bool _town_rating_test
If true, town rating is in test-mode.
CommandCost CmdTownRating(DoCommandFlags flags, TownID town_id, CompanyID company_id, int16_t rating)
Change the rating of a company in a town.
void UpdateTownRadius(Town *t)
Update the cached town zone radii of a town, based on the number of houses.
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile, TownExpandModes modes)
Grows the town with an extra house.
void AddAcceptedCargoOfHouse(TileIndex tile, HouseID house, const HouseSpec *hs, Town *t, CargoArray &acceptance, CargoTypes &always_accepted)
Determine accepted cargo for a house.
static bool TownAllowedToBuildRoads(TownExpandModes modes)
Check if the town is allowed to build roads.
CommandCost CmdExpandTown(DoCommandFlags flags, TownID town_id, uint32_t grow_amount, TownExpandModes modes)
Expand a town (scenario editor only).
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
static RoadBits GenRandomRoadBits()
Generate a random road block.
static bool CheckBuildHouseSameZ(TileIndex tile, int z, bool noslope)
Check if a tile where we want to build a multi-tile house has an appropriate max Z.
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlags flags)
Checks whether the local authority allows construction of a new station (rail, road,...
static bool CanFollowRoad(TileIndex tile, DiagDirection dir, TownExpandModes modes)
Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
static void BuildTownHouse(Town *t, TileIndex tile, const HouseSpec *hs, HouseID house, uint8_t random_bits, bool house_completed, bool is_protected)
Build a house at this tile.
static void TownGenerateCargo(Town *t, CargoType cargo, uint amount, StationFinder &stations, bool affected_by_recession)
Generate cargo for a house, scaled by the current economy scale.
static void DrawTile_Town(TileInfo *ti)
Tile callback function signature for drawing a tile and its contents to the screen.
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
CommandCost CmdPlaceHouseArea(DoCommandFlags flags, TileIndex tile, TileIndex start_tile, HouseID house, bool is_protected, bool replace, bool diagonal)
Construct multiple houses in an area.
Command definitions related to towns.
Declarations for accessing the k-d tree of towns.
Sprites to use and how to display them for town tiles.
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
void IncrementHouseAge(Tile t)
Increments the age of the house.
void HaltLift(Tile t)
Stop the lift of this animated house from moving.
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
void ResetHouseAge(Tile t)
Sets the age of the house to zero.
void MakeHouseTile(Tile t, TownID tid, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits, bool house_protected)
Make the tile a house.
void IncHouseConstructionTick(Tile t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits,...
uint8_t GetLiftPosition(Tile t)
Get the position of the lift on this animated house.
bool IsHousePlayerProtected(Tile t)
Check if a house is protected by a player from removal by towns.
void SetLiftDestination(Tile t, uint8_t dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit.
TimerGameCalendar::Year GetHouseAge(Tile t)
Get the age of the house.
void SetLiftPosition(Tile t, uint8_t pos)
Set the position of the lift on this animated house.
uint8_t GetLiftDestination(Tile t)
Get the current destination for this lift.
uint8_t GetHouseBuildingStage(Tile t)
House Construction Scheme.
TownID GetTownIndex(Tile t)
Get the index of which town this house/street is attached to.
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
bool LiftHasDestination(Tile t)
Check if the lift of this animated house has a destination.
bool IsHouseCompleted(Tile t)
Get the completion of this house.
uint8_t GetHouseConstructionTick(Tile t)
Gets the construction stage of a house.
static constexpr int RATING_GROWTH_UP_STEP
when a town grows, all companies have rating increased a bit ...
static constexpr int RATING_INITIAL
initial rating
static constexpr int RATING_ROAD_NEEDED_HOSTILE
"Hostile"
@ Original
Original algorithm (quadratic cargo by population).
@ Bitcount
Bit-counted algorithm (normal distribution from individual house population).
static constexpr int RATING_ROAD_NEEDED_NEUTRAL
"Neutral"
@ Original
Original algorithm (min. 1 distance between roads).
@ Random
Random town layout.
@ BetterRoads
Extended original algorithm (min. 2 distance between roads).
@ End
Number of town layouts.
@ Grid2x2
Geometric 2x2 grid algorithm.
@ Grid3x3
Geometric 3x3 grid algorithm.
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
@ CustomLayout
Allowed, with custom town layout.
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
"Hostile"
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
static constexpr int RATING_STATION_DOWN_STEP
... but loses for badly serviced stations
static constexpr int RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
"Neutral"
static constexpr int RATING_ROAD_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
static constexpr int RATING_STATION_UP_STEP
when a town grows, company gains reputation for all well serviced stations ...
TownSize
Supported initial town sizes.
@ Random
Random size, bigger than small, smaller than large.
@ End
Number of available town sizes.
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including '\0'.
@ Roads
Allow town to place roads.
@ Buildings
Allow town to place buildings.
EnumBitSet< TownExpandMode, uint8_t > TownExpandModes
Bitset of TownExpandMode elements.
static constexpr int RATING_ROAD_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
static constexpr int RATING_GROWTH_MAXIMUM
... up to RATING_MEDIOCRE
bool VerifyTownName(uint32_t r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
bool GenerateTownName(Randomizer &randomizer, uint32_t *townnameparts, TownNames *town_names)
Generates valid town name.
Town name generator stuff.
bool IsTransparencySet(TransparencyOption to)
Check if the transparency option bit is set and if we aren't in the game menu (there's never transpar...
bool IsInvisibilitySet(TransparencyOption to)
Check if the invisibility option bit is set and if we aren't in the game menu (there's never transpar...
@ Road
Transport by road vehicle.
Map accessors for tree tiles.
TreeGround GetTreeGround(Tile t)
Returns the groundtype for tree tiles.
Command definitions related to tunnels and bridges.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int z, const SpriteBounds &bounds, bool transparent, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
void AddChildSpriteScreen(SpriteID image, PaletteID pal, int x, int y, bool transparent, const SubSprite *sub, bool scale, bool relative)
Add a child sprite to a parent sprite.
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.
Functions related to (drawing on) viewports.
Declarations for accessing the k-d tree of viewports.
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
bool IsSea(Tile t)
Is it a sea water tile?
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
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-...
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Window functions not directly related to making/drawing windows.