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"
20 #include "terraform_cmd.h"
21 #include "landscape_cmd.h"
23 #include "table/strings.h"
25 #include "safeguards.h"
28 typedef std::set
<TileIndex
> TileIndexSet
;
29 /** Mapping of tiles to their height. */
30 typedef std::map
<TileIndex
, int> TileIndexToHeightMap
;
32 /** State of the terraforming. */
33 struct TerraformerState
{
34 TileIndexSet dirty_tiles
; ///< The tiles that need to be redrawn.
35 TileIndexToHeightMap tile_to_new_height
; ///< The tiles for which the height has changed.
39 * Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
41 * @param ts TerraformerState.
45 static int TerraformGetHeightOfTile(const TerraformerState
*ts
, TileIndex tile
)
47 TileIndexToHeightMap::const_iterator it
= ts
->tile_to_new_height
.find(tile
);
48 return it
!= ts
->tile_to_new_height
.end() ? it
->second
: TileHeight(tile
);
52 * Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
54 * @param ts TerraformerState.
56 * @param height New TileHeight.
58 static void TerraformSetHeightOfTile(TerraformerState
*ts
, TileIndex tile
, int height
)
60 ts
->tile_to_new_height
[tile
] = height
;
64 * Adds a tile to the "tile_table" in a TerraformerState.
66 * @param ts TerraformerState.
70 static void TerraformAddDirtyTile(TerraformerState
*ts
, TileIndex tile
)
72 ts
->dirty_tiles
.insert(tile
);
76 * Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a TerraformerState.
78 * @param ts TerraformerState.
82 static void TerraformAddDirtyTileAround(TerraformerState
*ts
, TileIndex tile
)
84 /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, Map::Size()] */
85 if (TileY(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY( 0, -1));
86 if (TileY(tile
) >= 1 && TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, -1));
87 if (TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, 0));
88 TerraformAddDirtyTile(ts
, tile
);
92 * Terraform the north corner of a tile to a specific height.
94 * @param ts TerraformerState.
96 * @param height Aimed height.
97 * @return Error code or cost.
99 static std::tuple
<CommandCost
, TileIndex
> TerraformTileHeight(TerraformerState
*ts
, TileIndex tile
, int height
)
101 assert(tile
< Map::Size());
103 /* Check range of destination height */
104 if (height
< 0) return { CommandCost(STR_ERROR_ALREADY_AT_SEA_LEVEL
), INVALID_TILE
};
105 if (height
> _settings_game
.construction
.map_height_limit
) return { CommandCost(STR_ERROR_TOO_HIGH
), INVALID_TILE
};
108 * Check if the terraforming has any effect.
109 * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
110 * In this case the terraforming should fail. (Don't know why.)
112 if (height
== TerraformGetHeightOfTile(ts
, tile
)) return { CMD_ERROR
, INVALID_TILE
};
114 /* Check "too close to edge of map". Only possible when freeform-edges is off. */
115 uint x
= TileX(tile
);
116 uint y
= TileY(tile
);
117 if (!_settings_game
.construction
.freeform_edges
&& ((x
<= 1) || (y
<= 1) || (x
>= Map::MaxX() - 1) || (y
>= Map::MaxY() - 1))) {
119 * Determine a sensible error tile
123 return { CommandCost(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP
), TileXY(x
, y
) };
126 /* Mark incident tiles that are involved in the terraforming. */
127 TerraformAddDirtyTileAround(ts
, tile
);
129 /* Store the height modification */
130 TerraformSetHeightOfTile(ts
, tile
, height
);
132 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
135 total_cost
.AddCost(_price
[PR_TERRAFORM
]);
137 /* Recurse to neighboured corners if height difference is larger than 1 */
139 const TileIndexDiffC
*ttm
;
141 TileIndex orig_tile
= tile
;
142 static const TileIndexDiffC _terraform_tilepos
[] = {
143 { 1, 0}, // move to tile in SE
144 {-2, 0}, // undo last move, and move to tile in NW
145 { 1, 1}, // undo last move, and move to tile in SW
146 { 0, -2} // undo last move, and move to tile in NE
149 for (ttm
= _terraform_tilepos
; ttm
!= endof(_terraform_tilepos
); ttm
++) {
150 tile
+= ToTileIndexDiff(*ttm
);
152 if (tile
>= Map::Size()) continue;
153 /* Make sure we don't wrap around the map */
154 if (Delta(TileX(orig_tile
), TileX(tile
)) == Map::SizeX() - 1) continue;
155 if (Delta(TileY(orig_tile
), TileY(tile
)) == Map::SizeY() - 1) continue;
157 /* Get TileHeight of neighboured tile as of current terraform progress */
158 int r
= TerraformGetHeightOfTile(ts
, tile
);
159 int height_diff
= height
- r
;
161 /* Is the height difference to the neighboured corner greater than 1? */
162 if (abs(height_diff
) > 1) {
163 /* Terraform the neighboured corner. The resulting height difference should be 1. */
164 height_diff
+= (height_diff
< 0 ? 1 : -1);
165 auto [cost
, err_tile
] = TerraformTileHeight(ts
, tile
, r
+ height_diff
);
166 if (cost
.Failed()) return { cost
, err_tile
};
167 total_cost
.AddCost(cost
);
172 return { total_cost
, INVALID_TILE
};
177 * @param flags for this command type
178 * @param tile tile to terraform
179 * @param slope corners to terraform (SLOPE_xxx)
180 * @param dir_up direction; eg up (true) or down (false)
181 * @return the cost of this operation or an error
183 std::tuple
<CommandCost
, Money
, TileIndex
> CmdTerraformLand(DoCommandFlag flags
, TileIndex tile
, Slope slope
, bool dir_up
)
185 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
186 int direction
= (dir_up
? 1 : -1);
189 /* Compute the costs and the terraforming result in a model of the landscape */
190 if ((slope
& SLOPE_W
) != 0 && tile
+ TileDiffXY(1, 0) < Map::Size()) {
191 TileIndex t
= tile
+ TileDiffXY(1, 0);
192 auto [cost
, err_tile
] = TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
193 if (cost
.Failed()) return { cost
, 0, err_tile
};
194 total_cost
.AddCost(cost
);
197 if ((slope
& SLOPE_S
) != 0 && tile
+ TileDiffXY(1, 1) < Map::Size()) {
198 TileIndex t
= tile
+ TileDiffXY(1, 1);
199 auto [cost
, err_tile
] = TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
200 if (cost
.Failed()) return { cost
, 0, err_tile
};
201 total_cost
.AddCost(cost
);
204 if ((slope
& SLOPE_E
) != 0 && tile
+ TileDiffXY(0, 1) < Map::Size()) {
205 TileIndex t
= tile
+ TileDiffXY(0, 1);
206 auto [cost
, err_tile
] = TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
207 if (cost
.Failed()) return { cost
, 0, err_tile
};
208 total_cost
.AddCost(cost
);
211 if ((slope
& SLOPE_N
) != 0) {
212 TileIndex t
= tile
+ TileDiffXY(0, 0);
213 auto [cost
, err_tile
] = TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
214 if (cost
.Failed()) return { cost
, 0, err_tile
};
215 total_cost
.AddCost(cost
);
218 /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
219 * Pass == 0: Collect tileareas which are caused to be auto-cleared.
220 * Pass == 1: Collect the actual cost. */
221 for (int pass
= 0; pass
< 2; pass
++) {
222 for (const auto &t
: ts
.dirty_tiles
) {
223 assert(t
< Map::Size());
224 /* MP_VOID tiles can be terraformed but as tunnels and bridges
225 * cannot go under / over these tiles they don't need checking. */
226 if (IsTileType(t
, MP_VOID
)) continue;
228 /* Find new heights of tile corners */
229 int z_N
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(0, 0));
230 int z_W
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(1, 0));
231 int z_S
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(1, 1));
232 int z_E
= TerraformGetHeightOfTile(&ts
, t
+ TileDiffXY(0, 1));
234 /* Find min and max height of tile */
235 int z_min
= std::min({z_N
, z_W
, z_S
, z_E
});
236 int z_max
= std::max({z_N
, z_W
, z_S
, z_E
});
238 /* Compute tile slope */
239 Slope tileh
= (z_max
> z_min
+ 1 ? SLOPE_STEEP
: SLOPE_FLAT
);
240 if (z_W
> z_min
) tileh
|= SLOPE_W
;
241 if (z_S
> z_min
) tileh
|= SLOPE_S
;
242 if (z_E
> z_min
) tileh
|= SLOPE_E
;
243 if (z_N
> z_min
) tileh
|= SLOPE_N
;
246 /* Check if bridge would take damage */
247 if (IsBridgeAbove(t
)) {
248 int bridge_height
= GetBridgeHeight(GetSouthernBridgeEnd(t
));
250 /* Check if bridge would take damage. */
251 if (direction
== 1 && bridge_height
<= z_max
) {
252 return { CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
), 0, t
}; // highlight the tile under the bridge
255 /* Is the bridge above not too high afterwards? */
256 if (direction
== -1 && bridge_height
> (z_min
+ _settings_game
.construction
.max_bridge_height
)) {
257 return { CommandCost(STR_ERROR_BRIDGE_TOO_HIGH_AFTER_LOWER_LAND
), 0, t
};
260 /* Check if tunnel would take damage */
261 if (direction
== -1 && IsTunnelInWay(t
, z_min
)) {
262 return { CommandCost(STR_ERROR_EXCAVATION_WOULD_DAMAGE
), 0, t
}; // highlight the tile above the tunnel
266 /* Is the tile already cleared? */
267 const ClearedObjectArea
*coa
= FindClearedObject(t
);
268 bool indirectly_cleared
= coa
!= nullptr && coa
->first_tile
!= t
;
270 /* Check tiletype-specific things, and add extra-cost */
271 Backup
<bool> old_generating_world(_generating_world
, FILE_LINE
);
272 if (_game_mode
== GM_EDITOR
) old_generating_world
.Change(true); // used to create green terraformed land
273 DoCommandFlag tile_flags
= flags
| DC_AUTO
| DC_FORCE_CLEAR_TILE
;
275 tile_flags
&= ~DC_EXEC
;
276 tile_flags
|= DC_NO_MODIFY_TOWN_RATING
;
279 if (indirectly_cleared
) {
280 cost
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(tile_flags
, t
);
282 cost
= _tile_type_procs
[GetTileType(t
)]->terraform_tile_proc(t
, tile_flags
, z_min
, tileh
);
284 old_generating_world
.Restore();
286 return { cost
, 0, t
};
288 if (pass
== 1) total_cost
.AddCost(cost
);
292 Company
*c
= Company::GetIfValid(_current_company
);
293 if (c
!= nullptr && GB(c
->terraform_limit
, 16, 16) < ts
.tile_to_new_height
.size()) {
294 return { CommandCost(STR_ERROR_TERRAFORM_LIMIT_REACHED
), 0, INVALID_TILE
};
297 if (flags
& DC_EXEC
) {
298 /* Mark affected areas dirty. */
299 for (const auto &t
: ts
.dirty_tiles
) {
300 MarkTileDirtyByTile(t
);
301 TileIndexToHeightMap::const_iterator new_height
= ts
.tile_to_new_height
.find(t
);
302 if (new_height
== ts
.tile_to_new_height
.end()) continue;
303 MarkTileDirtyByTile(t
, 0, new_height
->second
);
306 /* change the height */
307 for (const auto &it
: ts
.tile_to_new_height
) {
308 TileIndex t
= it
.first
;
309 int height
= it
.second
;
311 SetTileHeight(t
, (uint
)height
);
314 if (c
!= nullptr) c
->terraform_limit
-= (uint32_t)ts
.tile_to_new_height
.size() << 16;
316 return { total_cost
, 0, total_cost
.Succeeded() ? tile
: INVALID_TILE
};
321 * Levels a selected (rectangle) area of land
322 * @param flags for this command type
323 * @param tile end tile of area-drag
324 * @param start_tile start tile of area drag
325 * @param diagonal Whether to use the Orthogonal (false) or Diagonal (true) iterator.
326 * @param LevelMode Mode of leveling \c LevelMode.
327 * @return the cost of this operation or an error
329 std::tuple
<CommandCost
, Money
, TileIndex
> CmdLevelLand(DoCommandFlag flags
, TileIndex tile
, TileIndex start_tile
, bool diagonal
, LevelMode lm
)
331 if (start_tile
>= Map::Size()) return { CMD_ERROR
, 0, INVALID_TILE
};
333 /* remember level height */
334 uint oldh
= TileHeight(start_tile
);
336 /* compute new height */
339 case LM_LEVEL
: break;
340 case LM_RAISE
: h
++; break;
341 case LM_LOWER
: h
--; break;
342 default: return { CMD_ERROR
, 0, INVALID_TILE
};
345 /* Check range of destination height */
346 if (h
> _settings_game
.construction
.map_height_limit
) return { CommandCost(oldh
== 0 ? STR_ERROR_ALREADY_AT_SEA_LEVEL
: STR_ERROR_TOO_HIGH
), 0, INVALID_TILE
};
348 Money money
= GetAvailableMoneyForCommand();
349 CommandCost
cost(EXPENSES_CONSTRUCTION
);
350 CommandCost
last_error(lm
== LM_LEVEL
? STR_ERROR_ALREADY_LEVELLED
: INVALID_STRING_ID
);
351 bool had_success
= false;
353 const Company
*c
= Company::GetIfValid(_current_company
);
354 int limit
= (c
== nullptr ? INT32_MAX
: GB(c
->terraform_limit
, 16, 16));
355 if (limit
== 0) return { CommandCost(STR_ERROR_TERRAFORM_LIMIT_REACHED
), 0, INVALID_TILE
};
357 TileIndex error_tile
= INVALID_TILE
;
358 std::unique_ptr
<TileIterator
> iter
= TileIterator::Create(tile
, start_tile
, diagonal
);
359 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
361 uint curh
= TileHeight(t
);
364 std::tie(ret
, std::ignore
, error_tile
) = Command
<CMD_TERRAFORM_LAND
>::Do(flags
& ~DC_EXEC
, t
, SLOPE_N
, curh
<= h
);
368 /* Did we reach the limit? */
369 if (ret
.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED
) limit
= 0;
373 if (flags
& DC_EXEC
) {
374 money
-= ret
.GetCost();
376 return { cost
, ret
.GetCost(), error_tile
};
378 Command
<CMD_TERRAFORM_LAND
>::Do(flags
, t
, SLOPE_N
, curh
<= h
);
380 /* When we're at the terraform limit we better bail (unneeded) testing as well.
381 * This will probably cause the terraforming cost to be underestimated, but only
382 * when it's near the terraforming limit. Even then, the estimation is
383 * completely off due to it basically counting terraforming double, so it being
384 * cut off earlier might even give a better estimate in some cases. */
392 curh
+= (curh
> h
) ? -1 : 1;
396 if (limit
<= 0) break;
399 CommandCost cc_ret
= had_success
? cost
: last_error
;
400 return { cc_ret
, 0, cc_ret
.Succeeded() ? tile
: error_tile
};