4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file landscape.cpp Functions related to the landscape (slopes etc.). */
12 /** @defgroup SnowLineGroup Snowline functions and data structures */
15 #include "heightmap.h"
16 #include "clear_map.h"
17 #include "spritecache.h"
18 #include "viewport_func.h"
19 #include "command_func.h"
20 #include "landscape.h"
25 #include "date_func.h"
27 #include "effectvehicle_func.h"
28 #include "landscape_type.h"
29 #include "animated_tile_func.h"
30 #include "core/random_func.hpp"
31 #include "object_base.h"
32 #include "company_func.h"
33 #include "pathfinder/npf/aystar.h"
34 #include "saveload/saveload.h"
38 #include "table/strings.h"
39 #include "table/sprites.h"
41 #include "safeguards.h"
43 extern const TileTypeProcs
44 _tile_type_clear_procs
,
45 _tile_type_rail_procs
,
46 _tile_type_road_procs
,
47 _tile_type_town_procs
,
48 _tile_type_trees_procs
,
49 _tile_type_station_procs
,
50 _tile_type_water_procs
,
51 _tile_type_void_procs
,
52 _tile_type_industry_procs
,
53 _tile_type_tunnelbridge_procs
,
54 _tile_type_object_procs
;
57 * Tile callback functions for each type of tile.
58 * @ingroup TileCallbackGroup
61 const TileTypeProcs
* const _tile_type_procs
[16] = {
62 &_tile_type_clear_procs
, ///< Callback functions for MP_CLEAR tiles
63 &_tile_type_rail_procs
, ///< Callback functions for MP_RAILWAY tiles
64 &_tile_type_road_procs
, ///< Callback functions for MP_ROAD tiles
65 &_tile_type_town_procs
, ///< Callback functions for MP_HOUSE tiles
66 &_tile_type_trees_procs
, ///< Callback functions for MP_TREES tiles
67 &_tile_type_station_procs
, ///< Callback functions for MP_STATION tiles
68 &_tile_type_water_procs
, ///< Callback functions for MP_WATER tiles
69 &_tile_type_void_procs
, ///< Callback functions for MP_VOID tiles
70 &_tile_type_industry_procs
, ///< Callback functions for MP_INDUSTRY tiles
71 &_tile_type_tunnelbridge_procs
, ///< Callback functions for MP_TUNNELBRIDGE tiles
72 &_tile_type_object_procs
, ///< Callback functions for MP_OBJECT tiles
75 /** landscape slope => sprite */
76 extern const byte _slope_to_sprite_offset
[32] = {
77 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0,
78 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 17, 0, 15, 18, 0,
82 * Description of the snow line throughout the year.
84 * If it is \c NULL, a static snowline height is used, as set by \c _settings_game.game_creation.snow_line_height.
85 * Otherwise it points to a table loaded from a newGRF file that describes the variable snowline.
86 * @ingroup SnowLineGroup
87 * @see GetSnowLine() GameCreationSettings
89 static SnowLine
*_snow_line
= NULL
;
92 * Applies a foundation to a slope.
94 * @pre Foundation and slope must be valid combined.
95 * @param f The #Foundation.
96 * @param s The #Slope to modify.
97 * @return Increment to the tile Z coordinate.
99 uint
ApplyFoundationToSlope(Foundation f
, Slope
*s
)
101 if (!IsFoundation(f
)) return 0;
103 if (IsLeveledFoundation(f
)) {
104 uint dz
= 1 + (IsSteepSlope(*s
) ? 1 : 0);
109 if (f
!= FOUNDATION_STEEP_BOTH
&& IsNonContinuousFoundation(f
)) {
110 *s
= HalftileSlope(*s
, GetHalftileFoundationCorner(f
));
114 if (IsSpecialRailFoundation(f
)) {
115 *s
= SlopeWithThreeCornersRaised(OppositeCorner(GetRailFoundationCorner(f
)));
119 uint dz
= IsSteepSlope(*s
) ? 1 : 0;
120 Corner highest_corner
= GetHighestSlopeCorner(*s
);
123 case FOUNDATION_INCLINED_X
:
124 *s
= (((highest_corner
== CORNER_W
) || (highest_corner
== CORNER_S
)) ? SLOPE_SW
: SLOPE_NE
);
127 case FOUNDATION_INCLINED_Y
:
128 *s
= (((highest_corner
== CORNER_S
) || (highest_corner
== CORNER_E
)) ? SLOPE_SE
: SLOPE_NW
);
131 case FOUNDATION_STEEP_LOWER
:
132 *s
= SlopeWithOneCornerRaised(highest_corner
);
135 case FOUNDATION_STEEP_BOTH
:
136 *s
= HalftileSlope(SlopeWithOneCornerRaised(highest_corner
), highest_corner
);
139 default: NOT_REACHED();
146 * Determines height at given coordinate of a slope
147 * @param x x coordinate
148 * @param y y coordinate
149 * @param corners slope to examine
150 * @return height of given point of given slope
152 uint
GetPartialPixelZ(int x
, int y
, Slope corners
)
154 if (IsHalftileSlope(corners
)) {
155 switch (GetHalftileSlopeCorner(corners
)) {
157 if (x
- y
>= 0) return GetSlopeMaxPixelZ(corners
);
161 if (x
- (y
^ 0xF) >= 0) return GetSlopeMaxPixelZ(corners
);
165 if (y
- x
>= 0) return GetSlopeMaxPixelZ(corners
);
169 if ((y
^ 0xF) - x
>= 0) return GetSlopeMaxPixelZ(corners
);
172 default: NOT_REACHED();
178 switch (RemoveHalftileSlope(corners
)) {
258 z
= 1 + ((x
+ y
) >> 1);
262 z
= 1 + ((x
+ (y
^ 0xF)) >> 1);
266 z
= 1 + (((x
^ 0xF) + (y
^ 0xF)) >> 1);
270 z
= 1 + (((x
^ 0xF) + y
) >> 1);
279 int GetSlopePixelZ(int x
, int y
)
281 TileIndex tile
= TileVirtXY(x
, y
);
283 return _tile_type_procs
[GetTileType(tile
)]->get_slope_z_proc(tile
, x
, y
);
287 * Determine the Z height of a corner relative to TileZ.
289 * @pre The slope must not be a halftile slope.
291 * @param tileh The slope.
292 * @param corner The corner.
293 * @return Z position of corner relative to TileZ.
295 int GetSlopeZInCorner(Slope tileh
, Corner corner
)
297 assert(!IsHalftileSlope(tileh
));
298 return ((tileh
& SlopeWithOneCornerRaised(corner
)) != 0 ? 1 : 0) + (tileh
== SteepSlope(corner
) ? 1 : 0);
302 * Determine the Z height of the corners of a specific tile edge
304 * @note If a tile has a non-continuous halftile foundation, a corner can have different heights wrt. its edges.
306 * @pre z1 and z2 must be initialized (typ. with TileZ). The corner heights just get added.
308 * @param tileh The slope of the tile.
309 * @param edge The edge of interest.
310 * @param z1 Gets incremented by the height of the first corner of the edge. (near corner wrt. the camera)
311 * @param z2 Gets incremented by the height of the second corner of the edge. (far corner wrt. the camera)
313 void GetSlopePixelZOnEdge(Slope tileh
, DiagDirection edge
, int *z1
, int *z2
)
315 static const Slope corners
[4][4] = {
316 /* corner | steep slope
318 {SLOPE_E
, SLOPE_N
, SLOPE_STEEP_E
, SLOPE_STEEP_N
}, // DIAGDIR_NE, z1 = E, z2 = N
319 {SLOPE_S
, SLOPE_E
, SLOPE_STEEP_S
, SLOPE_STEEP_E
}, // DIAGDIR_SE, z1 = S, z2 = E
320 {SLOPE_S
, SLOPE_W
, SLOPE_STEEP_S
, SLOPE_STEEP_W
}, // DIAGDIR_SW, z1 = S, z2 = W
321 {SLOPE_W
, SLOPE_N
, SLOPE_STEEP_W
, SLOPE_STEEP_N
}, // DIAGDIR_NW, z1 = W, z2 = N
324 int halftile_test
= (IsHalftileSlope(tileh
) ? SlopeWithOneCornerRaised(GetHalftileSlopeCorner(tileh
)) : 0);
325 if (halftile_test
== corners
[edge
][0]) *z2
+= TILE_HEIGHT
; // The slope is non-continuous in z2. z2 is on the upper side.
326 if (halftile_test
== corners
[edge
][1]) *z1
+= TILE_HEIGHT
; // The slope is non-continuous in z1. z1 is on the upper side.
328 if ((tileh
& corners
[edge
][0]) != 0) *z1
+= TILE_HEIGHT
; // z1 is raised
329 if ((tileh
& corners
[edge
][1]) != 0) *z2
+= TILE_HEIGHT
; // z2 is raised
330 if (RemoveHalftileSlope(tileh
) == corners
[edge
][2]) *z1
+= TILE_HEIGHT
; // z1 is highest corner of a steep slope
331 if (RemoveHalftileSlope(tileh
) == corners
[edge
][3]) *z2
+= TILE_HEIGHT
; // z2 is highest corner of a steep slope
335 * Get slope of a tile on top of a (possible) foundation
336 * If a tile does not have a foundation, the function returns the same as GetTileSlope.
338 * @param tile The tile of interest.
339 * @param z returns the z of the foundation slope. (Can be NULL, if not needed)
340 * @return The slope on top of the foundation.
342 Slope
GetFoundationSlope(TileIndex tile
, int *z
)
344 Slope tileh
= GetTileSlope(tile
, z
);
345 Foundation f
= _tile_type_procs
[GetTileType(tile
)]->get_foundation_proc(tile
, tileh
);
346 uint z_inc
= ApplyFoundationToSlope(f
, &tileh
);
347 if (z
!= NULL
) *z
+= z_inc
;
352 bool HasFoundationNW(TileIndex tile
, Slope slope_here
, uint z_here
)
356 int z_W_here
= z_here
;
357 int z_N_here
= z_here
;
358 GetSlopePixelZOnEdge(slope_here
, DIAGDIR_NW
, &z_W_here
, &z_N_here
);
360 Slope slope
= GetFoundationPixelSlope(TILE_ADDXY(tile
, 0, -1), &z
);
363 GetSlopePixelZOnEdge(slope
, DIAGDIR_SE
, &z_W
, &z_N
);
365 return (z_N_here
> z_N
) || (z_W_here
> z_W
);
369 bool HasFoundationNE(TileIndex tile
, Slope slope_here
, uint z_here
)
373 int z_E_here
= z_here
;
374 int z_N_here
= z_here
;
375 GetSlopePixelZOnEdge(slope_here
, DIAGDIR_NE
, &z_E_here
, &z_N_here
);
377 Slope slope
= GetFoundationPixelSlope(TILE_ADDXY(tile
, -1, 0), &z
);
380 GetSlopePixelZOnEdge(slope
, DIAGDIR_SW
, &z_E
, &z_N
);
382 return (z_N_here
> z_N
) || (z_E_here
> z_E
);
386 * Draw foundation \a f at tile \a ti. Updates \a ti.
387 * @param ti Tile to draw foundation on
388 * @param f Foundation to draw
390 void DrawFoundation(TileInfo
*ti
, Foundation f
)
392 if (!IsFoundation(f
)) return;
394 /* Two part foundations must be drawn separately */
395 assert(f
!= FOUNDATION_STEEP_BOTH
);
397 uint sprite_block
= 0;
399 Slope slope
= GetFoundationPixelSlope(ti
->tile
, &z
);
401 /* Select the needed block of foundations sprites
402 * Block 0: Walls at NW and NE edge
403 * Block 1: Wall at NE edge
404 * Block 2: Wall at NW edge
405 * Block 3: No walls at NW or NE edge
407 if (!HasFoundationNW(ti
->tile
, slope
, z
)) sprite_block
+= 1;
408 if (!HasFoundationNE(ti
->tile
, slope
, z
)) sprite_block
+= 2;
410 /* Use the original slope sprites if NW and NE borders should be visible */
411 SpriteID leveled_base
= (sprite_block
== 0 ? (int)SPR_FOUNDATION_BASE
: (SPR_SLOPES_VIRTUAL_BASE
+ sprite_block
* SPR_TRKFOUND_BLOCK_SIZE
));
412 SpriteID inclined_base
= SPR_SLOPES_VIRTUAL_BASE
+ SPR_SLOPES_INCLINED_OFFSET
+ sprite_block
* SPR_TRKFOUND_BLOCK_SIZE
;
413 SpriteID halftile_base
= SPR_HALFTILE_FOUNDATION_BASE
+ sprite_block
* SPR_HALFTILE_BLOCK_SIZE
;
415 if (IsSteepSlope(ti
->tileh
)) {
416 if (!IsNonContinuousFoundation(f
)) {
417 /* Lower part of foundation */
418 AddSortableSpriteToDraw(
419 leveled_base
+ (ti
->tileh
& ~SLOPE_STEEP
), PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
423 Corner highest_corner
= GetHighestSlopeCorner(ti
->tileh
);
424 ti
->z
+= ApplyPixelFoundationToSlope(f
, &ti
->tileh
);
426 if (IsInclinedFoundation(f
)) {
427 /* inclined foundation */
428 byte inclined
= highest_corner
* 2 + (f
== FOUNDATION_INCLINED_Y
? 1 : 0);
430 AddSortableSpriteToDraw(inclined_base
+ inclined
, PAL_NONE
, ti
->x
, ti
->y
,
431 f
== FOUNDATION_INCLINED_X
? 16 : 1,
432 f
== FOUNDATION_INCLINED_Y
? 16 : 1,
435 OffsetGroundSprite(31, 9);
436 } else if (IsLeveledFoundation(f
)) {
437 AddSortableSpriteToDraw(leveled_base
+ SlopeWithOneCornerRaised(highest_corner
), PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
- TILE_HEIGHT
);
438 OffsetGroundSprite(31, 1);
439 } else if (f
== FOUNDATION_STEEP_LOWER
) {
440 /* one corner raised */
441 OffsetGroundSprite(31, 1);
443 /* halftile foundation */
444 int x_bb
= (((highest_corner
== CORNER_W
) || (highest_corner
== CORNER_S
)) ? 8 : 0);
445 int y_bb
= (((highest_corner
== CORNER_S
) || (highest_corner
== CORNER_E
)) ? 8 : 0);
447 AddSortableSpriteToDraw(halftile_base
+ highest_corner
, PAL_NONE
, ti
->x
+ x_bb
, ti
->y
+ y_bb
, 8, 8, 7, ti
->z
+ TILE_HEIGHT
);
448 OffsetGroundSprite(31, 9);
451 if (IsLeveledFoundation(f
)) {
452 /* leveled foundation */
453 AddSortableSpriteToDraw(leveled_base
+ ti
->tileh
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
454 OffsetGroundSprite(31, 1);
455 } else if (IsNonContinuousFoundation(f
)) {
456 /* halftile foundation */
457 Corner halftile_corner
= GetHalftileFoundationCorner(f
);
458 int x_bb
= (((halftile_corner
== CORNER_W
) || (halftile_corner
== CORNER_S
)) ? 8 : 0);
459 int y_bb
= (((halftile_corner
== CORNER_S
) || (halftile_corner
== CORNER_E
)) ? 8 : 0);
461 AddSortableSpriteToDraw(halftile_base
+ halftile_corner
, PAL_NONE
, ti
->x
+ x_bb
, ti
->y
+ y_bb
, 8, 8, 7, ti
->z
);
462 OffsetGroundSprite(31, 9);
463 } else if (IsSpecialRailFoundation(f
)) {
464 /* anti-zig-zag foundation */
466 if (ti
->tileh
== SLOPE_NS
|| ti
->tileh
== SLOPE_EW
) {
467 /* half of leveled foundation under track corner */
468 spr
= leveled_base
+ SlopeWithThreeCornersRaised(GetRailFoundationCorner(f
));
470 /* tile-slope = sloped along X/Y, foundation-slope = three corners raised */
471 spr
= inclined_base
+ 2 * GetRailFoundationCorner(f
) + ((ti
->tileh
== SLOPE_SW
|| ti
->tileh
== SLOPE_NE
) ? 1 : 0);
473 AddSortableSpriteToDraw(spr
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
474 OffsetGroundSprite(31, 9);
476 /* inclined foundation */
477 byte inclined
= GetHighestSlopeCorner(ti
->tileh
) * 2 + (f
== FOUNDATION_INCLINED_Y
? 1 : 0);
479 AddSortableSpriteToDraw(inclined_base
+ inclined
, PAL_NONE
, ti
->x
, ti
->y
,
480 f
== FOUNDATION_INCLINED_X
? 16 : 1,
481 f
== FOUNDATION_INCLINED_Y
? 16 : 1,
484 OffsetGroundSprite(31, 9);
486 ti
->z
+= ApplyPixelFoundationToSlope(f
, &ti
->tileh
);
490 void DoClearSquare(TileIndex tile
)
492 /* If the tile can have animation and we clear it, delete it from the animated tile list. */
493 if (_tile_type_procs
[GetTileType(tile
)]->animate_tile_proc
!= NULL
) DeleteAnimatedTile(tile
);
495 MakeClear(tile
, CLEAR_GRASS
, _generating_world
? 3 : 0);
496 MarkTileDirtyByTile(tile
);
500 * Returns information about trackdirs and signal states.
501 * If there is any trackbit at 'side', return all trackdirbits.
502 * For TRANSPORT_ROAD, return no trackbits if there is no roadbit (of given subtype) at given side.
503 * @param tile tile to get info about
504 * @param mode transport type
505 * @param sub_mode for TRANSPORT_ROAD, roadtypes to check
506 * @param side side we are entering from, INVALID_DIAGDIR to return all trackbits
507 * @return trackdirbits and other info depending on 'mode'
509 TrackStatus
GetTileTrackStatus(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
511 return _tile_type_procs
[GetTileType(tile
)]->get_tile_track_status_proc(tile
, mode
, sub_mode
, side
);
515 * Change the owner of a tile
516 * @param tile Tile to change
517 * @param old_owner Current owner of the tile
518 * @param new_owner New owner of the tile
520 void ChangeTileOwner(TileIndex tile
, Owner old_owner
, Owner new_owner
)
522 _tile_type_procs
[GetTileType(tile
)]->change_tile_owner_proc(tile
, old_owner
, new_owner
);
525 void GetTileDesc(TileIndex tile
, TileDesc
*td
)
527 _tile_type_procs
[GetTileType(tile
)]->get_tile_desc_proc(tile
, td
);
531 * Has a snow line table already been loaded.
532 * @return true if the table has been loaded already.
533 * @ingroup SnowLineGroup
537 return _snow_line
!= NULL
;
541 * Set a variable snow line, as loaded from a newgrf file.
542 * @param table the 12 * 32 byte table containing the snowline for each day
543 * @ingroup SnowLineGroup
545 void SetSnowLine(byte table
[SNOW_LINE_MONTHS
][SNOW_LINE_DAYS
])
547 _snow_line
= CallocT
<SnowLine
>(1);
548 _snow_line
->lowest_value
= 0xFF;
549 memcpy(_snow_line
->table
, table
, sizeof(_snow_line
->table
));
551 for (uint i
= 0; i
< SNOW_LINE_MONTHS
; i
++) {
552 for (uint j
= 0; j
< SNOW_LINE_DAYS
; j
++) {
553 _snow_line
->highest_value
= max(_snow_line
->highest_value
, table
[i
][j
]);
554 _snow_line
->lowest_value
= min(_snow_line
->lowest_value
, table
[i
][j
]);
560 * Get the current snow line, either variable or static.
561 * @return the snow line height.
562 * @ingroup SnowLineGroup
566 if (_snow_line
== NULL
) return _settings_game
.game_creation
.snow_line_height
;
569 ConvertDateToYMD(_date
, &ymd
);
570 return _snow_line
->table
[ymd
.month
][ymd
.day
];
574 * Get the highest possible snow line height, either variable or static.
575 * @return the highest snow line height.
576 * @ingroup SnowLineGroup
578 byte
HighestSnowLine()
580 return _snow_line
== NULL
? _settings_game
.game_creation
.snow_line_height
: _snow_line
->highest_value
;
584 * Get the lowest possible snow line height, either variable or static.
585 * @return the lowest snow line height.
586 * @ingroup SnowLineGroup
588 byte
LowestSnowLine()
590 return _snow_line
== NULL
? _settings_game
.game_creation
.snow_line_height
: _snow_line
->lowest_value
;
594 * Clear the variable snow line table and free the memory.
595 * @ingroup SnowLineGroup
604 * Clear a piece of landscape
605 * @param tile tile to clear
606 * @param flags of operation to conduct
610 * @return the cost of this operation or an error
612 CommandCost
CmdLandscapeClear(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
614 CommandCost
cost(EXPENSES_CONSTRUCTION
);
615 bool do_clear
= false;
616 /* Test for stuff which results in water when cleared. Then add the cost to also clear the water. */
617 if ((flags
& DC_FORCE_CLEAR_TILE
) && HasTileWaterClass(tile
) && IsTileOnWater(tile
) && !IsWaterTile(tile
) && !IsCoastTile(tile
)) {
618 if ((flags
& DC_AUTO
) && GetWaterClass(tile
) == WATER_CLASS_CANAL
) return_cmd_error(STR_ERROR_MUST_DEMOLISH_CANAL_FIRST
);
620 cost
.AddCost(GetWaterClass(tile
) == WATER_CLASS_CANAL
? _price
[PR_CLEAR_CANAL
] : _price
[PR_CLEAR_WATER
]);
623 Company
*c
= (flags
& (DC_AUTO
| DC_BANKRUPT
)) ? NULL
: Company::GetIfValid(_current_company
);
624 if (c
!= NULL
&& (int)GB(c
->clear_limit
, 16, 16) < 1) {
625 return_cmd_error(STR_ERROR_CLEARING_LIMIT_REACHED
);
628 const ClearedObjectArea
*coa
= FindClearedObject(tile
);
630 /* If this tile was the first tile which caused object destruction, always
631 * pass it on to the tile_type_proc. That way multiple test runs and the exec run stay consistent. */
632 if (coa
!= NULL
&& coa
->first_tile
!= tile
) {
633 /* If this tile belongs to an object which was already cleared via another tile, pretend it has been
635 * However, we need to check stuff, which is not the same for all object tiles. (e.g. being on water or not) */
637 /* If a object is removed, it leaves either bare land or water. */
638 if ((flags
& DC_NO_WATER
) && HasTileWaterClass(tile
) && IsTileOnWater(tile
)) {
639 return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
642 cost
.AddCost(_tile_type_procs
[GetTileType(tile
)]->clear_tile_proc(tile
, flags
));
645 if (flags
& DC_EXEC
) {
646 if (c
!= NULL
) c
->clear_limit
-= 1 << 16;
647 if (do_clear
) DoClearSquare(tile
);
653 * Clear a big piece of landscape
654 * @param tile end tile of area dragging
655 * @param flags of operation to conduct
656 * @param p1 start tile of area dragging
657 * @param p2 various bitstuffed data.
658 * bit 0: Whether to use the Orthogonal (0) or Diagonal (1) iterator.
660 * @return the cost of this operation or an error
662 CommandCost
CmdClearArea(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
664 if (p1
>= MapSize()) return CMD_ERROR
;
666 Money money
= GetAvailableMoneyForCommand();
667 CommandCost
cost(EXPENSES_CONSTRUCTION
);
668 CommandCost last_error
= CMD_ERROR
;
669 bool had_success
= false;
671 const Company
*c
= (flags
& (DC_AUTO
| DC_BANKRUPT
)) ? NULL
: Company::GetIfValid(_current_company
);
672 int limit
= (c
== NULL
? INT32_MAX
: GB(c
->clear_limit
, 16, 16));
674 TileIterator
*iter
= HasBit(p2
, 0) ? (TileIterator
*)new DiagonalTileIterator(tile
, p1
) : new OrthogonalTileIterator(tile
, p1
);
675 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
677 CommandCost ret
= DoCommand(t
, 0, 0, flags
& ~DC_EXEC
, CMD_LANDSCAPE_CLEAR
);
681 /* We may not clear more tiles. */
682 if (c
!= NULL
&& GB(c
->clear_limit
, 16, 16) < 1) break;
687 if (flags
& DC_EXEC
) {
688 money
-= ret
.GetCost();
689 if (ret
.GetCost() > 0 && money
< 0) {
690 _additional_cash_required
= ret
.GetCost();
694 DoCommand(t
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
696 /* draw explosion animation...
697 * Disable explosions when game is paused. Looks silly and blocks the view. */
698 if ((t
== tile
|| t
== p1
) && _pause_mode
== PM_UNPAUSED
) {
699 /* big explosion in two corners, or small explosion for single tiles */
700 CreateEffectVehicleAbove(TileX(t
) * TILE_SIZE
+ TILE_SIZE
/ 2, TileY(t
) * TILE_SIZE
+ TILE_SIZE
/ 2, 2,
701 TileX(tile
) == TileX(p1
) && TileY(tile
) == TileY(p1
) ? EV_EXPLOSION_SMALL
: EV_EXPLOSION_LARGE
705 /* When we're at the clearing limit we better bail (unneed) testing as well. */
706 if (ret
.GetCost() != 0 && --limit
<= 0) break;
712 return had_success
? cost
: last_error
;
716 TileIndex _cur_tileloop_tile
;
719 * Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks.
723 /* The pseudorandom sequence of tiles is generated using a Galois linear feedback
724 * shift register (LFSR). This allows a deterministic pseudorandom ordering, but
725 * still with minimal state and fast iteration. */
727 /* Maximal length LFSR feedback terms, from 12-bit (for 64x64 maps) to 24-bit (for 4096x4096 maps).
728 * Extracted from http://www.ece.cmu.edu/~koopman/lfsr/ */
729 static const uint32 feedbacks
[] = {
730 0xD8F, 0x1296, 0x2496, 0x4357, 0x8679, 0x1030E, 0x206CD, 0x403FE, 0x807B8, 0x1004B2, 0x2006A8, 0x4004B2, 0x800B87
732 assert_compile(lengthof(feedbacks
) == 2 * MAX_MAP_SIZE_BITS
- 2 * MIN_MAP_SIZE_BITS
+ 1);
733 const uint32 feedback
= feedbacks
[MapLogX() + MapLogY() - 2 * MIN_MAP_SIZE_BITS
];
735 /* We update every tile every 256 ticks, so divide the map size by 2^8 = 256 */
736 uint count
= 1 << (MapLogX() + MapLogY() - 8);
738 TileIndex tile
= _cur_tileloop_tile
;
739 /* The LFSR cannot have a zeroed state. */
742 /* Manually update tile 0 every 256 ticks - the LFSR never iterates over it itself. */
743 if (_tick_counter
% 256 == 0) {
744 _tile_type_procs
[GetTileType(0)]->tile_loop_proc(0);
749 _tile_type_procs
[GetTileType(tile
)]->tile_loop_proc(tile
);
751 /* Get the next tile in sequence using a Galois LFSR. */
752 tile
= (tile
>> 1) ^ (-(int32
)(tile
& 1) & feedback
);
755 _cur_tileloop_tile
= tile
;
758 void InitializeLandscape()
760 uint maxx
= MapMaxX();
761 uint maxy
= MapMaxY();
762 uint sizex
= MapSizeX();
765 for (y
= _settings_game
.construction
.freeform_edges
? 1 : 0; y
< maxy
; y
++) {
767 for (x
= _settings_game
.construction
.freeform_edges
? 1 : 0; x
< maxx
; x
++) {
768 MakeClear(sizex
* y
+ x
, CLEAR_GRASS
, 3);
769 SetTileHeight(sizex
* y
+ x
, 0);
770 SetTropicZone(sizex
* y
+ x
, TROPICZONE_NORMAL
);
771 ClearBridgeMiddle(sizex
* y
+ x
);
773 MakeVoid(sizex
* y
+ x
);
775 for (uint x
= 0; x
< sizex
; x
++) MakeVoid(sizex
* y
+ x
);
778 static const byte _genterrain_tbl_1
[5] = { 10, 22, 33, 37, 4 };
779 static const byte _genterrain_tbl_2
[5] = { 0, 0, 0, 0, 33 };
781 static void GenerateTerrain(int type
, uint flag
)
785 const Sprite
*templ
= GetSprite((((r
>> 24) * _genterrain_tbl_1
[type
]) >> 8) + _genterrain_tbl_2
[type
] + 4845, ST_MAPGEN
);
786 if (templ
== NULL
) usererror("Map generator sprites could not be loaded");
788 uint x
= r
& MapMaxX();
789 uint y
= (r
>> MapLogX()) & MapMaxY();
791 if (x
< 2 || y
< 2) return;
793 DiagDirection direction
= (DiagDirection
)GB(r
, 22, 2);
794 uint w
= templ
->width
;
795 uint h
= templ
->height
;
797 if (DiagDirToAxis(direction
) == AXIS_Y
) Swap(w
, h
);
799 const byte
*p
= templ
->data
;
801 if ((flag
& 4) != 0) {
802 uint xw
= x
* MapSizeY();
803 uint yw
= y
* MapSizeX();
804 uint bias
= (MapSizeX() + MapSizeY()) * 16;
807 default: NOT_REACHED();
809 if (xw
+ yw
> MapSize() - bias
) return;
813 if (yw
< xw
+ bias
) return;
817 if (xw
+ yw
< MapSize() + bias
) return;
821 if (xw
< yw
+ bias
) return;
826 if (x
+ w
>= MapMaxX() - 1) return;
827 if (y
+ h
>= MapMaxY() - 1) return;
829 TileIndex tile
= TileXY(x
, y
);
832 default: NOT_REACHED();
835 TileIndex tile_cur
= tile
;
837 for (uint w_cur
= w
; w_cur
!= 0; --w_cur
) {
838 if (GB(*p
, 0, 4) >= TileHeight(tile_cur
)) SetTileHeight(tile_cur
, GB(*p
, 0, 4));
842 tile
+= TileDiffXY(0, 1);
848 TileIndex tile_cur
= tile
;
850 for (uint h_cur
= h
; h_cur
!= 0; --h_cur
) {
851 if (GB(*p
, 0, 4) >= TileHeight(tile_cur
)) SetTileHeight(tile_cur
, GB(*p
, 0, 4));
853 tile_cur
+= TileDiffXY(0, 1);
855 tile
+= TileDiffXY(1, 0);
860 tile
+= TileDiffXY(w
- 1, 0);
862 TileIndex tile_cur
= tile
;
864 for (uint w_cur
= w
; w_cur
!= 0; --w_cur
) {
865 if (GB(*p
, 0, 4) >= TileHeight(tile_cur
)) SetTileHeight(tile_cur
, GB(*p
, 0, 4));
869 tile
+= TileDiffXY(0, 1);
874 tile
+= TileDiffXY(0, h
- 1);
876 TileIndex tile_cur
= tile
;
878 for (uint h_cur
= h
; h_cur
!= 0; --h_cur
) {
879 if (GB(*p
, 0, 4) >= TileHeight(tile_cur
)) SetTileHeight(tile_cur
, GB(*p
, 0, 4));
881 tile_cur
-= TileDiffXY(0, 1);
883 tile
+= TileDiffXY(1, 0);
890 #include "table/genland.h"
892 static void CreateDesertOrRainForest()
894 TileIndex update_freq
= MapSize() / 4;
895 const TileIndexDiffC
*data
;
896 uint max_desert_height
= CeilDiv(_settings_game
.construction
.max_heightlevel
, 4);
898 for (TileIndex tile
= 0; tile
!= MapSize(); ++tile
) {
899 if ((tile
% update_freq
) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE
);
901 if (!IsValidTile(tile
)) continue;
903 for (data
= _make_desert_or_rainforest_data
;
904 data
!= endof(_make_desert_or_rainforest_data
); ++data
) {
905 TileIndex t
= AddTileIndexDiffCWrap(tile
, *data
);
906 if (t
!= INVALID_TILE
&& (TileHeight(t
) >= max_desert_height
|| IsTileType(t
, MP_WATER
))) break;
908 if (data
== endof(_make_desert_or_rainforest_data
)) {
909 SetTropicZone(tile
, TROPICZONE_DESERT
);
913 for (uint i
= 0; i
!= 256; i
++) {
914 if ((i
% 64) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE
);
919 for (TileIndex tile
= 0; tile
!= MapSize(); ++tile
) {
920 if ((tile
% update_freq
) == 0) IncreaseGeneratingWorldProgress(GWP_LANDSCAPE
);
922 if (!IsValidTile(tile
)) continue;
924 for (data
= _make_desert_or_rainforest_data
;
925 data
!= endof(_make_desert_or_rainforest_data
); ++data
) {
926 TileIndex t
= AddTileIndexDiffCWrap(tile
, *data
);
927 if (t
!= INVALID_TILE
&& IsTileType(t
, MP_CLEAR
) && IsClearGround(t
, CLEAR_DESERT
)) break;
929 if (data
== endof(_make_desert_or_rainforest_data
)) {
930 SetTropicZone(tile
, TROPICZONE_RAINFOREST
);
936 * Find the spring of a river.
937 * @param tile The tile to consider for being the spring.
938 * @param user_data Ignored data.
939 * @return True iff it is suitable as a spring.
941 static bool FindSpring(TileIndex tile
, void *user_data
)
944 if (!IsTileFlat(tile
, &referenceHeight
) || IsWaterTile(tile
)) return false;
946 /* In the tropics rivers start in the rainforest. */
947 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
&& GetTropicZone(tile
) != TROPICZONE_RAINFOREST
) return false;
949 /* Are there enough higher tiles to warrant a 'spring'? */
951 for (int dx
= -1; dx
<= 1; dx
++) {
952 for (int dy
= -1; dy
<= 1; dy
++) {
953 TileIndex t
= TileAddWrap(tile
, dx
, dy
);
954 if (t
!= INVALID_TILE
&& GetTileMaxZ(t
) > referenceHeight
) num
++;
958 if (num
< 4) return false;
960 /* Are we near the top of a hill? */
961 for (int dx
= -16; dx
<= 16; dx
++) {
962 for (int dy
= -16; dy
<= 16; dy
++) {
963 TileIndex t
= TileAddWrap(tile
, dx
, dy
);
964 if (t
!= INVALID_TILE
&& GetTileMaxZ(t
) > referenceHeight
+ 2) return false;
972 * Make a connected lake; fill all tiles in the circular tile search that are connected.
973 * @param tile The tile to consider for lake making.
974 * @param user_data The height of the lake.
975 * @return Always false, so it continues searching.
977 static bool MakeLake(TileIndex tile
, void *user_data
)
979 uint height
= *(uint
*)user_data
;
980 if (!IsValidTile(tile
) || TileHeight(tile
) != height
|| !IsTileFlat(tile
)) return false;
981 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
&& GetTropicZone(tile
) == TROPICZONE_DESERT
) return false;
983 for (DiagDirection d
= DIAGDIR_BEGIN
; d
< DIAGDIR_END
; d
++) {
984 TileIndex t2
= tile
+ TileOffsByDiagDir(d
);
985 if (IsWaterTile(t2
)) {
986 MakeRiver(tile
, Random());
995 * Check whether a river at begin could (logically) flow down to end.
996 * @param begin The origin of the flow.
997 * @param end The destination of the flow.
998 * @return True iff the water can be flowing down.
1000 static bool FlowsDown(TileIndex begin
, TileIndex end
)
1002 assert(DistanceManhattan(begin
, end
) == 1);
1006 Slope slopeBegin
= GetTileSlope(begin
, &heightBegin
);
1007 Slope slopeEnd
= GetTileSlope(end
, &heightEnd
);
1009 return heightEnd
<= heightBegin
&&
1010 /* Slope either is inclined or flat; rivers don't support other slopes. */
1011 (slopeEnd
== SLOPE_FLAT
|| IsInclinedSlope(slopeEnd
)) &&
1012 /* Slope continues, then it must be lower... or either end must be flat. */
1013 ((slopeEnd
== slopeBegin
&& heightEnd
< heightBegin
) || slopeEnd
== SLOPE_FLAT
|| slopeBegin
== SLOPE_FLAT
);
1016 /* AyStar callback for checking whether we reached our destination. */
1017 static int32
River_EndNodeCheck(AyStar
*aystar
, OpenListNode
*current
)
1019 return current
->path
.node
.tile
== *(TileIndex
*)aystar
->user_target
? AYSTAR_FOUND_END_NODE
: AYSTAR_DONE
;
1022 /* AyStar callback for getting the cost of the current node. */
1023 static int32
River_CalculateG(AyStar
*aystar
, AyStarNode
*current
, OpenListNode
*parent
)
1025 return 1 + RandomRange(_settings_game
.game_creation
.river_route_random
);
1028 /* AyStar callback for getting the estimated cost to the destination. */
1029 static int32
River_CalculateH(AyStar
*aystar
, AyStarNode
*current
, OpenListNode
*parent
)
1031 return DistanceManhattan(*(TileIndex
*)aystar
->user_target
, current
->tile
);
1034 /* AyStar callback for getting the neighbouring nodes of the given node. */
1035 static void River_GetNeighbours(AyStar
*aystar
, OpenListNode
*current
)
1037 TileIndex tile
= current
->path
.node
.tile
;
1039 aystar
->num_neighbours
= 0;
1040 for (DiagDirection d
= DIAGDIR_BEGIN
; d
< DIAGDIR_END
; d
++) {
1041 TileIndex t2
= tile
+ TileOffsByDiagDir(d
);
1042 if (IsValidTile(t2
) && FlowsDown(tile
, t2
)) {
1043 aystar
->neighbours
[aystar
->num_neighbours
].tile
= t2
;
1044 aystar
->neighbours
[aystar
->num_neighbours
].direction
= INVALID_TRACKDIR
;
1045 aystar
->num_neighbours
++;
1050 /* AyStar callback when an route has been found. */
1051 static void River_FoundEndNode(AyStar
*aystar
, OpenListNode
*current
)
1053 for (PathNode
*path
= ¤t
->path
; path
!= NULL
; path
= path
->parent
) {
1054 TileIndex tile
= path
->node
.tile
;
1055 if (!IsWaterTile(tile
)) {
1056 MakeRiver(tile
, Random());
1057 /* Remove desert directly around the river tile. */
1058 CircularTileSearch(&tile
, 5, RiverModifyDesertZone
, NULL
);
1063 static const uint RIVER_HASH_SIZE
= 8; ///< The number of bits the hash for river finding should have.
1066 * Simple hash function for river tiles to be used by AyStar.
1067 * @param tile The tile to hash.
1068 * @param dir The unused direction.
1069 * @return The hash for the tile.
1071 static uint
River_Hash(uint tile
, uint dir
)
1073 return GB(TileHash(TileX(tile
), TileY(tile
)), 0, RIVER_HASH_SIZE
);
1077 * Actually build the river between the begin and end tiles using AyStar.
1078 * @param begin The begin of the river.
1079 * @param end The end of the river.
1081 static void BuildRiver(TileIndex begin
, TileIndex end
)
1084 MemSetT(&finder
, 0);
1085 finder
.CalculateG
= River_CalculateG
;
1086 finder
.CalculateH
= River_CalculateH
;
1087 finder
.GetNeighbours
= River_GetNeighbours
;
1088 finder
.EndNodeCheck
= River_EndNodeCheck
;
1089 finder
.FoundEndNode
= River_FoundEndNode
;
1090 finder
.user_target
= &end
;
1092 finder
.Init(River_Hash
, 1 << RIVER_HASH_SIZE
);
1096 start
.direction
= INVALID_TRACKDIR
;
1097 finder
.AddStartNode(&start
, 0);
1103 * Try to flow the river down from a given begin.
1104 * @param spring The springing point of the river.
1105 * @param begin The begin point we are looking from; somewhere down hill from the spring.
1106 * @return True iff a river could/has been built, otherwise false.
1108 static bool FlowRiver(TileIndex spring
, TileIndex begin
)
1110 #define SET_MARK(x) marks.insert(x)
1111 #define IS_MARKED(x) (marks.find(x) != marks.end())
1113 uint height
= TileHeight(begin
);
1114 if (IsWaterTile(begin
)) return DistanceManhattan(spring
, begin
) > _settings_game
.game_creation
.min_river_length
;
1116 std::set
<TileIndex
> marks
;
1119 /* Breadth first search for the closest tile we can flow down to. */
1120 std::list
<TileIndex
> queue
;
1121 queue
.push_back(begin
);
1124 uint count
= 0; // Number of tiles considered; to be used for lake location guessing.
1127 end
= queue
.front();
1130 uint height2
= TileHeight(end
);
1131 if (IsTileFlat(end
) && (height2
< height
|| (height2
== height
&& IsWaterTile(end
)))) {
1136 for (DiagDirection d
= DIAGDIR_BEGIN
; d
< DIAGDIR_END
; d
++) {
1137 TileIndex t2
= end
+ TileOffsByDiagDir(d
);
1138 if (IsValidTile(t2
) && !IS_MARKED(t2
) && FlowsDown(end
, t2
)) {
1141 queue
.push_back(t2
);
1144 } while (!queue
.empty());
1147 /* Flow further down hill. */
1148 found
= FlowRiver(spring
, end
);
1149 } else if (count
> 32) {
1150 /* Maybe we can make a lake. Find the Nth of the considered tiles. */
1151 TileIndex lakeCenter
= 0;
1152 int i
= RandomRange(count
- 1) + 1;
1153 std::set
<TileIndex
>::const_iterator cit
= marks
.begin();
1157 if (IsValidTile(lakeCenter
) &&
1158 /* A river, or lake, can only be built on flat slopes. */
1159 IsTileFlat(lakeCenter
) &&
1160 /* We want the lake to be built at the height of the river. */
1161 TileHeight(begin
) == TileHeight(lakeCenter
) &&
1162 /* We don't want the lake at the entry of the valley. */
1163 lakeCenter
!= begin
&&
1164 /* We don't want lakes in the desert. */
1165 (_settings_game
.game_creation
.landscape
!= LT_TROPIC
|| GetTropicZone(lakeCenter
) != TROPICZONE_DESERT
) &&
1166 /* We only want a lake if the river is long enough. */
1167 DistanceManhattan(spring
, lakeCenter
) > _settings_game
.game_creation
.min_river_length
) {
1169 MakeRiver(lakeCenter
, Random());
1170 uint range
= RandomRange(8) + 3;
1171 CircularTileSearch(&lakeCenter
, range
, MakeLake
, &height
);
1172 /* Call the search a second time so artefacts from going circular in one direction get (mostly) hidden. */
1174 CircularTileSearch(&lakeCenter
, range
, MakeLake
, &height
);
1180 if (found
) BuildRiver(begin
, end
);
1185 * Actually (try to) create some rivers.
1187 static void CreateRivers()
1189 int amount
= _settings_game
.game_creation
.amount_of_rivers
;
1190 if (amount
== 0) return;
1192 uint wells
= ScaleByMapSize(4 << _settings_game
.game_creation
.amount_of_rivers
);
1193 SetGeneratingWorldProgress(GWP_RIVER
, wells
+ 256 / 64); // Include the tile loop calls below.
1195 for (; wells
!= 0; wells
--) {
1196 IncreaseGeneratingWorldProgress(GWP_RIVER
);
1197 for (int tries
= 0; tries
< 128; tries
++) {
1198 TileIndex t
= RandomTile();
1199 if (!CircularTileSearch(&t
, 8, FindSpring
, NULL
)) continue;
1200 if (FlowRiver(t
, t
)) break;
1204 /* Run tile loop to update the ground density. */
1205 for (uint i
= 0; i
!= 256; i
++) {
1206 if (i
% 64 == 0) IncreaseGeneratingWorldProgress(GWP_RIVER
);
1211 void GenerateLandscape(byte mode
)
1213 /** Number of steps of landscape generation */
1214 enum GenLandscapeSteps
{
1215 GLS_HEIGHTMAP
= 3, ///< Loading a heightmap
1216 GLS_TERRAGENESIS
= 5, ///< Terragenesis generator
1217 GLS_ORIGINAL
= 2, ///< Original generator
1218 GLS_TROPIC
= 12, ///< Extra steps needed for tropic landscape
1219 GLS_OTHER
= 0, ///< Extra steps for other landscapes
1221 uint steps
= (_settings_game
.game_creation
.landscape
== LT_TROPIC
) ? GLS_TROPIC
: GLS_OTHER
;
1223 if (mode
== GWM_HEIGHTMAP
) {
1224 SetGeneratingWorldProgress(GWP_LANDSCAPE
, steps
+ GLS_HEIGHTMAP
);
1225 LoadHeightmap(_file_to_saveload
.detail_ftype
, _file_to_saveload
.name
);
1226 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE
);
1227 } else if (_settings_game
.game_creation
.land_generator
== LG_TERRAGENESIS
) {
1228 SetGeneratingWorldProgress(GWP_LANDSCAPE
, steps
+ GLS_TERRAGENESIS
);
1229 GenerateTerrainPerlin();
1231 SetGeneratingWorldProgress(GWP_LANDSCAPE
, steps
+ GLS_ORIGINAL
);
1232 if (_settings_game
.construction
.freeform_edges
) {
1233 for (uint x
= 0; x
< MapSizeX(); x
++) MakeVoid(TileXY(x
, 0));
1234 for (uint y
= 0; y
< MapSizeY(); y
++) MakeVoid(TileXY(0, y
));
1236 switch (_settings_game
.game_creation
.landscape
) {
1238 uint32 r
= Random();
1240 for (uint i
= ScaleByMapSize(GB(r
, 0, 7) + 950); i
!= 0; --i
) {
1241 GenerateTerrain(2, 0);
1244 uint flag
= GB(r
, 7, 2) | 4;
1245 for (uint i
= ScaleByMapSize(GB(r
, 9, 7) + 450); i
!= 0; --i
) {
1246 GenerateTerrain(4, flag
);
1252 uint32 r
= Random();
1254 for (uint i
= ScaleByMapSize(GB(r
, 0, 7) + 170); i
!= 0; --i
) {
1255 GenerateTerrain(0, 0);
1258 uint flag
= GB(r
, 7, 2) | 4;
1259 for (uint i
= ScaleByMapSize(GB(r
, 9, 8) + 1700); i
!= 0; --i
) {
1260 GenerateTerrain(0, flag
);
1265 for (uint i
= ScaleByMapSize(GB(r
, 17, 7) + 410); i
!= 0; --i
) {
1266 GenerateTerrain(3, flag
);
1272 uint32 r
= Random();
1274 assert(_settings_game
.difficulty
.quantity_sea_lakes
!= CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
);
1275 uint i
= ScaleByMapSize(GB(r
, 0, 7) + (3 - _settings_game
.difficulty
.quantity_sea_lakes
) * 256 + 100);
1276 for (; i
!= 0; --i
) {
1277 /* Make sure we do not overflow. */
1278 GenerateTerrain(Clamp(_settings_game
.difficulty
.terrain_type
, 0, 3), 0);
1285 /* Do not call IncreaseGeneratingWorldProgress() before FixSlopes(),
1286 * it allows screen redraw. Drawing of broken slopes crashes the game */
1288 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE
);
1289 ConvertGroundTilesIntoWaterTiles();
1290 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE
);
1292 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
) CreateDesertOrRainForest();
1298 void OnTick_Trees();
1299 void OnTick_Station();
1300 void OnTick_Industry();
1302 void OnTick_Companies();
1303 void OnTick_LinkGraph();
1305 void CallLandscapeTick()