Codechange: Use CargoArray for linkgraph refresher. (#13165)
[openttd-github.git] / src / map_func.h
blob3d0331be63a219abdd966efb8a5a16c1662f4f04
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file map_func.h Functions related to maps. */
10 #ifndef MAP_FUNC_H
11 #define MAP_FUNC_H
13 #include "core/math_func.hpp"
14 #include "tile_type.h"
15 #include "map_type.h"
16 #include "direction_func.h"
18 /**
19 * Wrapper class to abstract away the way the tiles are stored. It is
20 * intended to be used to access the "map" data of a single tile.
22 * The wrapper is expected to be fully optimized away by the compiler, even
23 * with low optimization levels except when completely disabling it.
25 class Tile {
26 private:
27 friend struct Map;
28 /**
29 * Data that is stored per tile. Also used TileExtended for this.
30 * Look at docs/landscape.html for the exact meaning of the members.
32 struct TileBase {
33 uint8_t type; ///< The type (bits 4..7), bridges (2..3), rainforest/desert (0..1)
34 uint8_t height; ///< The height of the northern corner.
35 uint16_t m2; ///< Primarily used for indices to towns, industries and stations
36 uint8_t m1; ///< Primarily used for ownership information
37 uint8_t m3; ///< General purpose
38 uint8_t m4; ///< General purpose
39 uint8_t m5; ///< General purpose
42 static_assert(sizeof(TileBase) == 8);
44 /**
45 * Data that is stored per tile. Also used TileBase for this.
46 * Look at docs/landscape.html for the exact meaning of the members.
48 struct TileExtended {
49 uint8_t m6; ///< General purpose
50 uint8_t m7; ///< Primarily used for newgrf support
51 uint16_t m8; ///< General purpose
54 static TileBase *base_tiles; ///< Pointer to the tile-array.
55 static TileExtended *extended_tiles; ///< Pointer to the extended tile-array.
57 TileIndex tile; ///< The tile to access the map data for.
59 public:
60 /**
61 * Create the tile wrapper for the given tile.
62 * @param tile The tile to access the map for.
64 debug_inline Tile(TileIndex tile) : tile(tile) {}
66 /**
67 * Create the tile wrapper for the given tile.
68 * @param tile The tile to access the map for.
70 Tile(uint tile) : tile(tile) {}
72 /**
73 * Implicit conversion to the TileIndex.
75 debug_inline constexpr operator TileIndex() const { return tile; }
77 /**
78 * Implicit conversion to the uint for bounds checking.
80 debug_inline constexpr operator uint() const { return tile.base(); }
82 /**
83 * The type (bits 4..7), bridges (2..3), rainforest/desert (0..1)
85 * Look at docs/landscape.html for the exact meaning of the data.
86 * @param tile The tile to get the data for.
87 * @return reference to the byte holding the data.
89 debug_inline uint8_t &type()
91 return base_tiles[tile.base()].type;
94 /**
95 * The height of the northern corner
97 * Look at docs/landscape.html for the exact meaning of the data.
98 * @param tile The tile to get the height for.
99 * @return reference to the byte holding the height.
101 debug_inline uint8_t &height()
103 return base_tiles[tile.base()].height;
107 * Primarily used for ownership information
109 * Look at docs/landscape.html for the exact meaning of the data.
110 * @param tile The tile to get the data for.
111 * @return reference to the byte holding the data.
113 debug_inline uint8_t &m1()
115 return base_tiles[tile.base()].m1;
119 * Primarily used for indices to towns, industries and stations
121 * Look at docs/landscape.html for the exact meaning of the data.
122 * @param tile The tile to get the data for.
123 * @return reference to the uint16_t holding the data.
125 debug_inline uint16_t &m2()
127 return base_tiles[tile.base()].m2;
131 * General purpose
133 * Look at docs/landscape.html for the exact meaning of the data.
134 * @param tile The tile to get the data for.
135 * @return reference to the byte holding the data.
137 debug_inline uint8_t &m3()
139 return base_tiles[tile.base()].m3;
143 * General purpose
145 * Look at docs/landscape.html for the exact meaning of the data.
146 * @param tile The tile to get the data for.
147 * @return reference to the byte holding the data.
149 debug_inline uint8_t &m4()
151 return base_tiles[tile.base()].m4;
155 * General purpose
157 * Look at docs/landscape.html for the exact meaning of the data.
158 * @param tile The tile to get the data for.
159 * @return reference to the byte holding the data.
161 debug_inline uint8_t &m5()
163 return base_tiles[tile.base()].m5;
167 * General purpose
169 * Look at docs/landscape.html for the exact meaning of the data.
170 * @param tile The tile to get the data for.
171 * @return reference to the byte holding the data.
173 debug_inline uint8_t &m6()
175 return extended_tiles[tile.base()].m6;
179 * Primarily used for newgrf support
181 * Look at docs/landscape.html for the exact meaning of the data.
182 * @param tile The tile to get the data for.
183 * @return reference to the byte holding the data.
185 debug_inline uint8_t &m7()
187 return extended_tiles[tile.base()].m7;
191 * General purpose
193 * Look at docs/landscape.html for the exact meaning of the data.
194 * @param tile The tile to get the data for.
195 * @return reference to the uint16_t holding the data.
197 debug_inline uint16_t &m8()
199 return extended_tiles[tile.base()].m8;
204 * Size related data of the map.
206 struct Map {
207 private:
209 * Iterator to iterate all Tiles
211 struct Iterator {
212 typedef Tile value_type;
213 typedef Tile *pointer;
214 typedef Tile &reference;
215 typedef size_t difference_type;
216 typedef std::forward_iterator_tag iterator_category;
218 explicit Iterator(TileIndex index) : index(index) {}
219 bool operator==(const Iterator &other) const { return this->index == other.index; }
220 bool operator!=(const Iterator &other) const { return !(*this == other); }
221 Tile operator*() const { return this->index; }
222 Iterator & operator++() { this->index++; return *this; }
223 private:
224 TileIndex index;
228 * Iterable ensemble of all Tiles
230 struct IterateWrapper {
231 Iterator begin() { return Iterator(0); }
232 Iterator end() { return Iterator(Map::Size()); }
233 bool empty() { return false; }
236 static uint log_x; ///< 2^_map_log_x == _map_size_x
237 static uint log_y; ///< 2^_map_log_y == _map_size_y
238 static uint size_x; ///< Size of the map along the X
239 static uint size_y; ///< Size of the map along the Y
240 static uint size; ///< The number of tiles on the map
241 static uint tile_mask; ///< _map_size - 1 (to mask the mapsize)
243 public:
244 static void Allocate(uint size_x, uint size_y);
247 * Logarithm of the map size along the X side.
248 * @note try to avoid using this one
249 * @return 2^"return value" == Map::SizeX()
251 debug_inline static uint LogX()
253 return Map::log_x;
257 * Logarithm of the map size along the y side.
258 * @note try to avoid using this one
259 * @return 2^"return value" == Map::SizeY()
261 static inline uint LogY()
263 return Map::log_y;
267 * Get the size of the map along the X
268 * @return the number of tiles along the X of the map
270 debug_inline static uint SizeX()
272 return Map::size_x;
276 * Get the size of the map along the Y
277 * @return the number of tiles along the Y of the map
279 static inline uint SizeY()
281 return Map::size_y;
285 * Get the size of the map
286 * @return the number of tiles of the map
288 debug_inline static uint Size()
290 return Map::size;
294 * Gets the maximum X coordinate within the map, including MP_VOID
295 * @return the maximum X coordinate
297 debug_inline static uint MaxX()
299 return Map::SizeX() - 1;
303 * Gets the maximum Y coordinate within the map, including MP_VOID
304 * @return the maximum Y coordinate
306 static inline uint MaxY()
308 return Map::SizeY() - 1;
313 * 'Wraps' the given "tile" so it is within the map.
314 * It does this by masking the 'high' bits of.
315 * @param tile the tile to 'wrap'
317 static inline TileIndex WrapToMap(TileIndex tile)
319 return tile.base() & Map::tile_mask;
323 * Scales the given value by the map size, where the given value is
324 * for a 256 by 256 map.
325 * @param n the value to scale
326 * @return the scaled size
328 static inline uint ScaleBySize(uint n)
330 /* Subtract 12 from shift in order to prevent integer overflow
331 * for large values of n. It's safe since the min mapsize is 64x64. */
332 return CeilDiv(n << (Map::LogX() + Map::LogY() - 12), 1 << 4);
336 * Scales the given value by the maps circumference, where the given
337 * value is for a 256 by 256 map
338 * @param n the value to scale
339 * @return the scaled size
341 static inline uint ScaleBySize1D(uint n)
343 /* Normal circumference for the X+Y is 256+256 = 1<<9
344 * Note, not actually taking the full circumference into account,
345 * just half of it. */
346 return CeilDiv((n << Map::LogX()) + (n << Map::LogY()), 1 << 9);
350 * Check whether the map has been initialized, as to not try to save the map
351 * during crashlog when the map is not there yet.
352 * @return true when the map has been allocated/initialized.
354 static bool IsInitialized()
356 return Tile::base_tiles != nullptr;
360 * Returns an iterable ensemble of all Tiles
361 * @return an iterable ensemble of all Tiles
363 static IterateWrapper Iterate() { return IterateWrapper(); }
367 * Returns the TileIndex of a coordinate.
369 * @param x The x coordinate of the tile
370 * @param y The y coordinate of the tile
371 * @return The TileIndex calculated by the coordinate
373 debug_inline static TileIndex TileXY(uint x, uint y)
375 return (y << Map::LogX()) + x;
379 * Calculates an offset for the given coordinate(-offset).
381 * This function calculate an offset value which can be added to a
382 * #TileIndex. The coordinates can be negative.
384 * @param x The offset in x direction
385 * @param y The offset in y direction
386 * @return The resulting offset value of the given coordinate
387 * @see ToTileIndexDiff(TileIndexDiffC)
389 inline TileIndexDiff TileDiffXY(int x, int y)
391 /* Multiplication gives much better optimization on MSVC than shifting.
392 * 0 << shift isn't optimized to 0 properly.
393 * Typically x and y are constants, and then this doesn't result
394 * in any actual multiplication in the assembly code.. */
395 return (y * Map::SizeX()) + x;
399 * Get a tile from the virtual XY-coordinate.
400 * @param x The virtual x coordinate of the tile.
401 * @param y The virtual y coordinate of the tile.
402 * @return The TileIndex calculated by the coordinate.
404 debug_inline static TileIndex TileVirtXY(uint x, uint y)
406 return (y >> 4 << Map::LogX()) + (x >> 4);
411 * Get the X component of a tile
412 * @param tile the tile to get the X component of
413 * @return the X component
415 debug_inline static uint TileX(TileIndex tile)
417 return tile.base() & Map::MaxX();
421 * Get the Y component of a tile
422 * @param tile the tile to get the Y component of
423 * @return the Y component
425 debug_inline static uint TileY(TileIndex tile)
427 return tile.base() >> Map::LogX();
431 * Return the offset between two tiles from a TileIndexDiffC struct.
433 * This function works like #TileDiffXY(int, int) and returns the
434 * difference between two tiles.
436 * @param tidc The coordinate of the offset as TileIndexDiffC
437 * @return The difference between two tiles.
438 * @see TileDiffXY(int, int)
440 inline TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
442 return TileDiffXY(tidc.x, tidc.y);
447 * Adds a given offset to a tile.
449 * @param tile The tile to add an offset to.
450 * @param offset The offset to add.
451 * @return The resulting tile.
453 #ifndef _DEBUG
454 constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset) { return tile + offset; }
455 #else
456 TileIndex TileAdd(TileIndex tile, TileIndexDiff offset);
457 #endif
460 * Adds a given offset to a tile.
462 * @param tile The tile to add an offset to.
463 * @param x The x offset to add to the tile.
464 * @param y The y offset to add to the tile.
465 * @return The resulting tile.
467 inline TileIndex TileAddXY(TileIndex tile, int x, int y)
469 return TileAdd(tile, TileDiffXY(x, y));
472 TileIndex TileAddWrap(TileIndex tile, int addx, int addy);
475 * Returns the TileIndexDiffC offset from a DiagDirection.
477 * @param dir The given direction
478 * @return The offset as TileIndexDiffC value
480 inline TileIndexDiffC TileIndexDiffCByDiagDir(DiagDirection dir)
482 extern const TileIndexDiffC _tileoffs_by_diagdir[DIAGDIR_END];
484 assert(IsValidDiagDirection(dir));
485 return _tileoffs_by_diagdir[dir];
489 * Returns the TileIndexDiffC offset from a Direction.
491 * @param dir The given direction
492 * @return The offset as TileIndexDiffC value
494 inline TileIndexDiffC TileIndexDiffCByDir(Direction dir)
496 extern const TileIndexDiffC _tileoffs_by_dir[DIR_END];
498 assert(IsValidDirection(dir));
499 return _tileoffs_by_dir[dir];
503 * Add a TileIndexDiffC to a TileIndex and returns the new one.
505 * Returns tile + the diff given in diff. If the result tile would end up
506 * outside of the map, INVALID_TILE is returned instead.
508 * @param tile The base tile to add the offset on
509 * @param diff The offset to add on the tile
510 * @return The resulting TileIndex
512 inline TileIndex AddTileIndexDiffCWrap(TileIndex tile, TileIndexDiffC diff)
514 int x = TileX(tile) + diff.x;
515 int y = TileY(tile) + diff.y;
516 /* Negative value will become big positive value after cast */
517 if ((uint)x >= Map::SizeX() || (uint)y >= Map::SizeY()) return INVALID_TILE;
518 return TileXY(x, y);
522 * Returns the diff between two tiles
524 * @param tile_a from tile
525 * @param tile_b to tile
526 * @return the difference between tila_a and tile_b
528 inline TileIndexDiffC TileIndexToTileIndexDiffC(TileIndex tile_a, TileIndex tile_b)
530 TileIndexDiffC difference;
532 difference.x = TileX(tile_a) - TileX(tile_b);
533 difference.y = TileY(tile_a) - TileY(tile_b);
535 return difference;
538 /* Functions to calculate distances */
539 uint DistanceManhattan(TileIndex, TileIndex); ///< also known as L1-Norm. Is the shortest distance one could go over diagonal tracks (or roads)
540 uint DistanceSquare(TileIndex, TileIndex); ///< euclidian- or L2-Norm squared
541 uint DistanceMax(TileIndex, TileIndex); ///< also known as L-Infinity-Norm
542 uint DistanceMaxPlusManhattan(TileIndex, TileIndex); ///< Max + Manhattan
543 uint DistanceFromEdge(TileIndex); ///< shortest distance from any edge of the map
544 uint DistanceFromEdgeDir(TileIndex, DiagDirection); ///< distance from the map edge in given direction
547 * Convert an Axis to a TileIndexDiff
549 * @param axis The Axis
550 * @return The resulting TileIndexDiff in southern direction (either SW or SE).
552 inline TileIndexDiff TileOffsByAxis(Axis axis)
554 extern const TileIndexDiffC _tileoffs_by_axis[];
556 assert(IsValidAxis(axis));
557 return ToTileIndexDiff(_tileoffs_by_axis[axis]);
561 * Convert a DiagDirection to a TileIndexDiff
563 * @param dir The DiagDirection
564 * @return The resulting TileIndexDiff
565 * @see TileIndexDiffCByDiagDir
567 inline TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
569 extern const TileIndexDiffC _tileoffs_by_diagdir[DIAGDIR_END];
571 assert(IsValidDiagDirection(dir));
572 return ToTileIndexDiff(_tileoffs_by_diagdir[dir]);
576 * Convert a Direction to a TileIndexDiff.
578 * @param dir The direction to convert from
579 * @return The resulting TileIndexDiff
581 inline TileIndexDiff TileOffsByDir(Direction dir)
583 extern const TileIndexDiffC _tileoffs_by_dir[DIR_END];
585 assert(IsValidDirection(dir));
586 return ToTileIndexDiff(_tileoffs_by_dir[dir]);
590 * Adds a Direction to a tile.
592 * @param tile The current tile
593 * @param dir The direction in which we want to step
594 * @return the moved tile
596 inline TileIndex TileAddByDir(TileIndex tile, Direction dir)
598 return TileAdd(tile, TileOffsByDir(dir));
602 * Adds a DiagDir to a tile.
604 * @param tile The current tile
605 * @param dir The direction in which we want to step
606 * @return the moved tile
608 inline TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
610 return TileAdd(tile, TileOffsByDiagDir(dir));
614 * Determines the DiagDirection to get from one tile to another.
615 * The tiles do not necessarily have to be adjacent.
616 * @param tile_from Origin tile
617 * @param tile_to Destination tile
618 * @return DiagDirection from tile_from towards tile_to, or INVALID_DIAGDIR if the tiles are not on an axis
620 inline DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
622 int dx = (int)TileX(tile_to) - (int)TileX(tile_from);
623 int dy = (int)TileY(tile_to) - (int)TileY(tile_from);
624 if (dx == 0) {
625 if (dy == 0) return INVALID_DIAGDIR;
626 return (dy < 0 ? DIAGDIR_NW : DIAGDIR_SE);
627 } else {
628 if (dy != 0) return INVALID_DIAGDIR;
629 return (dx < 0 ? DIAGDIR_NE : DIAGDIR_SW);
634 * A callback function type for searching tiles.
636 * @param tile The tile to test
637 * @param user_data additional data for the callback function to use
638 * @return A boolean value, depend on the definition of the function.
640 typedef bool TestTileOnSearchProc(TileIndex tile, void *user_data);
642 bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data);
643 bool CircularTileSearch(TileIndex *tile, uint radius, uint w, uint h, TestTileOnSearchProc proc, void *user_data);
646 * Get a random tile out of a given seed.
647 * @param r the random 'seed'
648 * @return a valid tile
650 inline TileIndex RandomTileSeed(uint32_t r)
652 return Map::WrapToMap(r);
656 * Get a valid random tile.
657 * @note a define so 'random' gets inserted in the place where it is actually
658 * called, thus making the random traces more explicit.
659 * @return a valid tile
661 #define RandomTile() RandomTileSeed(Random())
663 uint GetClosestWaterDistance(TileIndex tile, bool water);
665 #endif /* MAP_FUNC_H */