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/>.
8 /** @file terraform_cmd.cpp Commands related to terraforming. */
11 #include "command_func.h"
12 #include "tunnel_map.h"
13 #include "bridge_map.h"
14 #include "viewport_func.h"
16 #include "object_base.h"
17 #include "company_base.h"
18 #include "company_func.h"
19 #include "core/backup_type.hpp"
21 #include "table/strings.h"
26 #include "safeguards.h"
29 typedef std::set
<TileIndex
> TileIndexSet
;
30 /** Mapping of tiles to their height. */
31 typedef std::map
<TileIndex
, int> TileIndexToHeightMap
;
33 /** State of the terraforming. */
34 struct TerraformerState
{
35 TileIndexSet dirty_tiles
; ///< The tiles that need to be redrawn.
36 TileIndexToHeightMap tile_to_new_height
; ///< The tiles for which the height has changed.
39 TileIndex _terraform_err_tile
; ///< first tile we couldn't terraform
42 * Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
44 * @param ts TerraformerState.
48 static int TerraformGetHeightOfTile(const TerraformerState
*ts
, TileIndex tile
)
50 TileIndexToHeightMap::const_iterator it
= ts
->tile_to_new_height
.find(tile
);
51 return it
!= ts
->tile_to_new_height
.end() ? it
->second
: TileHeight(tile
);
55 * Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
57 * @param ts TerraformerState.
59 * @param height New TileHeight.
61 static void TerraformSetHeightOfTile(TerraformerState
*ts
, TileIndex tile
, int height
)
63 ts
->tile_to_new_height
[tile
] = height
;
67 * Adds a tile to the "tile_table" in a TerraformerState.
69 * @param ts TerraformerState.
73 static void TerraformAddDirtyTile(TerraformerState
*ts
, TileIndex tile
)
75 ts
->dirty_tiles
.insert(tile
);
79 * Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a TerraformerState.
81 * @param ts TerraformerState.
85 static void TerraformAddDirtyTileAround(TerraformerState
*ts
, TileIndex tile
)
87 /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
88 if (TileY(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY( 0, -1));
89 if (TileY(tile
) >= 1 && TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, -1));
90 if (TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, 0));
91 TerraformAddDirtyTile(ts
, tile
);
95 * Terraform the north corner of a tile to a specific height.
97 * @param ts TerraformerState.
99 * @param height Aimed height.
100 * @return Error code or cost.
102 static CommandCost
TerraformTileHeight(TerraformerState
*ts
, TileIndex tile
, int height
)
104 assert(tile
< MapSize());
106 /* Check range of destination height */
107 if (height
< 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL
);
108 if (height
> _settings_game
.construction
.map_height_limit
) return_cmd_error(STR_ERROR_TOO_HIGH
);
111 * Check if the terraforming has any effect.
112 * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
113 * In this case the terraforming should fail. (Don't know why.)
115 if (height
== TerraformGetHeightOfTile(ts
, tile
)) return CMD_ERROR
;
117 /* Check "too close to edge of map". Only possible when freeform-edges is off. */
118 uint x
= TileX(tile
);
119 uint y
= TileY(tile
);
120 if (!_settings_game
.construction
.freeform_edges
&& ((x
<= 1) || (y
<= 1) || (x
>= MapMaxX() - 1) || (y
>= MapMaxY() - 1))) {
122 * Determine a sensible error tile
126 _terraform_err_tile
= TileXY(x
, y
);
127 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP
);
130 /* Mark incident tiles that are involved in the terraforming. */
131 TerraformAddDirtyTileAround(ts
, tile
);
133 /* Store the height modification */
134 TerraformSetHeightOfTile(ts
, tile
, height
);
136 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
139 total_cost
.AddCost(_price
[PR_TERRAFORM
]);
141 /* Recurse to neighboured corners if height difference is larger than 1 */
143 const TileIndexDiffC
*ttm
;
145 TileIndex orig_tile
= tile
;
146 static const TileIndexDiffC _terraform_tilepos
[] = {
147 { 1, 0}, // move to tile in SE
148 {-2, 0}, // undo last move, and move to tile in NW
149 { 1, 1}, // undo last move, and move to tile in SW
150 { 0, -2} // undo last move, and move to tile in NE
153 for (ttm
= _terraform_tilepos
; ttm
!= endof(_terraform_tilepos
); ttm
++) {
154 tile
+= ToTileIndexDiff(*ttm
);
156 if (tile
>= MapSize()) continue;
157 /* Make sure we don't wrap around the map */
158 if (Delta(TileX(orig_tile
), TileX(tile
)) == MapSizeX() - 1) continue;
159 if (Delta(TileY(orig_tile
), TileY(tile
)) == MapSizeY() - 1) continue;
161 /* Get TileHeight of neighboured tile as of current terraform progress */
162 int r
= TerraformGetHeightOfTile(ts
, tile
);
163 int height_diff
= height
- r
;
165 /* Is the height difference to the neighboured corner greater than 1? */
166 if (abs(height_diff
) > 1) {
167 /* Terraform the neighboured corner. The resulting height difference should be 1. */
168 height_diff
+= (height_diff
< 0 ? 1 : -1);
169 CommandCost cost
= TerraformTileHeight(ts
, tile
, r
+ height_diff
);
170 if (cost
.Failed()) return cost
;
171 total_cost
.AddCost(cost
);
181 * @param tile tile to terraform
182 * @param flags for this command type
183 * @param p1 corners to terraform (SLOPE_xxx)
184 * @param p2 direction; eg up (non-zero) or down (zero)
186 * @return the cost of this operation or an error
188 CommandCost
CmdTerraformLand(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
190 _terraform_err_tile
= INVALID_TILE
;
192 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
193 int direction
= (p2
!= 0 ? 1 : -1);
196 /* Compute the costs and the terraforming result in a model of the landscape */
197 if ((p1
& SLOPE_W
) != 0 && tile
+ TileDiffXY(1, 0) < MapSize()) {
198 TileIndex t
= tile
+ TileDiffXY(1, 0);
199 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
200 if (cost
.Failed()) return cost
;
201 total_cost
.AddCost(cost
);
204 if ((p1
& SLOPE_S
) != 0 && tile
+ TileDiffXY(1, 1) < MapSize()) {
205 TileIndex t
= tile
+ TileDiffXY(1, 1);
206 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
207 if (cost
.Failed()) return cost
;
208 total_cost
.AddCost(cost
);
211 if ((p1
& SLOPE_E
) != 0 && tile
+ TileDiffXY(0, 1) < MapSize()) {
212 TileIndex t
= tile
+ TileDiffXY(0, 1);
213 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
214 if (cost
.Failed()) return cost
;
215 total_cost
.AddCost(cost
);
218 if ((p1
& SLOPE_N
) != 0) {
219 TileIndex t
= tile
+ TileDiffXY(0, 0);
220 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
221 if (cost
.Failed()) return cost
;
222 total_cost
.AddCost(cost
);
225 /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
226 * Pass == 0: Collect tileareas which are caused to be auto-cleared.
227 * Pass == 1: Collect the actual cost. */
228 for (int pass
= 0; pass
< 2; pass
++) {
229 for (TileIndexSet::const_iterator it
= ts
.dirty_tiles
.begin(); it
!= ts
.dirty_tiles
.end(); it
++) {
232 assert(t
< MapSize());
233 /* MP_VOID tiles can be terraformed but as tunnels and bridges
234 * cannot go under / over these tiles they don't need checking. */
235 if (IsTileType(t
, MP_VOID
)) continue;
237 /* Find new heights of tile corners */
238 int z_N
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(0, 0));
239 int z_W
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(1, 0));
240 int z_S
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(1, 1));
241 int z_E
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(0, 1));
243 /* Find min and max height of tile */
244 int z_min
= std::min({z_N
, z_W
, z_S
, z_E
});
245 int z_max
= std::max({z_N
, z_W
, z_S
, z_E
});
247 /* Compute tile slope */
248 Slope tileh
= (z_max
> z_min
+ 1 ? SLOPE_STEEP
: SLOPE_FLAT
);
249 if (z_W
> z_min
) tileh
|= SLOPE_W
;
250 if (z_S
> z_min
) tileh
|= SLOPE_S
;
251 if (z_E
> z_min
) tileh
|= SLOPE_E
;
252 if (z_N
> z_min
) tileh
|= SLOPE_N
;
255 /* Check if bridge would take damage */
256 if (IsBridgeAbove(t
)) {
257 int bridge_height
= GetBridgeHeight(GetSouthernBridgeEnd(t
));
259 /* Check if bridge would take damage. */
260 if (direction
== 1 && bridge_height
<= z_max
) {
261 _terraform_err_tile
= t
; // highlight the tile under the bridge
262 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
265 /* Is the bridge above not too high afterwards? */
266 if (direction
== -1 && bridge_height
> (z_min
+ _settings_game
.construction
.max_bridge_height
)) {
267 _terraform_err_tile
= t
;
268 return_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_AFTER_LOWER_LAND
);
271 /* Check if tunnel would take damage */
272 if (direction
== -1 && IsTunnelInWay(t
, z_min
)) {
273 _terraform_err_tile
= t
; // highlight the tile above the tunnel
274 return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE
);
278 /* Is the tile already cleared? */
279 const ClearedObjectArea
*coa
= FindClearedObject(t
);
280 bool indirectly_cleared
= coa
!= nullptr && coa
->first_tile
!= t
;
282 /* Check tiletype-specific things, and add extra-cost */
283 Backup
<bool> old_generating_world(_generating_world
, FILE_LINE
);
284 if (_game_mode
== GM_EDITOR
) old_generating_world
.Change(true); // used to create green terraformed land
285 DoCommandFlag tile_flags
= flags
| DC_AUTO
| DC_FORCE_CLEAR_TILE
;
287 tile_flags
&= ~DC_EXEC
;
288 tile_flags
|= DC_NO_MODIFY_TOWN_RATING
;
291 if (indirectly_cleared
) {
292 cost
= DoCommand(t
, 0, 0, tile_flags
, CMD_LANDSCAPE_CLEAR
);
294 cost
= _tile_type_procs
[GetTileType(t
)]->terraform_tile_proc(t
, tile_flags
, z_min
, tileh
);
296 old_generating_world
.Restore();
298 _terraform_err_tile
= t
;
301 if (pass
== 1) total_cost
.AddCost(cost
);
305 Company
*c
= Company::GetIfValid(_current_company
);
306 if (c
!= nullptr && GB(c
->terraform_limit
, 16, 16) < ts
.tile_to_new_height
.size()) {
307 return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED
);
310 if (flags
& DC_EXEC
) {
311 /* Mark affected areas dirty. */
312 for (TileIndexSet::const_iterator it
= ts
.dirty_tiles
.begin(); it
!= ts
.dirty_tiles
.end(); it
++) {
313 MarkTileDirtyByTile(*it
);
314 TileIndexToHeightMap::const_iterator new_height
= ts
.tile_to_new_height
.find(*it
);
315 if (new_height
== ts
.tile_to_new_height
.end()) continue;
316 MarkTileDirtyByTile(*it
, 0, new_height
->second
);
319 /* change the height */
320 for (TileIndexToHeightMap::const_iterator it
= ts
.tile_to_new_height
.begin();
321 it
!= ts
.tile_to_new_height
.end(); it
++) {
322 TileIndex t
= it
->first
;
323 int height
= it
->second
;
325 SetTileHeight(t
, (uint
)height
);
328 if (c
!= nullptr) c
->terraform_limit
-= (uint32
)ts
.tile_to_new_height
.size() << 16;
335 * Levels a selected (rectangle) area of land
336 * @param tile end tile of area-drag
337 * @param flags for this command type
338 * @param p1 start tile of area drag
339 * @param p2 various bitstuffed data.
340 * bit 0: Whether to use the Orthogonal (0) or Diagonal (1) iterator.
341 * bits 1 - 2: Mode of leveling \c LevelMode.
343 * @return the cost of this operation or an error
345 CommandCost
CmdLevelLand(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const std::string
&text
)
347 if (p1
>= MapSize()) return CMD_ERROR
;
349 _terraform_err_tile
= INVALID_TILE
;
351 /* remember level height */
352 uint oldh
= TileHeight(p1
);
354 /* compute new height */
356 LevelMode lm
= (LevelMode
)GB(p2
, 1, 2);
358 case LM_LEVEL
: break;
359 case LM_RAISE
: h
++; break;
360 case LM_LOWER
: h
--; break;
361 default: return CMD_ERROR
;
364 /* Check range of destination height */
365 if (h
> _settings_game
.construction
.map_height_limit
) return_cmd_error((oldh
== 0) ? STR_ERROR_ALREADY_AT_SEA_LEVEL
: STR_ERROR_TOO_HIGH
);
367 Money money
= GetAvailableMoneyForCommand();
368 CommandCost
cost(EXPENSES_CONSTRUCTION
);
369 CommandCost
last_error(lm
== LM_LEVEL
? STR_ERROR_ALREADY_LEVELLED
: INVALID_STRING_ID
);
370 bool had_success
= false;
372 const Company
*c
= Company::GetIfValid(_current_company
);
373 int limit
= (c
== nullptr ? INT32_MAX
: GB(c
->terraform_limit
, 16, 16));
374 if (limit
== 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED
);
376 TileIterator
*iter
= HasBit(p2
, 0) ? (TileIterator
*)new DiagonalTileIterator(tile
, p1
) : new OrthogonalTileIterator(tile
, p1
);
377 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
379 uint curh
= TileHeight(t
);
381 CommandCost ret
= DoCommand(t
, SLOPE_N
, (curh
> h
) ? 0 : 1, flags
& ~DC_EXEC
, CMD_TERRAFORM_LAND
);
385 /* Did we reach the limit? */
386 if (ret
.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED
) limit
= 0;
390 if (flags
& DC_EXEC
) {
391 money
-= ret
.GetCost();
393 _additional_cash_required
= ret
.GetCost();
397 DoCommand(t
, SLOPE_N
, (curh
> h
) ? 0 : 1, flags
, CMD_TERRAFORM_LAND
);
399 /* When we're at the terraform limit we better bail (unneeded) testing as well.
400 * This will probably cause the terraforming cost to be underestimated, but only
401 * when it's near the terraforming limit. Even then, the estimation is
402 * completely off due to it basically counting terraforming double, so it being
403 * cut off earlier might even give a better estimate in some cases. */
411 curh
+= (curh
> h
) ? -1 : 1;
415 if (limit
<= 0) break;
419 return had_success
? cost
: last_error
;