OpenTTD Source
20240917-master-g9ab0a47812
|
Go to the documentation of this file.
16 #include "viewport_kdtree.h"
61 #include "table/strings.h"
73 void RebuildTownKdtree()
75 std::vector<TownID> townids;
77 townids.push_back(town->index);
79 _town_kdtree.
Build(townids.begin(), townids.end());
121 assert(i->town !=
this);
126 assert(o->town !=
this);
151 for (
auto &psa : this->psa_list) {
154 this->psa_list.clear();
216 void Town::FillCachedName()
const
227 return (_price[PR_CLEAR_HOUSE] * this->
removal_cost) >> 8;
231 static int _grow_town_result;
234 enum TownGrowthResult {
236 GROWTH_SEARCH_STOPPED = 0
243 static void TownDrawHouseLift(
const TileInfo *ti)
248 typedef void TownDrawTileProc(
const TileInfo *ti);
249 static TownDrawTileProc *
const _town_draw_tile_procs[1] = {
275 if (
HouseSpec::Get(house_id)->grf_prop.spritegroup[0] !=
nullptr) {
276 DrawNewHouseTile(ti, house_id);
297 ti->
x + dcts->subtile_x,
298 ti->
y + dcts->subtile_y,
310 int proc = dcts->draw_proc - 1;
312 if (proc >= 0) _town_draw_tile_procs[proc](ti);
316 static int GetSlopePixelZ_Town(
TileIndex tile, uint, uint,
bool)
353 AnimateNewHouseTile(tile);
384 pos += (pos < dest) ? 1 : -1;
403 if (_town_kdtree.
Count() == 0)
return false;
419 STR_VIEWPORT_TOWN_TINY_WHITE);
421 _viewport_sign_kdtree.
Insert(ViewportSignKdtreeItem::MakeTown(this->
index));
430 t->UpdateVirtCoord();
438 t->cached_name.clear();
481 bool covers_area = st->TileIsInCatchment(tile);
482 if (flags & BUILDING_2_TILES_Y) covers_area |= st->TileIsInCatchment(tile +
TileDiffXY(0, 1));
483 if (flags & BUILDING_2_TILES_X) covers_area |= st->TileIsInCatchment(tile +
TileDiffXY(1, 0));
484 if (flags & BUILDING_HAS_4_TILES) covers_area |= st->TileIsInCatchment(tile +
TileDiffXY(1, 1));
506 AnimateNewHouseConstruction(tile);
540 if (amount == 0)
return;
544 amount = (amount + 1) >> 1;
565 uint32_t r = Random();
566 if (
GB(r, 0, 8) < rate) {
568 uint amt = (
GB(r, 0, 8) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR) / 8 + 1;
586 uint32_t r = Random();
589 int genmax = (rate + 7) / 8;
590 uint32_t genmask = (genmax >= 32) ? 0xFFFFFFFF : ((1 << genmax) - 1);
593 uint amt =
CountBits(r & genmask) * cs->town_production_multiplier / TOWN_PRODUCTION_DIVISOR;
629 Town *t = Town::GetByTile(tile);
630 uint32_t r = Random();
635 for (uint i = 0; i < 256; i++) {
643 uint amt =
GB(callback, 0, 8);
644 if (amt == 0)
continue;
676 CanDeleteHouse(tile) &&
684 if (
GB(r, 24, 8) >= 12) {
692 int x =
Clamp(grid_pos.
x, 0, 1);
693 int y =
Clamp(grid_pos.
y, 0, 1);
720 if (!CanDeleteHouse(tile))
return CMD_ERROR;
728 Town *t = Town::GetByTile(tile);
750 Town *t = Town::GetByTile(tile);
753 for (uint i = 0; i < 256; i++) {
766 produced[cs->Index()]++;
771 produced[cs->Index()]++;
787 acceptance[cargo] += amount;
788 SetBit(always_accepted, cargo);
791 static void AddAcceptedCargo_Town(
TileIndex tile,
CargoArray &acceptance, CargoTypes &always_accepted)
797 for (uint8_t i = 0; i <
lengthof(accepts); i++) {
829 for (uint8_t i = 0; i <
lengthof(accepts); i++) {
842 uint16_t callback_res = GetHouseCallback(
CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, Town::GetByTile(tile), tile);
844 if (callback_res > 0x400) {
848 if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
854 if (!house_completed) {
856 td->
str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
903 if (_game_mode == GM_EDITOR)
return;
930 const uint16_t assume_max_speed = 50;
933 if (RoadTypeIsTram(rt))
continue;
938 if (rti->
label == 0)
continue;
946 if (best !=
nullptr) {
965 if (RoadTypeIsTram(rt))
continue;
967 if (rti->
label == 0)
continue;
974 if (best ==
nullptr)
return INT32_MAX;
987 if (min_date < INT32_MAX) {
991 ShowErrorMessage(STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL, STR_ERROR_NO_TOWN_ROADTYPES_AVAILABLE_AT_ALL_EXPLANATION,
WL_CRITICAL);
1017 dist_multi = (dist_multi + 1) * 4;
1018 for (uint pos = 4; pos < dist_multi; pos++) {
1023 if (pos & 2) cur += tid_lt[2];
1066 if (desired_slope != cur_slope &&
ComplementSlope(desired_slope) != cur_slope) {
1084 static bool TerraformTownTile(
TileIndex tile,
Slope edges,
bool dir)
1089 if (r.
Failed() || r.
GetCost() >= (_price[PR_TERRAFORM] + 2) * 8)
return false;
1094 static void LevelTownLand(
TileIndex tile)
1124 default: NOT_REACHED();
1127 if ((grid_pos.
x % 3) == 0) rcmd |=
ROAD_Y;
1128 if ((grid_pos.
y % 3) == 0) rcmd |=
ROAD_X;
1132 if ((grid_pos.
x % 4) == 0) rcmd |=
ROAD_Y;
1133 if ((grid_pos.
y % 4) == 0) rcmd |=
ROAD_X;
1143 default: rb_template =
ROAD_ALL;
break;
1201 _grow_town_result = GROWTH_SUCCEED;
1222 _grow_town_result = GROWTH_SUCCEED;
1317 uint bridge_length = 0;
1324 const uint TOWN_BRIDGE_LENGTH_CAP = 11;
1325 uint base_bridge_length = 5;
1326 uint max_bridge_length = std::min(t->
cache.
population / 1000 + base_bridge_length, TOWN_BRIDGE_LENGTH_CAP);
1331 if (bridge_length++ >= base_bridge_length) {
1335 bridge_tile += delta;
1339 if (bridge_length++ >= max_bridge_length) {
1343 bridge_tile += delta;
1348 if (bridge_length == 1)
return false;
1358 for (uint8_t times = 0; times <= 22; times++) {
1365 _grow_town_result = GROWTH_SUCCEED;
1396 int max_tunnel_length = 0;
1402 for (uint8_t tiles = 0; tiles < 4; tiles++) {
1406 slope_tile += delta;
1413 max_tunnel_length = 5;
1416 uint8_t tunnel_length = 0;
1421 if (tunnel_length++ >= max_tunnel_length)
return false;
1422 tunnel_tile += delta;
1427 if (tunnel_length == 1)
return false;
1436 _grow_town_result = GROWTH_SUCCEED;
1451 static const TileIndexDiffC tiles[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
1454 for (
const auto &ptr : tiles) {
1461 RoadType road_rt = GetRoadTypeRoad(cur_tile);
1462 RoadType tram_rt = GetRoadTypeTram(cur_tile);
1482 RoadType rt = GetRoadTypeRoad(tile);
1522 _grow_town_result = GROWTH_SEARCH_STOPPED;
1532 default: NOT_REACHED();
1548 do target_dir =
RandomDiagDir();
while (target_dir == source_dir);
1576 _grow_town_result = GROWTH_SEARCH_STOPPED;
1581 default: NOT_REACHED();
1594 bool allow_house =
true;
1611 if (cur_rb & target_rb) {
1619 if ((cur_rb &
ROAD_X) != target_rb)
return;
1651 default: NOT_REACHED();
1659 allow_house = (rcmd & target_rb) ==
ROAD_NONE;
1681 if (
Chance16(1, 6)) LevelTownLand(house_tile);
1686 _grow_town_result = GROWTH_SUCCEED;
1694 _grow_town_result = GROWTH_SEARCH_STOPPED;
1752 return (target_rb & back_rb) != 0 && (target_rb & ~back_rb) != 0;
1794 if (_grow_town_result == GROWTH_SUCCEED)
return true;
1813 }
while (!(cur_rb & target_bits));
1814 cur_rb &= ~target_bits;
1832 }
while (--_grow_town_result >= 0);
1846 uint32_t r = Random();
1847 uint a =
GB(r, 0, 2);
1848 uint b =
GB(r, 8, 2);
1882 for (
const auto &ptr : _town_coord_mod) {
1895 for (
const auto &ptr : _town_coord_mod) {
1919 static const std::array<std::array<uint32_t, HZB_END>, 23> _town_squared_town_zone_radius_data = {{
1932 { 81, 36, 25, 0, 9},
1933 { 81, 36, 25, 16, 9},
1934 { 81, 49, 0, 25, 9},
1935 { 81, 64, 0, 25, 9},
1936 { 81, 64, 0, 36, 9},
1937 { 81, 64, 0, 36, 16},
1938 {100, 81, 0, 49, 16},
1939 {100, 81, 0, 49, 25},
1940 {121, 81, 0, 49, 25},
1941 {121, 81, 0, 49, 25},
1942 {121, 81, 0, 49, 36},
1945 if (t->
cache.
num_houses < std::size(_town_squared_town_zone_radius_data) * 4) {
2030 t->townnamegrfid = tnp.grfid;
2031 t->townnametype = tnp.type;
2033 t->townnameparts = townnameparts;
2039 int x = (int)size * 16 + 3;
2040 if (size ==
TSZ_RANDOM) x = (Random() & 0xF) + 8;
2095 if (!t->
name.empty() && t->
name == name)
return false;
2124 if (random_location)
return {
CMD_ERROR, 0, INVALID_TOWN };
2145 if (!random_location) {
2147 if (ret.
Failed())
return { ret, 0, INVALID_TOWN };
2150 static const uint8_t price_mult[][
TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
2152 static_assert(
lengthof(price_mult[0]) == 4);
2155 uint8_t mult = price_mult[city][size];
2160 TownID new_town = INVALID_TOWN;
2169 if (random_location) {
2171 if (t ==
nullptr)
return {
CommandCost(STR_ERROR_NO_SPACE_FOR_TOWN), 0, INVALID_TOWN };
2174 DoCreateTown(t, tile, townnameparts, size, city, layout,
true);
2177 new_town = t->
index;
2179 old_generating_world.
Restore();
2181 if (t !=
nullptr && !text.empty()) {
2186 if (_game_mode != GM_EDITOR) {
2188 assert(!random_location);
2206 return { cost, 0, new_town };
2223 default:
return tile;
2241 default:
return true;
2353 DoCreateTown(t, tile, townnameparts, size, city, layout,
false);
2369 }
while (--attempts != 0);
2374 static const uint8_t _num_initial_towns[4] = {5, 11, 23, 46};
2384 uint current_number = 0;
2388 uint32_t townnameparts;
2389 TownNames town_names;
2395 town_names.insert(town->GetCachedName());
2413 RebuildTownKdtree();
2415 if (current_number != 0)
return true;
2445 HouseZonesBits smallest = HZB_TOWN_EDGE;
2446 for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
2447 if (dist < t->cache.squared_town_zone_radius[i]) smallest = i;
2582 if ((grid_pos.
x % 3) == 0 || (grid_pos.
y % 3) == 0)
return false;
2586 if ((grid_pos.
x % 4) == 0 || (grid_pos.
y % 4) == 0)
return false;
2616 if ((grid_pos.
x != 2 && grid_pos.
x != -1) ||
2617 (grid_pos.
y != 2 && grid_pos.
y != -1))
return false;
2621 if ((grid_pos.
x & 3) < 2 || (grid_pos.
y & 3) < 2)
return false;
2695 uint8_t construction_counter = 0;
2696 uint8_t construction_stage = 0;
2699 uint32_t construction_random = Random();
2707 construction_counter =
GB(construction_random, 2, 2);
2711 MakeTownHouse(tile, t, construction_counter, construction_stage, house, random_bits);
2741 uint bitmask = (1 << rad) + (1 << (land + 12));
2746 static std::vector<std::pair<HouseID, uint>> probs;
2749 uint probability_max = 0;
2757 if (hs.
class_id != HOUSE_NO_CLASS) {
2766 probability_max += cur_prob;
2767 probs.emplace_back(hs.
Index(), cur_prob);
2772 while (probability_max > 0) {
2782 for (i = 0; i < probs.size(); i++) {
2783 if (probs[i].second > r)
break;
2784 r -= probs[i].second;
2787 HouseID house = probs[i].first;
2788 probability_max -= probs[i].second;
2791 probs[i] = probs.back();
2811 if (t->
flags & oneof)
continue;
2815 if (noslope && slope !=
SLOPE_FLAT)
continue;
2827 uint8_t random_bits = Random();
2847 if (_game_mode != GM_EDITOR)
return CMD_ERROR;
2903 DoClearSquare(tile);
2922 }
else if (
HouseSpec::Get(house - 1)->building_flags & BUILDING_2_TILES_Y) {
2925 }
else if (
HouseSpec::Get(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
2928 }
else if (
HouseSpec::Get(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
2989 bool reset = text.empty();
3006 ClearAllStationCachedNames();
3007 ClearAllIndustryCachedNames();
3021 if (cs->town_acceptance_effect == effect)
return cs;
3048 t->
goal[tae] = goal;
3071 if (!text.empty()) t->
text = text;
3093 if (growth_rate == 0) {
3132 int16_t new_rating =
Clamp(rating, RATING_MINIMUM, RATING_MAXIMUM);
3134 t->
ratings[company_id] = new_rating;
3156 if (grow_amount == 0) {
3161 uint n = amount * 10;
3166 for (; grow_amount > 0; grow_amount--) {
3168 for (uint i = 0; i < 25; i++)
if (
GrowTown(t))
break;
3193 if (st->town == t) {
3198 if (ret.
Failed())
return ret;
3219 if (ret.
Failed())
return ret;
3225 bool try_clear =
false;
3262 if (ret.
Failed())
return ret;
3281 2, 4, 9, 35, 48, 53, 117, 175
3384 static const int STATUE_NUMBER_INNER_TILES = 25;
3403 if (statue_data->
tile_count <= STATUE_NUMBER_INNER_TILES) {
3499 SetDParam(0, STR_NEWS_EXCLUSIVE_RIGHTS_TITLE);
3554 static TownActionProc *
const _town_action_proc[] = {
3592 if (t->
ratings[cid] >= RATING_BRIBE_MAXIMUM) {
3637 CommandCost ret = _town_action_proc[action](t, flags);
3638 if (ret.
Failed())
return ret;
3647 template <
typename Func>
3648 static void ForAllStationsNearTown(
Town *t, Func func)
3656 if (DistanceSquare(st->xy, t->xy) <= t->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
3675 ForAllStationsNearTown(t, [&](
const Station *st) {
3676 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3677 if (Company::IsValidID(st->owner)) {
3678 int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
3679 t->ratings[st->owner] = std::min<int>(new_rating, INT16_MAX);
3683 int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
3684 t->ratings[st->owner] = std::max(new_rating, INT16_MIN);
3722 ForAllStationsNearTown(t, [&](
const Station * st) {
3723 if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
3743 static const uint16_t _grow_count_values[2][6] = {
3744 { 120, 120, 120, 100, 80, 60 },
3745 { 320, 420, 300, 220, 160, 100 }
3753 m >>= growth_multiplier;
3787 for (
int i = TAE_BEGIN; i <
TAE_END; i++) {
3788 switch (t->
goal[i]) {
3871 if (tid == INVALID_TOWN) {
3888 return Town::GetByTile(tile);
3905 static int ref_count = 0;
3907 if (ref_count == 0) {
3912 assert(ref_count > 0);
3954 if (rating < max) rating = max;
3959 if (rating > max) rating = max;
4026 for (
auto &supplied : t->
supplied) supplied.NewMonth();
4027 for (
auto &received : t->
received) received.NewMonth();
4055 bool allow_terraform =
true;
4062 uint16_t res = GetHouseCallback(
CBID_HOUSE_AUTOSLOPE, 0, 0, house, Town::GetByTile(tile), tile);
4076 GetSlopePixelZ_Town,
4078 AddAcceptedCargo_Town,
4080 GetTileTrackStatus_Town,
4084 ChangeTileOwner_Town,
4085 AddProducedCargo_Town,
4091 std::span<const DrawBuildingsTileStruct> GetTownDrawTileData()
@ SLOPE_E
the east corner of the tile is raised
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
Grows the given town.
RoadTypeFlags flags
Bit mask of road type flags.
@ SLOPE_SE
south and east corner are raised
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
@ MP_HOUSE
A house by a town.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
@ TACT_BRIBE
Try to bribe the council.
const char * grf
newGRF used for the tile contents
CompanyMask have_ratings
which companies have a rating
void ClearTownHouse(Town *t, TileIndex tile)
Clear a town house.
@ OWNER_DEITY
The object is owned by a superuser / goal script.
@ TROPICZONE_DESERT
Tile is desert.
@ TACT_BUILD_STATUE
Build a statue.
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-...
Structure for storing data while searching the best place to build a statue.
static void TileLoop_Town(TileIndex tile)
Tile callback function.
void ResetHouseAge(Tile t)
Sets the age of the house to zero.
static std::map< const Town *, int > _town_test_ratings
Map of towns to modified ratings, while in town rating test-mode.
constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset)
Adds a given offset to a tile.
Cheat magic_bulldozer
dynamite industries, objects
uint8_t rating
Station rating for this cargo.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
@ RATING_TUNNEL_BRIDGE_NEEDED_HOSTILE
"Hostile"
Structure contains cached list of stations nearby.
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest to the given tile within threshold.
TownSize
Supported initial town sizes.
static Titem * Get(size_t index)
Returns Titem with given index.
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
@ TO_HOUSES
town buildings
void OnTick_Town()
Iterate through all towns and call their tick handler.
uint8_t larger_towns
the number of cities to build. These start off larger and grow twice as fast
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
static int GetRating(const Town *t)
Get the rating of a town for the _current_company.
RoadBits
Enumeration for the road parts on a tile.
static void TownGenerateCargoOriginal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the original algorithm.
@ CBM_HOUSE_CARGO_ACCEPTANCE
decides amount of cargo acceptance
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
Update data structures when a house is removed.
uint TileHash2Bit(uint x, uint y)
Get the last two bits of the TileHash from a tile position.
static void TownGenerateCargoBinominal(Town *t, TownProductionEffect tpe, uint8_t rate, StationFinder &stations)
Generate cargo for a house using the binominal algorithm.
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
void InitializeLayout(TownLayout layout)
Assign the town layout.
@ ROADTYPE_ROAD
Basic road type.
bool IsRoadOwner(Tile t, RoadTramType rtt, Owner o)
Check if a specific road type is owned by an owner.
TownLayout town_layout
select town layout,
static bool FindNearestEmptyLand(TileIndex tile, void *)
CircularTileSearch callback to find the nearest land tile.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
TimerGameCalendar::Date introduction_date
Introduction date.
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
static CommandCost TownActionBuildStatue(Town *t, DoCommandFlag flags)
Perform a 9x9 tiles circular search from the center of the town in order to find a free tile to place...
K-dimensional tree, specialised for 2-dimensional space.
Tile information, used while rendering the tile.
Class to backup a specific variable and restore it later.
CompanyMask statues
which companies have a statue?
uint8_t minimum_life
The minimum number of years this house will survive before the town rebuilds it.
TimerGameCalendar::Year max_year
last year it can be built
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=nullptr, uint8_t view=0)
Actually build the object.
static constexpr DoCommandFlag CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
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.
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Owner owner[4]
Name of the owner(s)
@ SLOPE_NE
north and east corner are raised
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
uint32_t GetWorldPopulation()
Get the total population, the sum of all towns in the world.
uint GetClosestWaterDistance(TileIndex tile, bool water)
Finds the distance for the closest tile with water/land given a tile.
static void InvalidateAllFrom(SourceType src_type, SourceID src)
Invalidates (sets source_id to INVALID_SOURCE) all cargo packets from given source.
@ INVALID_COMPANY
An invalid company.
const uint8_t _town_action_costs[TACT_COUNT]
Factor in the cost of each town action.
static void UpdateTownRating(Town *t)
Monthly callback to update town and station ratings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
@ ROAD_SE
South-east part.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
static bool _town_rating_test
If true, town rating is in test-mode.
@ NT_INDUSTRY_OPEN
Opening of industries.
uint8_t GetHouseBuildingStage(Tile t)
House Construction Scheme.
An interval timer will fire every interval, and will continue to fire until it is deleted.
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
static void AddAcceptedCargoSetMask(CargoID cargo, uint amount, CargoArray &acceptance, CargoTypes &always_accepted)
Fill cargo acceptance array and always_accepted mask, if cargo ID is valid.
void IncHouseConstructionTick(Tile t)
Sets the increment stage of a house It is working with the whole counter + stage 5 bits,...
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Owner
Enum for all companies/owners.
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...
Tindex index
Index of this pool item.
@ TACT_FUND_BUILDINGS
Fund new buildings.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
static Object * GetByTile(TileIndex tile)
Get the object associated with a tile.
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
static bool GrowTownAtRoad(Town *t, TileIndex tile)
Try to grow a town at a given road tile.
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
Check if a Road is allowed on a given tile.
Class for storing amounts of cargo.
SpriteID sprite
The 'real' sprite.
uint8_t cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
@ ROAD_ALL
Full 4-way crossing.
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, int maxz, bool noslope)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
DifficultySettings difficulty
settings related to the difficulty
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
@ ROAD_W
Road at the two western edges.
@ ROADTYPE_BEGIN
Used for iterations.
uint16_t growth_rate
town growth rate
static void AdvanceSingleHouseConstruction(TileIndex tile)
Helper function for house construction stage progression.
@ DIAGDIRDIFF_90LEFT
90 degrees left
Representation of a waypoint.
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
uint8_t town_council_tolerance
minimum required town ratings to be allowed to demolish stuff
static const ObjectType OBJECT_STATUE
Statue in towns.
static const uint TILE_SIZE
Tile size in world coordinates.
static CommandCost TownActionBuyRights(Town *t, DoCommandFlag flags)
Perform the "buy exclusive transport rights" town action.
@ CBID_HOUSE_CUSTOM_NAME
Called on the Get Tile Description for an house tile.
bool VerifyTownName(uint32_t r, const TownNameParams *par, TownNames *town_names)
Verifies the town name is valid and unique.
DiagDirection
Enumeration for diagonal directions.
Randomizer _random
Random used in the game state calculations.
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
uint16_t callback_mask
Bitmask of house callbacks that have to be called.
StringID building_name
building name
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
@ SLOPE_NW
north and west corner are raised
ClientSettings _settings_client
The current settings for this game.
void AddAnimatedTile(TileIndex tile, bool mark_dirty)
Add the given tile to the animated tile table (if it does not exist yet).
TileIndex xy
town center tile
Specification of a cargo type.
@ DC_NO_WATER
don't allow building on water
uint8_t probability
Relative probability of appearing (16 is the standard value)
DiagDirection GetRoadStopDir(Tile t)
Gets the direction the road stop entrance points towards.
void SetLiftDestination(Tile t, uint8_t dest)
Set the new destination of the lift for this animated house, and activate the LiftHasDestination bit.
@ MP_INDUSTRY
Part of an industry.
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
@ SLOPE_STEEP_E
a steep slope falling to west (from east)
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
int y
Y position of the tile in unit coordinates.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
@ SLOPE_W
the west corner of the tile is raised
uint8_t number_towns
the amount of towns
@ WC_STATION_VIEW
Station view; Window numbers:
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
@ ROAD_N
Road at the two northern edges.
static Town * CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout)
Create a random town somewhere in the world.
@ TL_ORIGINAL
Original algorithm (min. 1 distance between roads)
Defines the internal data of a functional industry.
bool CatchmentCoversTown(TownID t) const
Test if the given town ID is covered by our catchment area.
@ CBID_HOUSE_DRAW_FOUNDATIONS
Called to determine the type (if any) of foundation to draw for house 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.
@ DC_EXEC
execute the given command
void Build(It begin, It end)
Clear and rebuild the tree from a new sequence of elements,.
@ TPE_MAIL
Cargo behaves mail-like for production.
uint8_t landscape
the landscape we're currently in
static RoadBits GetTownRoadBits(TileIndex tile)
Return the RoadBits of a tile, ignoring depot and bay road stops.
Owner owner
The owner of this station.
@ MP_ROAD
A tile with road (or tram tracks)
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Tile description for the 'land area information' tool.
bool LiftHasDestination(Tile t)
Check if the lift of this animated house has a destination.
@ TCGM_ORIGINAL
Original algorithm (quadratic cargo by population)
bool show_zone
NOSAVE: mark town to show the local authority zone in the viewports.
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.
@ TOWN_HAS_STADIUM
There can be only one stadium by town.
@ CBM_HOUSE_PRODUCE_CARGO
custom cargo production
DoCommandFlag
List of flags for a command.
@ SLOPE_S
the south corner of the tile is raised
void UpdateVirtCoord()
Resize the sign (label) of the town after it changes population.
Foundation
Enumeration for Foundations.
void UpdateTownRadius(Town *t)
Update the cached town zone radii of a town, based on the number of houses.
@ SLOPE_STEEP_S
a steep slope falling to north (from south)
bool GenerateTowns(TownLayout layout)
Generate a number of towns with a given layout.
size_t Count() const
Get number of elements stored in tree.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
@ ROAD_NW
North-west part.
Used as the user_data for FindFurthestFromWater.
uint8_t road_build_months
fund road reconstruction in action?
static Town * GetRandom()
Return a random valid town.
bool Succeeded() const
Did this command succeed?
@ RATING_GROWTH_UP_STEP
when a town grows, all companies have rating increased a bit ...
uint8_t removal_cost
cost multiplier for removing it
bool bribe
enable bribing the local authority
void Remove(const T &element)
Remove a single element from the tree, if it exists.
uint8_t flags
See TownFlags.
GameCreationSettings game_creation
settings used during the creation of a game (map)
@ NR_TOWN
Reference town. Scroll to town when clicking on the news.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
@ TRANSPORT_ROAD
Transport by road vehicle.
uint8_t town_growth_rate
town growth rate
@ RATING_INITIAL
initial rating
Slope ComplementSlope(Slope s)
Return the complement of a slope.
Slope tileh
Slope of the tile.
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
static constexpr TimerGame< struct Calendar >::Date MAX_DATE
The date of the last day of the max year.
static bool TestTownOwnsBridge(TileIndex tile, const Town *t)
Check if a town 'owns' a bridge.
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
DiagDirection GetRoadDepotDirection(Tile t)
Get the direction of the exit of a road depot.
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
uint ScaleByCargoScale(uint num, bool town)
Scale a number by the cargo scale setting.
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...
HouseExtraFlags extra_flags
some more flags
TimerGameCalendar::Year GetHouseAge(Tile t)
Get the age of the house.
static bool GrowTown(Town *t)
Grow the town.
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
uint16_t override
id of the entity been replaced by
static size_t GetPoolSize()
Returns first unused index.
TransportType
Available types of transport.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
bool fund_buildings
allow funding new buildings
uint8_t dist_local_authority
distance for town local authority, default 20
@ ROAD_S
Road at the two southern edges.
TransportedCargoStat< uint32_t > supplied[NUM_CARGO]
Cargo statistics about supplied cargo.
CommandCost CmdTownCargoGoal(DoCommandFlag flags, TownID town_id, TownAcceptanceEffect tae, uint32_t goal)
Change the cargo goal of a town.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
@ TOWN_RATING_CHECK_TYPE_COUNT
Number of town checking action types.
static DiagDirection RandomDiagDir()
Return a random direction.
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
RoadType GetTownRoadType()
Get the road type that towns should build at this current moment.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
static CommandCost TownActionAdvertiseSmall(Town *t, DoCommandFlag flags)
Perform the "small advertising campaign" town action.
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
Common return value for all commands.
static bool _generating_town
Set if a town is being generated.
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
Function performing a search around a center tile and going outward, thus in circle.
Information about GRF, used in the game and (part of it) in savegames.
uint16_t grow_counter
counter to count when to grow, value is smaller than or equal to growth_rate
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
@ WC_TOWN_AUTHORITY
Town authority; Window numbers:
TileIndex tile
holds the tile that was found
@ OWNER_NONE
The tile has no ownership.
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
@ GSF_FAKE_TOWNS
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
uint16_t custom_town_number
manually entered number of towns
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
static void BuildTownHouse(Town *t, TileIndex tile, const HouseSpec *hs, HouseID house, uint8_t random_bits)
Build a house at this tile.
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
@ DRD_NONE
None of the directions are disallowed.
static CommandCost TownCanBePlacedHere(TileIndex tile)
Check if it's possible to place a town on a given tile.
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
uint max_dist
holds the distance that tile is from the water
TownRatingCheckType
Action types that a company must ask permission for to a town authority.
@ ROAD_SW
South-west part.
static int CountActiveStations(Town *t)
Calculates amount of active stations in the range of town (HZB_TOWN_EDGE).
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
@ DIAGDIR_BEGIN
Used for iterations.
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
void Insert(const T &element)
Insert a single element in the tree.
@ MP_OBJECT
Contains objects such as transmitters and owned land.
@ CBID_HOUSE_ALLOW_CONSTRUCTION
Determine whether the house can be built on the specified tile.
Cheats _cheats
All the cheats.
@ TSZ_END
Number of available town sizes.
bool population_in_label
show the population of a town in its label?
@ CBM_HOUSE_ACCEPT_CARGO
decides accepted types
static std::array< std::vector< const CargoSpec * >, NUM_TPE > town_production_cargoes
List of cargo specs for each Town Product Effect.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
StationList stations_near
NOSAVE: List of nearby stations.
bool Failed() const
Did this command fail?
static void DoCreateTown(Town *t, TileIndex tile, uint32_t townnameparts, TownSize size, bool city, TownLayout layout, bool manual)
Actually create a town.
static TileIndex AlignTileToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
@ TPE_PASSENGERS
Cargo behaves passenger-like for production.
An object, such as transmitter, on the map.
static bool GrowTownWithTunnel(const Town *t, const TileIndex tile, const DiagDirection tunnel_dir)
Grows the town with a tunnel.
static bool TryBuildTownHouse(Town *t, TileIndex tile)
Tries to build a house at this tile.
@ TL_RANDOM
Random town layout.
CommandCost CmdTownRating(DoCommandFlag flags, TownID town_id, CompanyID company_id, int16_t rating)
Change the rating of a company in a town.
Represents the covered area of e.g.
@ TACT_ROAD_REBUILD
Rebuild the roads.
static bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
Checks if the current town layout allows building here.
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Container for a single string to be passed as NewsAllocatedData.
void DeleteSubsidyWith(SourceType type, SourceID index)
Delete the subsidies associated with a given cargo source type and id.
static const uint CALLBACK_HOUSEPRODCARGO_END
Sentinel indicating that the loop for CBID_HOUSE_PRODUCE_CARGO has ended.
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
RoadType
The different roadtypes we support.
EconomySettings economy
settings to change the economy
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
@ DIAGDIRDIFF_90RIGHT
90 degrees right
ObjectType type
Type of the object.
@ NUM_TLS
Number of town layouts.
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
uint8_t unwanted[MAX_COMPANIES]
how many months companies aren't wanted by towns (bribe)
HouseID Index() const
Gets the index of this spec.
static bool RedundantBridgeExistsNearby(TileIndex tile, void *user_data)
CircularTileSearch proc which checks for a nearby parallel bridge to avoid building redundant bridges...
static TimerGameCalendar::Date GetTownRoadTypeFirstIntroductionDate()
Get the calendar date of the earliest town-buildable road type.
static void ChangePopulation(Town *t, int mod)
Change the town's population as recorded in the town cache, town label, and town directory.
@ RATING_ROAD_NEEDED_HOSTILE
"Hostile"
#define lengthof(array)
Return the length of an fixed size array.
static debug_inline bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
static bool SearchTileForStatue(TileIndex tile, void *user_data)
Search callback function for TownActionBuildStatue.
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Money GetCost() const
The costs as made up to this moment.
int tile_count
Number of tiles tried.
static bool IsCloseToTown(TileIndex tile, uint dist)
Determines if a town is close to a tile.
static CommandCost TownActionRoadRebuild(Town *t, DoCommandFlag flags)
Perform the "local road reconstruction" town action.
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
Get the foundation for a house.
void HaltLift(Tile t)
Stop the lift of this animated house from moving.
#define RandomTile()
Get a valid random tile.
static bool RoadTypesAllowHouseHere(TileIndex t)
Checks whether at least one surrounding road allows to build a house here.
static CommandCost TownActionFundBuildings(Town *t, DoCommandFlag flags)
Perform the "fund new buildings" town action.
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.
@ DC_NO_TEST_TOWN_RATING
town rating does not disallow you from building
RoadBits CleanUpRoadBits(const TileIndex tile, RoadBits org_rb)
Clean up unnecessary RoadBits of a planned tile.
bool exclusive_rights
allow buying exclusive rights
static CommandCost TownActionAdvertiseLarge(Town *t, DoCommandFlag flags)
Perform the "large advertising campaign" town action.
uint8_t population
population (Zero on other tiles in multi tile house.)
void UpdateTownMaxPass(Town *t)
Update the maximum amount of montly passengers and mail for a town, based on its population.
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
@ TAE_END
End of town effects.
static bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
Checks if the current town layout allows a 2x2 building here.
@ INVALID_ROADTYPE
flag for invalid roadtype
int32_t TileIndexDiff
An offset value between two tiles.
Coordinates of a point in 2D.
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
@ FOUNDATION_NONE
The tile has no foundation, the slope remains unchanged.
TownFounding found_town
town founding.
RoadBits DiagDirToRoadBits(DiagDirection d)
Create the road-part which belongs to the given DiagDirection.
@ RATING_TUNNEL_BRIDGE_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
@ SLOPE_N
the north corner of the tile is raised
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
Generate the RoadBits of a grid tile.
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
@ CBID_HOUSE_CARGO_ACCEPTANCE
Called to decide how much cargo a town building can accept.
static void UpdateTownGrowth(Town *t)
Updates town growth state (whether it is growing or not).
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Set of callback functions for performing tile operations of a given tile type.
const StationList * GetStations()
Run a tile loop to find stations around a tile, on demand.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
bool value
tells if the bool cheat is active or not
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
@ EXPENSES_OTHER
Other expenses.
@ NF_NORMAL
Normal news item. (Newspaper with text only)
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
@ RATING_ROAD_NEEDED_NEUTRAL
"Neutral"
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
Callback function to clear a house tile.
@ Town
Source/destination is a town.
TownCargoGenMode town_cargogen_mode
algorithm for generating cargo from houses,
@ WC_TOWN_DIRECTORY
Town directory; Window numbers:
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
uint32_t population
Current population of people.
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int w, int h, int dz, int z, bool transparent, int bb_offset_x, int bb_offset_y, int bb_offset_z, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
uint16_t time_until_rebuild
time until we rebuild a house
bool IsValidTile(Tile tile)
Checks if a tile is valid.
@ RATING_ROAD_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
bool ConvertBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
@ MP_TREES
Tile got trees.
Tstorage new_max
Maximum amount this month.
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
A pair-construct of a TileIndexDiff.
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 void AdvanceHouseConstruction(TileIndex tile)
Increase the construction stage of a house.
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
bool _generating_world
Whether we are generating the map or not.
uint8_t mail_generation
mail generation multiplier (tile based, as the acceptances below)
uint DistanceSquare(TileIndex t0, TileIndex t1)
Gets the 'Square' distance between the two given tiles.
Tstorage old_max
Maximum amount last month.
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
@ ROADTYPE_END
Used for iterations.
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
static void PostDestructor(size_t index)
Invalidating of the "nearest town cache" has to be done after removing item from the pool.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
bool allow_town_level_crossings
towns are allowed to build level crossings
std::string text
General text with additional information.
@ ROAD_E
Road at the two eastern edges.
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
@ SLOPE_STEEP_W
a steep slope falling to east (from west)
Stores station stats for a single cargo.
CommandCost CmdTownSetText(DoCommandFlag flags, TownID town_id, const std::string &text)
Set a custom text in the Town window.
CompanyID _current_company
Company currently doing an action.
Tstorage new_act
Actually transported this month.
TownAcceptanceEffect
Town growth effect when delivering cargo.
static CommandCost TownActionBribe(Town *t, DoCommandFlag flags)
Perform the "bribe" town action.
@ BUILDING_IS_HISTORICAL
this house will only appear during town generation in random games, thus the historical
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
Check for parallel road inside a given distance.
void IncrementHouseAge(Tile t)
Increments the age of the house.
BuildingCounts< uint16_t > building_counts
The number of each type of building in the town.
Base class for all pools.
@ RATING_TUNNEL_BRIDGE_NEEDED_PERMISSIVE
"Permissive" (local authority disabled)
static bool TownAllowedToBuildRoads()
Check if the town is allowed to build roads.
@ TACT_COUNT
Number of available town actions.
static bool CanFollowRoad(TileIndex tile, DiagDirection dir)
Checks whether a road can be followed or is a dead end, that can not be extended to the next tile.
@ MP_VOID
Invisible tiles at the SW and SE border.
@ TCGM_BITCOUNT
Bit-counted algorithm (normal distribution from individual house population)
static size_t GetNumItems()
Returns number of valid items in the pool.
void DeleteAnimatedTile(TileIndex tile)
Removes the given tile from the animated tile table.
@ TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads)
RoadTypeLabel label
Unique 32 bit road type identifier.
void Restore()
Restore the variable.
void UpdatePosition(int center, int top, StringID str, StringID str_small=STR_NULL)
Update the position of the viewport sign.
Slope
Enumeration for the slope-type.
CommandCost CmdExpandTown(DoCommandFlag flags, TownID town_id, uint32_t grow_amount)
Expand a town (scenario editor only).
bool CheckTownRoadTypes()
Check if towns are able to build road.
static debug_inline uint Size()
Get the size of the map.
uint64_t dparam
Parameter of the str string.
void IncreaseBuildingCount(Town *t, HouseID house_id)
IncreaseBuildingCount() Increase the count of a building when it has been added by a town.
@ NF_COMPANY
Company news item. (Newspaper with face)
static void UpdateTownGrowCounter(Town *t, uint16_t prev_growth_rate)
Updates town grow counter after growth rate change.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
@ RATING_GROWTH_MAXIMUM
... up to RATING_MEDIOCRE
bool build_on_slopes
allow building on slopes
static void GetTownName(StringBuilder &builder, const TownNameParams *par, uint32_t townnameparts)
Fills builder with specified town name.
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
This structure is the same for both Industries and Houses.
@ SLOPE_SW
south and west corner are raised
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
uint32_t goal[NUM_TAE]
Amount of cargo required for the town to grow.
@ ROAD_NE
North-east part.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32_t ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32_t ref2=UINT32_MAX, const NewsAllocatedData *data=nullptr)
Add a new newsitem to be shown.
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
T FindNearest(CoordT x, CoordT y) const
Find the element closest to given coordinate, in Manhattan distance.
Tstorage old_act
Actually transported last month.
@ MP_STATION
A tile of a station.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
TownCache cache
Container for all cacheable data.
bool kdtree_valid
Are the sign data valid for use with the _viewport_sign_kdtree?
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
HouseClassID class_id
defines the class this house has (not grf file based)
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
bool IsHouseCompleted(Tile t)
Get the completion of this house.
Struct holding parameters used to generate town name.
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
TownProductionEffect
Town effect when producing cargo.
HouseZones building_availability
where can it be built (climates, zones)
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
CommandCost CheckforTownRating(DoCommandFlag flags, Town *t, TownRatingCheckType type)
Does the town authority allow the (destructive) action of the current company?
@ TOWN_IS_GROWING
Conditions for town growth are met. Grow according to Town::growth_rate.
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
Changes town rating of the current company.
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
@ DIAGDIR_END
Used for iterations.
@ SLOPE_ELEVATED
bit mask containing all 'simple' slopes
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,...
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
uint16_t HouseID
OpenTTD ID of house types.
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
StringID str
Description of the tile.
bool fund_roads
allow funding local road reconstruction
uint8_t town_name
the town name generator used for town names
@ DC_AUTO
don't allow building on structures
@ DC_NO_MODIFY_TOWN_RATING
do not change town rating
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.
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
TileIndex best_position
Best position found so far.
@ ROAD_NONE
No road-part is build.
uint32_t num_houses
Amount of houses.
@ ROTF_TOWN_BUILD
Bit number for allowing towns to build this roadtype.
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
@ TACT_NONE
Empty action set.
TileIndexDiff GetHouseNorthPart(HouseID &house)
Determines if a given HouseID is part of a multitile house.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
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.
int16_t y
The y value of the coordinate.
Slope InclinedSlope(DiagDirection dir)
Returns the slope that is inclined in a specific direction.
void SetLiftPosition(Tile t, uint8_t pos)
Set the position of the lift on this animated house.
@ CBID_HOUSE_PRODUCE_CARGO
Called to determine how much cargo a town building produces.
static void AnimateTile_Town(TileIndex tile)
Animate a tile for a town.
static void TownTickHandler(Town *t)
Handle the town tick for a single town, by growing the town if desired.
uint8_t GetLiftPosition(Tile t)
Get the position of the lift on this animated house.
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
Grows the town with an extra house.
static bool TownCanGrowRoad(TileIndex tile)
Test if town can grow road onto a specific tile.
@ ROTF_NO_HOUSES
Bit number for setting this roadtype as not house friendly.
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 MarkWholeScreenDirty()
This function mark the whole screen as dirty.
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.
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
@ COMPANY_SPECTATOR
The client is spectating.
static debug_inline uint TileHeight(Tile tile)
Returns the height of a tile.
CommandCost CmdDeleteTown(DoCommandFlag flags, TownID town_id)
Delete a town (scenario editor or worldgen only).
std::array< uint32_t, HZB_END > squared_town_zone_radius
UpdateTownRadius updates this given the house count.
static RoadBits GenRandomRoadBits()
Generate a random road block.
uint8_t fund_buildings_months
fund buildings program in action?
@ TAE_WATER
Cargo behaves water-like.
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
Grows the town with a bridge.
int16_t ratings[MAX_COMPANIES]
ratings of each company for this town
static void TownGenerateCargo(Town *t, CargoID ct, uint amount, StationFinder &stations, bool affected_by_recession)
Generate cargo for a house, scaled by the current economy scale.
CommandCost CmdRenameTown(DoCommandFlag flags, TownID town_id, const std::string &text)
Rename a town (server-only).
TransportedCargoStat< uint16_t > received[NUM_TAE]
Cargo statistics about received cargotypes.
@ CBM_HOUSE_AUTOSLOPE
decides allowance of autosloping
std::string string
The string to retain.
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
@ WC_TOWN_VIEW
Town view; Window numbers:
std::tuple< CommandCost, Money, TownID > CmdFoundTown(DoCommandFlag flags, TileIndex tile, TownSize size, bool city, TownLayout layout, bool random_location, uint32_t townnameparts, const std::string &text)
Create a new town.
bool GenerateTownName(Randomizer &randomizer, uint32_t *townnameparts, TownNames *town_names)
Generates valid town name.
TownLayout layout
town specific road layout
@ TF_CUSTOM_LAYOUT
Allowed, with custom town layout.
int x
X position of the tile in unit coordinates.
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
static bool CheckClearTile(TileIndex tile)
Check whether the land can be cleared.
PaletteID pal
The palette (use PAL_NONE) if not needed)
static Date date
Current date in days (day counter).
static bool IsUniqueTownName(const std::string &name)
Verifies this custom name is unique.
TileIndex tile
Tile index.
ConstructionSettings construction
construction of things in-game
@ TL_3X3_GRID
Geometric 3x3 grid algorithm.
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
@ TL_2X2_GRID
Geometric 2x2 grid algorithm.
@ MAX_COMPANIES
Maximum number of companies.
static const DrawBuildingsTileStruct _town_draw_tile_data[]
structure of houses graphics
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
bool EconomyIsInRecession()
Is the economy in recession?
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
@ CBM_HOUSE_DRAW_FOUNDATIONS
decides if default foundations need to be drawn
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
Checks whether the local authority allows construction of a new station (rail, road,...
static bool FindFurthestFromWater(TileIndex tile, void *user_data)
CircularTileSearch callback; finds the tile furthest from any water.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
const struct GRFFile * grffile
grf file that introduced this entity
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
bool larger_town
if this is a larger town and should grow more quickly
static CommandCost TownActionAdvertiseMedium(Town *t, DoCommandFlag flags)
Perform the "medium advertising campaign" town action.
uint8_t HighestSnowLine()
Get the highest possible snow line height, either variable or static.
static void DrawTile_Town(TileInfo *ti)
Draw a house and its tile.
static const uint MAX_LENGTH_TOWN_NAME_CHARS
The maximum length of a town name in characters including '\0'.
void DecreaseBuildingCount(Town *t, HouseID house_id)
DecreaseBuildingCount() Decrease the number of a building when it is deleted.
uint8_t GetLiftDestination(Tile t)
Get the current destination for this lift.
CommandCost CmdDoTownAction(DoCommandFlag flags, TownID town_id, uint8_t action)
Do a town action.
TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
Returns the diff between two tiles.
void MakeHouseTile(Tile t, TownID tid, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
Make the tile a house.
uint16_t remove_rating_decrease
rating decrease if removed
@ CBM_HOUSE_ALLOW_CONSTRUCTION
decide whether the house can be built on a given tile
Axis GetBridgeAxis(Tile t)
Get the axis of the bridge that goes over the tile.
@ TSZ_RANDOM
Random size, bigger than small, smaller than large.
CargoID GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
bool IsSlopeWithOneCornerRaised(Slope s)
Tests if a specific slope has exactly one corner raised.
bool IsLocalCompany()
Is the current company the local company?
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
CompanyID exclusivity
which company has exclusivity
@ RATING_ROAD_NEEDED_LENIENT
rating needed, "Lenient" difficulty settings
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
Money GetRemovalCost() const
Get the cost for removing this house.
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
Grows the town with a road piece.
@ GWP_TOWN
Generate towns.
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
@ CBID_HOUSE_ACCEPT_CARGO
Called to determine which cargoes a town building should accept.
@ SLOPE_STEEP_N
a steep slope falling to south (from north)
int16_t x
The x value of the coordinate.
TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
Get a list of available town authority actions.
static bool CheckTownBuild2House(TileIndex *tile, Town *t, int maxz, bool noslope, DiagDirection second)
Checks if a 1x2 or 2x1 building is allowed here, accounting for road layout and tile heights.
Town * town
Town the object is built in.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
@ TOWN_HAS_CHURCH
There can be only one church by town.
uint8_t exclusive_counter
months till the exclusivity expires
static debug_inline bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
@ ROAD_X
Full road along the x-axis (south-west + north-east)
GRFFileProps grf_prop
Properties related the the grf file.
std::string cached_name
NOSAVE: Cache of the resolved name of the town, if not using a custom town name.
TownActions
Town actions of a company.
static const uint CUSTOM_TOWN_NUMBER_DIFFICULTY
value for custom town number in difficulty settings
@ NR_NONE
Empty reference.
std::array< const struct SpriteGroup *, Tcnt > spritegroup
pointers to the different sprites of the entity
@ NT_GENERAL
General news (from towns)
void InitializeBuildingCounts(Town *t)
Initialise building counts for a town.
CommandCost CmdTownGrowthRate(DoCommandFlag flags, TownID town_id, uint16_t growth_rate)
Change the growth rate of the town.
uint8_t GetHouseConstructionTick(Tile t)
Gets the construction stage of a house.
static void MakeTownHouse(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
Write house information into the map.
@ CBID_HOUSE_AUTOSLOPE
Called to determine if one can alter the ground below a house tile.
static void UpdateTownGrowthRate(Town *t)
Updates town growth rate.
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
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.
@ AT_OILRIG
Oilrig airport.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
GUISettings gui
settings related to the GUI
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
TrackedViewportSign sign
Location of name sign, UpdateVirtCoord updates this.
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
@ RATING_TUNNEL_BRIDGE_NEEDED_NEUTRAL
"Neutral"
static debug_inline bool IsRoadDepotTile(Tile t)
Return whether a tile is a road depot tile.
const char * GetName() const
Get the name of this grf.
static bool CheckFree2x2Area(TileIndex tile, int z, bool noslope)
Checks if a house of size 2x2 can be built at this tile.
@ TACT_BUY_RIGHTS
Buy exclusive transport rights.
uint8_t initial_city_size
multiplier for the initial size of the cities compared to towns
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TownLayout layout
tells us what kind of town we're building
static uint GetNormalGrowthRate(Town *t)
Calculates town growth rate in normal conditions (custom growth rate not set).
static Year year
Current year, starting at 0.
TownID GetTownIndex(Tile t)
Get the index of which town this house/street is attached to.
static bool IsTileAlignedToGrid(TileIndex tile, TownLayout layout)
Towns must all be placed on the same grid or when they eventually interpenetrate their road networks ...
@ FACIL_AIRPORT
Station with an airport.
@ EXPENSES_CONSTRUCTION
Construction costs.
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 ClearMakeHouseTile(TileIndex tile, Town *t, uint8_t counter, uint8_t stage, HouseID type, uint8_t random_bits)
Clears tile and builds a house or house part.
bool IsSea(Tile t)
Is it a sea water tile?
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.