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 terraform_cmd.cpp Commands related to terraforming. */
13 #include "command_func.h"
14 #include "map/zoneheight.h"
15 #include "map/tunnel.h"
16 #include "map/bridge.h"
18 #include "viewport_func.h"
20 #include "object_base.h"
21 #include "company_base.h"
22 #include "company_func.h"
23 #include "landscape_type.h"
25 #include "table/strings.h"
28 * In one terraforming command all four corners of a initial tile can be raised/lowered (though this is not available to the player).
29 * The maximal amount of height modifications is achieved when raising a complete flat land from sea level to MAX_TILE_HEIGHT or vice versa.
30 * This affects all corners with a manhatten distance smaller than MAX_TILE_HEIGHT to one of the initial 4 corners.
31 * Their maximal amount is computed to 4 * \sum_{i=1}^{h_max} i = 2 * h_max * (h_max + 1).
33 static const int TERRAFORMER_MODHEIGHT_SIZE
= 2 * MAX_TILE_HEIGHT
* (MAX_TILE_HEIGHT
+ 1);
36 * The maximal amount of affected tiles (i.e. the tiles that incident with one of the corners above, is computed similar to
37 * 1 + 4 * \sum_{i=1}^{h_max} (i+1) = 1 + 2 * h_max + (h_max + 3).
39 static const int TERRAFORMER_TILE_TABLE_SIZE
= 1 + 2 * MAX_TILE_HEIGHT
* (MAX_TILE_HEIGHT
+ 3);
41 struct TerraformerHeightMod
{
42 TileIndex tile
; ///< Referenced tile.
43 byte height
; ///< New TileHeight (height of north corner) of the tile.
46 struct TerraformerState
{
47 int modheight_count
; ///< amount of entries in "modheight".
48 int tile_table_count
; ///< amount of entries in "tile_table".
51 * Dirty tiles, i.e.\ at least one corner changed.
53 * This array contains the tiles which are or will be marked as dirty.
57 TileIndex tile_table
[TERRAFORMER_TILE_TABLE_SIZE
];
58 TerraformerHeightMod modheight
[TERRAFORMER_MODHEIGHT_SIZE
]; ///< Height modifications.
61 TileIndex _terraform_err_tile
; ///< first tile we couldn't terraform
64 * Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
66 * @param ts TerraformerState.
70 static int TerraformGetHeightOfTile(const TerraformerState
*ts
, TileIndex tile
)
72 const TerraformerHeightMod
*mod
= ts
->modheight
;
74 for (int count
= ts
->modheight_count
; count
!= 0; count
--, mod
++) {
75 if (mod
->tile
== tile
) return mod
->height
;
78 /* TileHeight unchanged so far, read value from map. */
79 return TileHeight(tile
);
83 * Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
85 * @param ts TerraformerState.
87 * @param height New TileHeight.
89 static void TerraformSetHeightOfTile(TerraformerState
*ts
, TileIndex tile
, int height
)
91 /* Find tile in the "modheight" table.
92 * Note: In a normal user-terraform command the tile will not be found in the "modheight" table.
93 * But during house- or industry-construction multiple corners can be terraformed at once. */
94 TerraformerHeightMod
*mod
= ts
->modheight
;
95 int count
= ts
->modheight_count
;
97 while ((count
> 0) && (mod
->tile
!= tile
)) {
104 assert(ts
->modheight_count
< TERRAFORMER_MODHEIGHT_SIZE
);
105 ts
->modheight_count
++;
108 /* Finally store the new value */
110 mod
->height
= (byte
)height
;
114 * Adds a tile to the "tile_table" in a TerraformerState.
116 * @param ts TerraformerState.
120 static void TerraformAddDirtyTile(TerraformerState
*ts
, TileIndex tile
)
122 int count
= ts
->tile_table_count
;
124 for (TileIndex
*t
= ts
->tile_table
; count
!= 0; count
--, t
++) {
125 if (*t
== tile
) return;
128 assert(ts
->tile_table_count
< TERRAFORMER_TILE_TABLE_SIZE
);
130 ts
->tile_table
[ts
->tile_table_count
++] = tile
;
134 * Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a TerraformerState.
136 * @param ts TerraformerState.
140 static void TerraformAddDirtyTileAround(TerraformerState
*ts
, TileIndex tile
)
142 /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
143 if (TileY(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY( 0, -1));
144 if (TileY(tile
) >= 1 && TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, -1));
145 if (TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, 0));
146 TerraformAddDirtyTile(ts
, tile
);
150 * Terraform the north corner of a tile to a specific height.
152 * @param ts TerraformerState.
154 * @param height Aimed height.
155 * @return Error code or cost.
157 static CommandCost
TerraformTileHeight(TerraformerState
*ts
, TileIndex tile
, int height
)
159 assert(tile
< MapSize());
161 /* Check range of destination height */
162 if (height
< 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL
);
163 if (height
> (int)MAX_TILE_HEIGHT
) return_cmd_error(STR_ERROR_TOO_HIGH
);
166 * Check if the terraforming has any effect.
167 * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
168 * In this case the terraforming should fail. (Don't know why.)
170 if (height
== TerraformGetHeightOfTile(ts
, tile
)) return CMD_ERROR
;
172 /* Check "too close to edge of map". Only possible when freeform-edges is off. */
173 uint x
= TileX(tile
);
174 uint y
= TileY(tile
);
175 if (!_settings_game
.construction
.freeform_edges
&& ((x
<= 1) || (y
<= 1) || (x
>= MapMaxX() - 1) || (y
>= MapMaxY() - 1))) {
177 * Determine a sensible error tile
181 _terraform_err_tile
= TileXY(x
, y
);
182 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP
);
185 /* Mark incident tiles that are involved in the terraforming. */
186 TerraformAddDirtyTileAround(ts
, tile
);
188 /* Store the height modification */
189 TerraformSetHeightOfTile(ts
, tile
, height
);
191 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
194 total_cost
.AddCost(_price
[PR_TERRAFORM
]);
196 /* Recurse to neighboured corners if height difference is larger than 1 */
198 const CoordDiff
*ttm
;
200 TileIndex orig_tile
= tile
;
201 static const CoordDiff _terraform_tilepos
[] = {
202 { 1, 0}, // move to tile in SE
203 {-2, 0}, // undo last move, and move to tile in NW
204 { 1, 1}, // undo last move, and move to tile in SW
205 { 0, -2} // undo last move, and move to tile in NE
208 for (ttm
= _terraform_tilepos
; ttm
!= endof(_terraform_tilepos
); ttm
++) {
209 tile
+= ToTileIndexDiff(*ttm
);
211 if (tile
>= MapSize()) continue;
212 /* Make sure we don't wrap around the map */
213 if (Delta(TileX(orig_tile
), TileX(tile
)) == MapSizeX() - 1) continue;
214 if (Delta(TileY(orig_tile
), TileY(tile
)) == MapSizeY() - 1) continue;
216 /* Get TileHeight of neighboured tile as of current terraform progress */
217 int r
= TerraformGetHeightOfTile(ts
, tile
);
218 int height_diff
= height
- r
;
220 /* Is the height difference to the neighboured corner greater than 1? */
221 if (abs(height_diff
) > 1) {
222 /* Terraform the neighboured corner. The resulting height difference should be 1. */
223 height_diff
+= (height_diff
< 0 ? 1 : -1);
224 CommandCost cost
= TerraformTileHeight(ts
, tile
, r
+ height_diff
);
225 if (cost
.Failed()) return cost
;
226 total_cost
.AddCost(cost
);
236 * @param tile tile to terraform
237 * @param flags for this command type
238 * @param p1 corners to terraform (SLOPE_xxx)
239 * @param p2 direction; eg up (non-zero) or down (zero)
241 * @return the cost of this operation or an error
243 CommandCost
CmdTerraformLand(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
245 _terraform_err_tile
= INVALID_TILE
;
247 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
248 int direction
= (p2
!= 0 ? 1 : -1);
251 ts
.modheight_count
= ts
.tile_table_count
= 0;
253 /* Compute the costs and the terraforming result in a model of the landscape */
254 if ((p1
& SLOPE_W
) != 0 && tile
+ TileDiffXY(1, 0) < MapSize()) {
255 TileIndex t
= tile
+ TileDiffXY(1, 0);
256 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
257 if (cost
.Failed()) return cost
;
258 total_cost
.AddCost(cost
);
261 if ((p1
& SLOPE_S
) != 0 && tile
+ TileDiffXY(1, 1) < MapSize()) {
262 TileIndex t
= tile
+ TileDiffXY(1, 1);
263 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
264 if (cost
.Failed()) return cost
;
265 total_cost
.AddCost(cost
);
268 if ((p1
& SLOPE_E
) != 0 && tile
+ TileDiffXY(0, 1) < MapSize()) {
269 TileIndex t
= tile
+ TileDiffXY(0, 1);
270 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
271 if (cost
.Failed()) return cost
;
272 total_cost
.AddCost(cost
);
275 if ((p1
& SLOPE_N
) != 0) {
276 TileIndex t
= tile
+ TileDiffXY(0, 0);
277 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
278 if (cost
.Failed()) return cost
;
279 total_cost
.AddCost(cost
);
282 /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
283 * Pass == 0: Collect tileareas which are caused to be auto-cleared.
284 * Pass == 1: Collect the actual cost. */
285 for (int pass
= 0; pass
< 2; pass
++) {
286 TileIndex
*ti
= ts
.tile_table
;
288 for (int count
= ts
.tile_table_count
; count
!= 0; count
--, ti
++) {
289 TileIndex tile
= *ti
;
291 assert(tile
< MapSize());
292 /* Void tiles can be terraformed but as tunnels and bridges
293 * cannot go under / over these tiles they don't need checking. */
294 if (IsVoidTile(tile
)) continue;
296 /* Find new heights of tile corners */
297 int z_N
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(0, 0));
298 int z_W
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(1, 0));
299 int z_S
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(1, 1));
300 int z_E
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(0, 1));
302 /* Find min and max height of tile */
303 int z_min
= min(min(z_N
, z_W
), min(z_S
, z_E
));
304 int z_max
= max(max(z_N
, z_W
), max(z_S
, z_E
));
306 /* Compute tile slope */
307 Slope tileh
= (z_max
> z_min
+ 1 ? SLOPE_STEEP
: SLOPE_FLAT
);
308 if (z_W
> z_min
) tileh
|= SLOPE_W
;
309 if (z_S
> z_min
) tileh
|= SLOPE_S
;
310 if (z_E
> z_min
) tileh
|= SLOPE_E
;
311 if (z_N
> z_min
) tileh
|= SLOPE_N
;
314 /* Check if bridge would take damage */
315 if (direction
== 1 && HasBridgeAbove(tile
) &&
316 GetBridgeHeight(GetSouthernBridgeEnd(tile
)) <= z_max
) {
317 _terraform_err_tile
= tile
; // highlight the tile under the bridge
318 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
320 /* Check if tunnel would take damage */
321 if (direction
== -1 && IsTunnelInWay(tile
, z_min
)) {
322 _terraform_err_tile
= tile
; // highlight the tile above the tunnel
323 return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE
);
327 /* Is the tile already cleared? */
328 const ClearedObjectArea
*coa
= FindClearedObject(tile
);
329 bool indirectly_cleared
= coa
!= NULL
&& coa
->first_tile
!= tile
;
331 /* Check tiletype-specific things, and add extra-cost */
332 const bool curr_gen
= _generating_world
;
333 if (_game_mode
== GM_EDITOR
) _generating_world
= true; // used to create green terraformed land
334 DoCommandFlag tile_flags
= flags
| DC_AUTO
| DC_FORCE_CLEAR_TILE
;
336 tile_flags
&= ~DC_EXEC
;
337 tile_flags
|= DC_NO_MODIFY_TOWN_RATING
;
340 if (indirectly_cleared
) {
341 cost
= DoCommand(tile
, 0, 0, tile_flags
, CMD_LANDSCAPE_CLEAR
);
343 cost
= GetTileProcs(tile
)->terraform_tile_proc(tile
, tile_flags
, z_min
, tileh
);
345 _generating_world
= curr_gen
;
347 _terraform_err_tile
= tile
;
350 if (pass
== 1) total_cost
.AddCost(cost
);
354 Company
*c
= Company::GetIfValid(_current_company
);
355 if (c
!= NULL
&& (int)GB(c
->terraform_limit
, 16, 16) < ts
.modheight_count
) {
356 return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED
);
359 if (flags
& DC_EXEC
) {
360 /* change the height */
363 TerraformerHeightMod
*mod
;
366 for (count
= ts
.modheight_count
; count
!= 0; count
--, mod
++) {
367 TileIndex til
= mod
->tile
;
369 SetTileHeight(til
, mod
->height
);
373 /* finally mark the dirty tiles dirty */
376 TileIndex
*ti
= ts
.tile_table
;
377 for (count
= ts
.tile_table_count
; count
!= 0; count
--, ti
++) {
378 MarkTileDirtyByTile(*ti
);
382 if (c
!= NULL
) c
->terraform_limit
-= ts
.modheight_count
<< 16;
389 * Levels a selected (rectangle) area of land
390 * @param tile end tile of area-drag
391 * @param flags for this command type
392 * @param p1 start tile of area drag
393 * @param p2 various bitstuffed data.
394 * bit 0: Whether to use the Orthogonal (0) or Diagonal (1) iterator.
395 * bits 1 - 2: Mode of leveling \c LevelMode.
397 * @return the cost of this operation or an error
399 CommandCost
CmdLevelLand(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
401 if (p1
>= MapSize()) return CMD_ERROR
;
403 _terraform_err_tile
= INVALID_TILE
;
405 /* remember level height */
406 uint oldh
= TileHeight(p1
);
408 /* compute new height */
410 LevelMode lm
= (LevelMode
)GB(p2
, 1, 2);
412 case LM_LEVEL
: break;
413 case LM_RAISE
: h
++; break;
414 case LM_LOWER
: h
--; break;
415 default: return CMD_ERROR
;
418 /* Check range of destination height */
419 if (h
> MAX_TILE_HEIGHT
) return_cmd_error((oldh
== 0) ? STR_ERROR_ALREADY_AT_SEA_LEVEL
: STR_ERROR_TOO_HIGH
);
421 Money money
= GetAvailableMoneyForCommand();
422 CommandCost
cost(EXPENSES_CONSTRUCTION
);
423 CommandCost
last_error(lm
== LM_LEVEL
? STR_ERROR_ALREADY_LEVELLED
: INVALID_STRING_ID
);
424 bool had_success
= false;
426 const Company
*c
= Company::GetIfValid(_current_company
);
427 int limit
= (c
== NULL
? INT32_MAX
: GB(c
->terraform_limit
, 16, 16));
428 if (limit
== 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED
);
430 TileArea
ta(tile
, p1
);
431 TileIterator
*iter
= HasBit(p2
, 0) ? (TileIterator
*)new DiagonalTileIterator(tile
, p1
) : new OrthogonalTileIterator(ta
);
432 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
434 uint curh
= TileHeight(t
);
436 CommandCost ret
= DoCommand(t
, SLOPE_N
, (curh
> h
) ? 0 : 1, flags
& ~DC_EXEC
, CMD_TERRAFORM_LAND
);
440 /* Did we reach the limit? */
441 if (ret
.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED
) limit
= 0;
445 if (flags
& DC_EXEC
) {
446 money
-= ret
.GetCost();
448 _additional_cash_required
= ret
.GetCost();
452 DoCommand(t
, SLOPE_N
, (curh
> h
) ? 0 : 1, flags
, CMD_TERRAFORM_LAND
);
454 /* When we're at the terraform limit we better bail (unneeded) testing as well.
455 * This will probably cause the terraforming cost to be underestimated, but only
456 * when it's near the terraforming limit. Even then, the estimation is
457 * completely off due to it basically counting terraforming double, so it being
458 * cut off earlier might even give a better estimate in some cases. */
466 curh
+= (curh
> h
) ? -1 : 1;
470 if (limit
<= 0) break;
474 return had_success
? cost
: last_error
;