44#include "table/strings.h"
47#include <unordered_set>
52 _tile_type_clear_procs,
53 _tile_type_rail_procs,
56 _tile_type_trees_procs,
57 _tile_type_station_procs,
58 _tile_type_water_procs,
59 _tile_type_void_procs,
60 _tile_type_industry_procs,
61 _tile_type_tunnelbridge_procs,
62 _tile_type_object_procs;
70 &_tile_type_clear_procs,
71 &_tile_type_rail_procs,
74 &_tile_type_trees_procs,
75 &_tile_type_station_procs,
76 &_tile_type_water_procs,
77 &_tile_type_void_procs,
78 &_tile_type_industry_procs,
79 &_tile_type_tunnelbridge_procs,
80 &_tile_type_object_procs,
91 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0,
92 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 17, 0, 15, 18, 0,
123 if (clamped !=
nullptr) *clamped =
false;
141 if (clamped !=
nullptr) *clamped = (pt.
x != old_pt.
x) || (pt.
y != old_pt.
y);
151 for (
int i = 0; i < 5; i++) z =
GetSlopePixelZ(
Clamp(pt.
x + std::max(z, 4) - 4, min_coord, max_x),
Clamp(pt.
y + std::max(z, 4) - 4, min_coord, max_y)) / 2;
152 for (
int m = 3; m > 0; m--) z =
GetSlopePixelZ(
Clamp(pt.
x + std::max(z, m) - m, min_coord, max_x),
Clamp(pt.
y + std::max(z, m) - m, min_coord, max_y)) / 2;
164 pt.
x =
Clamp(pt.
x, min_coord, max_x);
165 pt.
y =
Clamp(pt.
y, min_coord, max_y);
166 if (clamped !=
nullptr) *clamped = *clamped || (pt.
x != old_pt.
x) || (pt.
y != old_pt.
y);
205 s = (((highest_corner == CORNER_W) || (highest_corner == CORNER_S)) ?
SLOPE_SW :
SLOPE_NE);
209 s = (((highest_corner == CORNER_S) || (highest_corner == CORNER_E)) ?
SLOPE_SE :
SLOPE_NW);
220 default: NOT_REACHED();
260 default: NOT_REACHED();
269 case SLOPE_E:
return y >= x ? (1 + y - x) >> 1 : 0;
271 case SLOPE_W:
return x >= y ? (x - y) >> 1 : 0;
287 case SLOPE_EW:
return x >= y ? (x - y) >> 1 : (1 + y - x) >> 1;
298 default: NOT_REACHED();
366 static const Slope corners[4][4] = {
376 if (halftile_test == corners[edge][0]) z2 +=
TILE_HEIGHT;
377 if (halftile_test == corners[edge][1]) z1 +=
TILE_HEIGHT;
379 if ((tileh & corners[edge][0]) != 0) z1 +=
TILE_HEIGHT;
380 if ((tileh & corners[edge][1]) != 0) z2 +=
TILE_HEIGHT;
401bool HasFoundationNW(
TileIndex tile,
Slope slope_here, uint z_here)
403 int z_W_here = z_here;
404 int z_N_here = z_here;
412 return (z_N_here > z_N) || (z_W_here > z_W);
416bool HasFoundationNE(
TileIndex tile,
Slope slope_here, uint z_here)
418 int z_E_here = z_here;
419 int z_N_here = z_here;
427 return (z_N_here > z_N) || (z_E_here > z_E);
442 uint sprite_block = 0;
451 if (!HasFoundationNW(ti->
tile, slope, z)) sprite_block += 1;
452 if (!HasFoundationNE(ti->
tile, slope, z)) sprite_block += 2;
455 SpriteID leveled_base = (sprite_block == 0 ? (int)SPR_FOUNDATION_BASE : (SPR_SLOPES_VIRTUAL_BASE + sprite_block * TRKFOUND_BLOCK_SIZE));
456 SpriteID inclined_base = SPR_SLOPES_VIRTUAL_BASE + SLOPES_INCLINED_OFFSET + sprite_block * TRKFOUND_BLOCK_SIZE;
487 int8_t x_bb = (((highest_corner == CORNER_W) || (highest_corner == CORNER_S)) ?
TILE_SIZE / 2 : 0);
488 int8_t y_bb = (((highest_corner == CORNER_S) || (highest_corner == CORNER_E)) ?
TILE_SIZE / 2 : 0);
494 Point pt = {(y_bb - x_bb) * 2, y_bb + x_bb};
506 int8_t x_bb = (((halftile_corner == CORNER_W) || (halftile_corner == CORNER_S)) ?
TILE_SIZE / 2 : 0);
507 int8_t y_bb = (((halftile_corner == CORNER_S) || (halftile_corner == CORNER_E)) ?
TILE_SIZE / 2 : 0);
513 Point pt = {(y_bb - x_bb) * 2, y_bb + x_bb};
550 if (remove) RemoveDockingTile(tile);
655 auto check_tile = [](uint x, uint y) ->
bool {
661 if (!check_tile(0, 0))
return false;
662 if (!check_tile(0,
Map::SizeY()))
return false;
663 if (!check_tile(
Map::SizeX(), 0))
return false;
668 if (!check_tile(x, 0))
return false;
669 if (!check_tile(x,
Map::SizeY()))
return false;
672 if (!check_tile(0, y))
return false;
673 if (!check_tile(
Map::SizeX(), y))
return false;
688 bool do_clear =
false;
701 return CommandCost(STR_ERROR_CLEARING_LIMIT_REACHED);
708 if (coa !=
nullptr && coa->
first_tile != tile) {
715 return CommandCost(STR_ERROR_CAN_T_BUILD_ON_WATER);
753 bool had_success =
false;
756 int limit = (c ==
nullptr ? INT32_MAX :
GB(c->
clear_limit, 16, 16));
765 last_error = std::move(ret);
775 if (ret.
GetCost() > 0 && money < 0) {
776 return { cost, ret.
GetCost() };
790 if (ret.
GetCost() != 0 && --limit <= 0)
break;
795 return { had_success ? cost : last_error, 0 };
814 static const uint32_t feedbacks[] = {
815 0xD8F, 0x1296, 0x2496, 0x4357, 0x8679, 0x1030E, 0x206CD, 0x403FE, 0x807B8, 0x1004B2, 0x2006A8, 0x4004B2, 0x800B87
838 tile =
TileIndex{(tile.base() >> 1) ^ (-(int32_t)(tile.base() & 1) & feedback)};
841 _cur_tileloop_tile = tile;
844void InitializeLandscape()
859static const uint8_t _genterrain_tbl_1[5] = { 10, 22, 33, 37, 4 };
860static const uint8_t _genterrain_tbl_2[5] = { 0, 0, 0, 0, 33 };
862static void GenerateTerrain(
int type, uint flag)
867 const Sprite *templ = GetSprite((((r >> 24) * _genterrain_tbl_1[type]) >> 8) + _genterrain_tbl_2[type] + SPR_MAPGEN_BEGIN,
SpriteType::MapGen);
868 if (templ ==
nullptr) UserError(
"Map generator sprites could not be loaded");
876 if (x <= edge_distance || y <= edge_distance)
return;
879 uint w = templ->
width;
884 const uint8_t *p =
reinterpret_cast<const uint8_t *
>(templ->
data);
886 if ((flag & 4) != 0) {
895 default: NOT_REACHED();
897 if (xw + yw >
Map::Size() - bias)
return;
901 if (yw < xw + bias)
return;
905 if (xw + yw <
Map::Size() + bias)
return;
909 if (xw < yw + bias)
return;
924 default: NOT_REACHED();
929 for (uint w_cur = w; w_cur != 0; --w_cur) {
942 for (uint h_cur = h; h_cur != 0; --h_cur) {
956 for (uint w_cur = w; w_cur != 0; --w_cur) {
970 for (uint h_cur = h; h_cur != 0; --h_cur) {
984static void CreateDesertOrRainForest(uint desert_tropic_line)
988 for (
const auto tile :
Map::Iterate()) {
993 auto allows_desert = [tile, desert_tropic_line](
auto &offset) {
997 if (std::all_of(std::begin(_make_desert_or_rainforest_data), std::end(_make_desert_or_rainforest_data), allows_desert)) {
1008 for (
const auto tile :
Map::Iterate()) {
1013 auto allows_rainforest = [tile](
auto &offset) {
1017 if (std::all_of(std::begin(_make_desert_or_rainforest_data), std::end(_make_desert_or_rainforest_data), allows_rainforest)) {
1032 int reference_height;
1039 uint max_hill_distance = 1;
1040 uint required_num_hills = 3;
1044 max_hill_distance = 3;
1045 required_num_hills = 1;
1051 for (uint i = 0; i < max_hill_distance; i++) {
1061 return num_hills >= required_num_hills;
1089 for (uint loops = 0; loops < 2; ++loops) {
1113 uint diameter = std::max((river_length), 16u);
1123 uint radius = diameter / 2;
1151 if (tile == begin)
return false;
1158 if (!
IsTileFlat(tile, &height_lake))
return false;
1162 if (height_lake != height_begin)
return false;
1203 bool flat_river_found =
false;
1204 bool sloped_river_found =
false;
1223 desired_slope = other_slope;
1224 sloped_river_found =
true;
1229 if (
IsTileFlat(other_tile)) flat_river_found =
true;
1233 if (!sloped_river_found && !flat_river_found)
return;
1236 if (!sloped_river_found && flat_river_found) desired_slope =
SLOPE_FLAT;
1263 Slope to_change = cur_slope ^ desired_slope;
1274 to_change = cur_slope ^ desired_slope;
1296 if (!
IsWaterTile(downstream_tile) && !downstream_is_ocean) {
1313 if (cur_slope == desired_slope) {
1336 if (height_end > height_begin)
return false;
1339 if (slope_end == slope_begin && height_end < height_begin)
return true;
1365 if (sea.size() > limit)
return false;
1393 std::unordered_set<TileIndex> marks;
1394 marks.insert(begin);
1396 std::vector<TileIndex> queue;
1397 queue.push_back(begin);
1405 for (
size_t i = 0; i != queue.size(); i++) {
1409 if (
IsTileFlat(end, &height_end) && (height_end < height_begin || (height_end == height_begin &&
IsWaterTile(end)))) {
1412 const uint MAX_SEA_SIZE_THRESHOLD = 1024;
1413 const uint SEA_SIZE_THRESHOLD = std::min(
static_cast<uint
>(2 * std::sqrt(
Map::SizeX() *
Map::SizeY())), MAX_SEA_SIZE_THRESHOLD);
1414 std::unordered_set<TileIndex> sea;
1417 if (found_edge || sea.size() > SEA_SIZE_THRESHOLD) {
1444 bool main_river =
false;
1447 std::tie(found, main_river) =
FlowRiver(spring, end, min_river_length);
1448 }
else if (queue.size() > 32) {
1461 return { found, main_river };
1470 if (amount == 0)
return;
1473 const uint num_short_rivers = wells - std::max(1u, wells / 10);
1477 for (; wells > num_short_rivers; wells--) {
1480 for (
int tries = 0; tries < 512; tries++) {
1492 for (; wells != 0; wells--) {
1495 for (
int tries = 0; tries < 128; tries++) {
1507 ConvertGroundTilesIntoWaterTiles();
1536 std::array<int, MAX_TILE_HEIGHT + 1> histogram = {};
1538 std::array<int, MAX_TILE_HEIGHT + 1> edge_histogram = {};
1545 if (edge_multiplier != 0) {
1550 edge_histogram[h]++;
1557 uint land_tiles =
Map::Size() - histogram[0];
1558 int best_score = land_tiles;
1561 int goal_tiles = land_tiles * coverage / 100;
1567 int current_tiles = 0;
1568 for (; h > 0; h--) {
1569 current_tiles += histogram[h];
1570 int current_score = goal_tiles - current_tiles;
1579 if (edge_multiplier != 0 && h > 1) {
1581 current_score -= edge_histogram[1] * edge_multiplier;
1583 current_score -= edge_histogram[h] * edge_multiplier;
1586 if (std::abs(current_score) < std::abs(best_score)) {
1587 best_score = current_score;
1621 static constexpr uint GLS_HEIGHTMAP = 3;
1622 static constexpr uint GLS_TERRAGENESIS = 4;
1623 static constexpr uint GLS_ORIGINAL = 2;
1624 static constexpr uint GLS_TROPIC = 12;
1625 static constexpr uint GLS_OTHER = 0;
1648 GenerateTerrain(2, 0);
1651 uint flag =
GB(r, 7, 2) | 4;
1653 GenerateTerrain(4, flag);
1662 GenerateTerrain(0, 0);
1665 uint flag =
GB(r, 7, 2) | 4;
1667 GenerateTerrain(0, flag);
1673 GenerateTerrain(3, flag);
1683 for (; i != 0; --i) {
1698 ConvertGroundTilesIntoWaterTiles();
1709 CreateDesertOrRainForest(desert_tropic_line);
1723void OnTick_Station();
1724void OnTick_Industry();
1729void CallLandscapeTick()
void DeleteAnimatedTile(TileIndex tile, bool immediate)
Stops animation on the given tile.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
void ClearBridgeMiddle(Tile t)
Removes bridges from the given, that is bridges along the X and Y axis.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is 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.
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?
A sort-of mixin that implements 'at(pos)' and 'operator[](pos)' only for a specific enum class.
Generate TileIndices around a center tile or tile area, with increasing distance.
static std::unique_ptr< TileIterator > Create(TileIndex corner1, TileIndex corner2, bool diagonal)
Create either an OrthogonalTileIterator or DiagonalTileIterator given the diagonal parameter.
static YearMonthDay ConvertDateToYMD(Date date)
Converts a Date to a Year, Month & Day.
static Date date
Current date in days (day counter).
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Map accessors for 'clear' tiles.
bool IsClearGround(Tile t, ClearGround ct)
Set the type of clear tile.
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
void SetClearGroundDensity(Tile t, ClearGround type, uint density)
Sets ground type and density in one go, also sets the counter to 0.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Auto
don't allow building on structures
@ NoWater
don't allow building on water
@ Execute
execute the given command
@ Bankrupt
company bankrupts, skip money check, skip vehicle on tile check in some cases
@ ForceClearTile
do not only remove the object on the tile, but also clear any water left on it
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
GUI Functions related to companies.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
DiagDirection ChangeDiagDir(DiagDirection d, DiagDirDiff delta)
Applies a difference on a DiagDirection.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirDiff
Enumeration for the difference between to DiagDirection.
@ DIAGDIRDIFF_END
Used for iterations.
@ DIAGDIRDIFF_90RIGHT
90 degrees right
@ DIAGDIRDIFF_90LEFT
90 degrees left
@ DIAGDIRDIFF_REVERSE
Reverse directions.
@ DIAGDIRDIFF_SAME
Same directions.
@ DIAGDIRDIFF_BEGIN
Used for iterations.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ DIAGDIR_END
Used for iterations.
@ DIAGDIR_BEGIN
Used for iterations.
@ EXPENSES_CONSTRUCTION
Construction costs.
@ ClearCanal
Price for destroying canals.
@ ClearWater
Price for destroying water e.g. see, rives.
EffectVehicle * CreateEffectVehicleAbove(int x, int y, int z, EffectVehicleType type)
Create an effect vehicle above a particular location.
Functions related to effect vehicles.
@ EV_EXPLOSION_SMALL
Various explosions.
@ EV_EXPLOSION_LARGE
Various explosions.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23)
Error reporting related functions.
Declarations for savegames operations.
Types for recording game performance data.
@ PFE_GL_LANDSCAPE
Time spent processing other world features.
Table used to generate deserts and/or rainforests.
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.
@ LG_TERRAGENESIS
TerraGenesis Perlin landscape generator.
static const uint CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
Value for custom sea level in difficulty settings.
@ GWP_LANDSCAPE
Create the landscape.
@ GWP_RIVER
Create the rivers.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
PauseModes _pause_mode
The current pause mode.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
@ MapGen
Special sprite for the map generator.
uint8_t LowestSnowLine()
Get the lowest possible snow line height, either variable or static.
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
bool IsSnowLineSet()
Has a snow line table already been loaded.
void ClearSnowLine()
Clear the variable snow line table and free the memory.
static std::unique_ptr< SnowLine > _snow_line
Description of the snow line throughout the year.
void SetSnowLine(std::unique_ptr< SnowLine > &&snow_line)
Set a variable snow line, as loaded from a newgrf file.
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.
bool LoadHeightmap(DetailedFileType dft, std::string_view filename)
Load a heightmap from file and change the map in its current dimensions to a landscape representing t...
void FixSlopes()
This function takes care of the fact that land in OpenTTD can never differ more than 1 in height.
Functions related to creating heightmaps from files.
uint GetPartialPixelZ(int x, int y, Slope corners)
Determines height at given coordinate of a slope.
static std::tuple< bool, bool > FlowRiver(TileIndex spring, TileIndex begin, uint min_river_length)
Try to flow the river down from a given begin.
int GetSlopePixelZOutsideMap(int x, int y)
Return world z coordinate of a given point of a tile, also for tiles outside the map (virtual "black"...
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
void OnTick_Companies()
Called every tick for updating some company info.
static bool TryMakeRiverTerminus(TileIndex tile, TileIndex begin)
Try to end a river at a tile which is not the sea.
static uint CalculateCoverageLine(uint coverage, uint edge_multiplier)
Calculate what height would be needed to cover N% of the landmass.
static bool IsValidRiverTerminusTile(TileIndex tile, uint height)
Is this a valid tile for the water feature at the end of a river?
static void CalculateSnowLine()
Calculate the line from which snow begins.
static const uint TILE_UPDATE_FREQUENCY_LOG
The logarithm of how many ticks it takes between tile updates (log base 2).
const EnumClassIndexContainer< std::array< const TileTypeProcs *, to_underlying(TileType::MaxSize)>, TileType > _tile_type_procs
Tile callback functions for each type of tile.
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every TILE_UPDATE_FREQU...
static bool FindSpring(TileIndex tile)
Find the spring of a river.
bool RiverFlowsDown(TileIndex begin, TileIndex end)
Check whether a river at begin could (logically) flow down to end.
static void CreateRivers()
Actually (try to) create some rivers.
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
int GetSlopeZInCorner(Slope tileh, Corner corner)
Determine the Z height of a corner relative to TileZ.
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 GetSlopePixelZOnEdge(Slope tileh, DiagDirection edge, int &z1, int &z2)
Determine the Z height of the corners of a specific tile edge.
static void MakeWetlands(TileIndex centre, uint height, uint river_length)
Make wetlands around the given tile.
void OnTick_LinkGraph()
Spawn or join a link graph job or compress a link graph if any link graph is due to do so.
Point InverseRemapCoords2(int x, int y, bool clamp_to_map, bool *clamped)
Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
const TileTypeProcs _tile_type_town_procs
Tile callback functions for a town.
static void MakeLake(TileIndex lake_centre, uint height_lake)
Make a lake centred on the given tile, of a random diameter.
void OnTick_Town()
Iterate through all towns and call their tick handler.
static uint8_t CalculateDesertLine()
Calculate the line (in height) between desert and tropic.
const uint8_t _slope_to_sprite_offset[32]
landscape slope => sprite
std::tuple< CommandCost, Money > CmdClearArea(DoCommandFlags flags, TileIndex tile, TileIndex start_tile, bool diagonal)
Clear a big piece of landscape.
const TileTypeProcs _tile_type_road_procs
Tile callback functions for road tiles.
uint ApplyFoundationToSlope(Foundation f, Slope &s)
Applies a foundation to a slope.
bool IsMapSurroundedByWater()
Check if all tiles on the map edge should be considered water borders.
static bool CountConnectedSeaTiles(TileIndex tile, std::unordered_set< TileIndex > &sea, const uint limit)
Find the size of a patch of connected sea tiles.
bool GenerateLandscape(uint8_t mode)
CommandCost CmdLandscapeClear(DoCommandFlags flags, TileIndex tile)
Clear a piece of landscape.
void RiverMakeWider(TileIndex tile, TileIndex origin_tile)
Widen a river by expanding into adjacent tiles via circular tile search.
static const uint TILE_UPDATE_FREQUENCY
How many ticks it takes between tile updates (has to be a power of 2).
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
Functions related to OTTD's landscape.
std::tuple< Slope, int > GetFoundationPixelSlope(TileIndex tile)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
uint ApplyPixelFoundationToSlope(Foundation f, Slope &s)
Applies a foundation to a slope.
Point InverseRemapCoords(int x, int y)
Map 2D viewport or smallmap coordinate to 3D world or tile coordinate.
Command definitions related to landscape (slopes etc.).
Types related to the landscape.
@ Arctic
Landscape with snow levels.
@ Tropic
Landscape with distinct rainforests and deserts,.
@ Random
Randomise borders.
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.
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
TileIndex AddTileIndexDiffCWrap(TileIndex tile, TileIndexDiffC diff)
Add a TileIndexDiffC to a TileIndex and returns the new one.
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.
TileIndexDiffC TileIndexDiffCByDiagDir(DiagDirection dir)
Returns the TileIndexDiffC offset from a DiagDirection.
static uint TileX(TileIndex tile)
Get the X component of a tile.
#define RandomTile()
Get a valid random tile.
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
static const uint MIN_MAP_SIZE_BITS
Minimal and maximal map width and height.
static const uint MAX_MAP_SIZE_BITS
Maximal size of map is equal to 2 ^ MAX_MAP_SIZE_BITS.
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
ClearedObjectArea * FindClearedObject(TileIndex tile)
Find the entry in _cleared_object_areas which occupies a certain tile.
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.
A number of safeguards to prevent using unsafe methods.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Functions/types related to saving and loading games.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
@ None
No tree placer algorithm.
bool IsSpecialRailFoundation(Foundation f)
Tests if a foundation is a special rail foundation for single horizontal/vertical track.
Slope SlopeWithThreeCornersRaised(Corner corner)
Returns the slope with all except one corner raised.
Corner OppositeCorner(Corner corner)
Returns the opposite corner.
static constexpr Corner GetHalftileSlopeCorner(Slope s)
Returns the leveled halftile of a halftile slope.
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.
bool IsNonContinuousFoundation(Foundation f)
Tests if a foundation is a non-continuous foundation, i.e.
Corner GetHighestSlopeCorner(Slope s)
Returns the highest corner of a slope (one corner raised or a steep slope).
Corner GetHalftileFoundationCorner(Foundation f)
Returns the halftile corner of a halftile-foundation.
bool IsLeveledFoundation(Foundation f)
Tests if the foundation is a leveled foundation.
bool IsFoundation(Foundation f)
Tests for FOUNDATION_NONE.
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
bool IsSlopeWithThreeCornersRaised(Slope s)
Tests if a specific slope has exactly three corners raised.
bool IsInclinedSlope(Slope s)
Tests if a specific slope is an inclined slope.
Slope SteepSlope(Corner corner)
Returns a specific steep slope.
Corner GetRailFoundationCorner(Foundation f)
Returns the track corner of a special rail foundation.
static constexpr bool IsHalftileSlope(Slope s)
Checks for non-continuous slope on halftile foundations.
static constexpr int GetSlopeMaxPixelZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height)
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
static constexpr Slope HalftileSlope(Slope s, Corner corner)
Adds a halftile slope to a slope.
Slope ComplementSlope(Slope s)
Return the complement of a slope.
Slope SlopeWithOneCornerRaised(Corner corner)
Returns the slope with a specific corner raised.
bool IsInclinedFoundation(Foundation f)
Tests if the foundation is an inclined foundation.
Corner
Enumeration of tile corners.
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_NS
north and south corner are raised
@ SLOPE_E
the east corner of the tile is raised
@ SLOPE_WSE
west, south and east corner are raised
@ SLOPE_S
the south corner of the tile is raised
@ SLOPE_N
the north corner of the tile is raised
@ SLOPE_SEN
south, east and north corner are raised
@ SLOPE_ENW
east, north and west corner are 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_NWS
north, west and south 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)
@ SLOPE_EW
east and west corner are raised
@ SLOPE_STEEP
indicates the slope is steep
Foundation
Enumeration for Foundations.
@ FOUNDATION_INCLINED_X
The tile has an along X-axis inclined foundation.
@ FOUNDATION_STEEP_BOTH
The tile has a steep slope. The lowest corner is raised by a foundation and the upper halftile is lev...
@ FOUNDATION_INCLINED_Y
The tile has an along Y-axis inclined foundation.
@ FOUNDATION_STEEP_LOWER
The tile has a steep slope. The lowest corner is raised by a foundation to allow building railroad on...
Functions to cache sprites in memory.
This file contains all sprite-related enums and defines.
static const SpriteID SPR_HALFTILE_FOUNDATION_BASE
Halftile foundations.
Functions related to stations.
Maps accessors for stations.
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Keeps track of removed objects during execution/testruns of commands.
TileIndex first_tile
The first tile being cleared, which then causes the whole object to be cleared.
uint32_t clear_limit
Amount of tiles we can (still) clear (times 65536).
bool freeform_edges
allow terraforming the tiles at the map edges
uint8_t map_height_limit
the maximum allowed heightlevel
GenworldMaxHeight terrain_type
the mountainousness of the landscape
uint8_t quantity_sea_lakes
the amount of seas/lakes
std::string name
Name of the file.
DetailedFileType detailed
Detailed file type.
uint8_t amount_of_rivers
the amount of rivers
TreePlacer tree_placer
the tree placer algorithm
uint8_t min_river_length
the minimum river length
uint8_t snow_coverage
the amount of snow coverage on the map
uint8_t desert_coverage
the amount of desert coverage on the map
LandscapeType landscape
the landscape we're currently in
uint8_t snow_line_height
the configured snow line height (deduced from "snow_coverage")
uint8_t land_generator
the landscape generator
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
GameCreationSettings game_creation
settings used during the creation of a game (map)
Size related data of the map.
static uint SizeX()
Get the size of the map along the X.
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 uint SizeY()
Get the size of the map along the Y.
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
static uint LogX()
Logarithm of the map size along the X side.
static uint LogY()
Logarithm of the map size along the y side.
static uint MaxY()
Gets the maximum Y coordinate within the map, including TileType::Void.
static uint MaxX()
Gets the maximum X coordinate within the map, including TileType::Void.
static uint Size()
Get the size of the map.
static Titem * Get(auto index)
Returns Titem with given index.
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Coord3D< uint8_t > extent
Size of bounding box.
Data structure describing a sprite.
uint16_t width
Width of the sprite.
uint16_t height
Height of the sprite.
std::byte data[]
Sprite data.
Tile description for the 'land area information' tool.
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.
void GenerateTerrainPerlin()
The main new land generator using Perlin noise.
Functions for the Perlin noise enhanced map generator.
bool MayAnimateTile(TileIndex tile)
Test if a tile may be animated.
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
std::tuple< Slope, int > GetTilePixelSlopeOutsideMap(int x, int y)
Return the slope of a given tile, also for tiles outside the map (virtual "black" tiles).
std::tuple< Slope, int > GetTileSlopeZ(TileIndex tile)
Return the slope of a given tile inside the map.
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.
static uint TileHeight(Tile tile)
Returns the height of a tile.
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
bool IsValidTile(Tile tile)
Checks if a tile is valid.
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
void SetTileHeight(Tile tile, uint height)
Sets the height of a tile.
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
void SetTropicZone(Tile tile, TropicZone type)
Set the tropic zone.
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
static constexpr uint MAX_TILE_HEIGHT
Maximum allowed tile height.
@ TROPICZONE_RAINFOREST
Rainforest tile.
@ TROPICZONE_DESERT
Tile is desert.
@ TROPICZONE_NORMAL
Normal tropiczone.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
static constexpr uint TILE_SIZE
Tile size in world coordinates.
static constexpr uint TILE_PIXELS
Pixel distance between tile columns/rows in ZOOM_BASE.
static constexpr uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
TileType
The different types of tiles.
@ MaxSize
The maximum possible number of tile types to be stored in map.
@ Void
Invisible tiles at the SW and SE border.
@ Clear
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition of the game-calendar-timer.
Definition of the tick-based game-timer.
TransportType
Available types of transport.
void PlaceTree(TileIndex tile, uint32_t r, bool keep_density)
Make a random tree tile of the given tile.
Command definitions related to tree tiles.
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
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.
Functions related to (drawing on) viewports.
Map accessors for void tiles.
void MakeVoid(Tile t)
Make a nice void tile ;)
Functions related to water management.
void ClearNeighbourNonFloodingStates(TileIndex tile)
Clear non-flooding state of the tiles around a tile.
void MakeRiverAndModifyDesertZoneAround(TileIndex tile)
Make a river tile and remove desert directly around it.
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
bool IsRiver(Tile t)
Is it a river water tile?
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
bool IsCanal(Tile t)
Is it a canal tile?
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
bool IsCoastTile(Tile t)
Is it a coast tile.
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
void InvalidateWaterRegion(TileIndex tile)
Marks the water region that tile is part of as invalid.
Handles dividing the water in the map into regions to assist pathfinding.
void YapfBuildRiver(TileIndex start_tile, TileIndex end_tile, TileIndex spring_tile, bool main_river)
Builds a river from the start tile to the end tile.
Pathfinder for river building.