Fix #10208: allow to use specific underlay for road/tram tunnels (#10233)
[openttd-github.git] / src / road_cmd.cpp
blobdda2f2fa2aee21ef8400e3f8859c01ef1eef3e0e
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 road_cmd.cpp Commands related to road tiles. */
10 #include "stdafx.h"
11 #include "road.h"
12 #include "road_internal.h"
13 #include "viewport_func.h"
14 #include "command_func.h"
15 #include "pathfinder/yapf/yapf_cache.h"
16 #include "depot_base.h"
17 #include "newgrf.h"
18 #include "autoslope.h"
19 #include "tunnelbridge_map.h"
20 #include "strings_func.h"
21 #include "vehicle_func.h"
22 #include "sound_func.h"
23 #include "tunnelbridge.h"
24 #include "cheat_type.h"
25 #include "effectvehicle_func.h"
26 #include "effectvehicle_base.h"
27 #include "elrail_func.h"
28 #include "roadveh.h"
29 #include "town.h"
30 #include "company_base.h"
31 #include "core/random_func.hpp"
32 #include "newgrf_debug.h"
33 #include "newgrf_railtype.h"
34 #include "newgrf_roadtype.h"
35 #include "date_func.h"
36 #include "genworld.h"
37 #include "company_gui.h"
38 #include "road_func.h"
39 #include "road_cmd.h"
40 #include "landscape_cmd.h"
41 #include "rail_cmd.h"
43 #include "table/strings.h"
44 #include "table/roadtypes.h"
46 #include "safeguards.h"
48 /** Helper type for lists/vectors of road vehicles */
49 typedef std::vector<RoadVehicle *> RoadVehicleList;
51 RoadTypeInfo _roadtypes[ROADTYPE_END];
52 std::vector<RoadType> _sorted_roadtypes;
53 RoadTypes _roadtypes_hidden_mask;
55 /**
56 * Bitmap of road/tram types.
57 * Bit if set if a roadtype is tram.
59 RoadTypes _roadtypes_type;
61 /**
62 * Reset all road type information to its default values.
64 void ResetRoadTypes()
66 static_assert(lengthof(_original_roadtypes) <= lengthof(_roadtypes));
68 uint i = 0;
69 for (; i < lengthof(_original_roadtypes); i++) _roadtypes[i] = _original_roadtypes[i];
71 static const RoadTypeInfo empty_roadtype = {
72 { 0, 0, 0, 0, 0, 0 },
73 { 0, 0, 0, 0, 0, 0 },
74 { 0, 0, 0, 0, 0, 0, 0, 0, 0, {}, {}, 0, {}, {} },
75 ROADTYPES_NONE, ROTFB_NONE, 0, 0, 0, 0,
76 RoadTypeLabelList(), 0, 0, ROADTYPES_NONE, ROADTYPES_NONE, 0,
77 {}, {} };
78 for (; i < lengthof(_roadtypes); i++) _roadtypes[i] = empty_roadtype;
80 _roadtypes_hidden_mask = ROADTYPES_NONE;
81 _roadtypes_type = ROADTYPES_TRAM;
84 void ResolveRoadTypeGUISprites(RoadTypeInfo *rti)
86 SpriteID cursors_base = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_CURSORS);
87 if (cursors_base != 0) {
88 rti->gui_sprites.build_y_road = cursors_base + 0;
89 rti->gui_sprites.build_x_road = cursors_base + 1;
90 rti->gui_sprites.auto_road = cursors_base + 2;
91 rti->gui_sprites.build_depot = cursors_base + 3;
92 rti->gui_sprites.build_tunnel = cursors_base + 4;
93 rti->gui_sprites.convert_road = cursors_base + 5;
94 rti->cursor.road_swne = cursors_base + 6;
95 rti->cursor.road_nwse = cursors_base + 7;
96 rti->cursor.autoroad = cursors_base + 8;
97 rti->cursor.depot = cursors_base + 9;
98 rti->cursor.tunnel = cursors_base + 10;
99 rti->cursor.convert_road = cursors_base + 11;
104 * Compare roadtypes based on their sorting order.
105 * @param first The roadtype to compare to.
106 * @param second The roadtype to compare.
107 * @return True iff the first should be sorted before the second.
109 static bool CompareRoadTypes(const RoadType &first, const RoadType &second)
111 if (RoadTypeIsRoad(first) == RoadTypeIsRoad(second)) {
112 return GetRoadTypeInfo(first)->sorting_order < GetRoadTypeInfo(second)->sorting_order;
114 return RoadTypeIsTram(first) < RoadTypeIsTram(second);
118 * Resolve sprites of custom road types
120 void InitRoadTypes()
122 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
123 RoadTypeInfo *rti = &_roadtypes[rt];
124 ResolveRoadTypeGUISprites(rti);
125 if (HasBit(rti->flags, ROTF_HIDDEN)) SetBit(_roadtypes_hidden_mask, rt);
128 _sorted_roadtypes.clear();
129 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
130 if (_roadtypes[rt].label != 0 && !HasBit(_roadtypes_hidden_mask, rt)) {
131 _sorted_roadtypes.push_back(rt);
134 std::sort(_sorted_roadtypes.begin(), _sorted_roadtypes.end(), CompareRoadTypes);
138 * Allocate a new road type label
140 RoadType AllocateRoadType(RoadTypeLabel label, RoadTramType rtt)
142 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
143 RoadTypeInfo *rti = &_roadtypes[rt];
145 if (rti->label == 0) {
146 /* Set up new road type */
147 *rti = _original_roadtypes[(rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD];
148 rti->label = label;
149 rti->alternate_labels.clear();
150 rti->flags = ROTFB_NONE;
151 rti->introduction_date = INVALID_DATE;
153 /* Make us compatible with ourself. */
154 rti->powered_roadtypes = (RoadTypes)(1ULL << rt);
156 /* We also introduce ourself. */
157 rti->introduces_roadtypes = (RoadTypes)(1ULL << rt);
159 /* Default sort order; order of allocation, but with some
160 * offsets so it's easier for NewGRF to pick a spot without
161 * changing the order of other (original) road types.
162 * The << is so you can place other roadtypes in between the
163 * other roadtypes, the 7 is to be able to place something
164 * before the first (default) road type. */
165 rti->sorting_order = rt << 2 | 7;
167 /* Set bitmap of road/tram types */
168 if (rtt == RTT_TRAM) {
169 SetBit(_roadtypes_type, rt);
170 } else {
171 ClrBit(_roadtypes_type, rt);
174 return rt;
178 return INVALID_ROADTYPE;
182 * Verify whether a road vehicle is available.
183 * @return \c true if at least one road vehicle is available, \c false if not
185 bool RoadVehiclesAreBuilt()
187 return !RoadVehicle::Iterate().empty();
191 * Update road infrastructure counts for a company.
192 * @param rt Road type to update count of.
193 * @param o Owner of road piece.
194 * @param count Number of road pieces to adjust.
196 void UpdateCompanyRoadInfrastructure(RoadType rt, Owner o, int count)
198 if (rt == INVALID_ROADTYPE) return;
200 Company *c = Company::GetIfValid(o);
201 if (c == nullptr) return;
203 c->infrastructure.road[rt] += count;
204 DirtyCompanyInfrastructureWindows(c->index);
207 /** Invalid RoadBits on slopes. */
208 static const RoadBits _invalid_tileh_slopes_road[2][15] = {
209 /* The inverse of the mixable RoadBits on a leveled slope */
211 ROAD_NONE, // SLOPE_FLAT
212 ROAD_NE | ROAD_SE, // SLOPE_W
213 ROAD_NE | ROAD_NW, // SLOPE_S
215 ROAD_NE, // SLOPE_SW
216 ROAD_NW | ROAD_SW, // SLOPE_E
217 ROAD_NONE, // SLOPE_EW
219 ROAD_NW, // SLOPE_SE
220 ROAD_NONE, // SLOPE_WSE
221 ROAD_SE | ROAD_SW, // SLOPE_N
223 ROAD_SE, // SLOPE_NW
224 ROAD_NONE, // SLOPE_NS
225 ROAD_NONE, // SLOPE_ENW
227 ROAD_SW, // SLOPE_NE
228 ROAD_NONE, // SLOPE_SEN
229 ROAD_NONE // SLOPE_NWS
231 /* The inverse of the allowed straight roads on a slope
232 * (with and without a foundation). */
234 ROAD_NONE, // SLOPE_FLAT
235 ROAD_NONE, // SLOPE_W Foundation
236 ROAD_NONE, // SLOPE_S Foundation
238 ROAD_Y, // SLOPE_SW
239 ROAD_NONE, // SLOPE_E Foundation
240 ROAD_ALL, // SLOPE_EW
242 ROAD_X, // SLOPE_SE
243 ROAD_ALL, // SLOPE_WSE
244 ROAD_NONE, // SLOPE_N Foundation
246 ROAD_X, // SLOPE_NW
247 ROAD_ALL, // SLOPE_NS
248 ROAD_ALL, // SLOPE_ENW
250 ROAD_Y, // SLOPE_NE
251 ROAD_ALL, // SLOPE_SEN
252 ROAD_ALL // SLOPE_NW
256 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits);
259 * Is it allowed to remove the given road bits from the given tile?
260 * @param tile the tile to remove the road from
261 * @param remove the roadbits that are going to be removed
262 * @param owner the actual owner of the roadbits of the tile
263 * @param rt the road type to remove the bits from
264 * @param flags command flags
265 * @param town_check Shall the town rating checked/affected
266 * @return A succeeded command when it is allowed to remove the road bits, a failed command otherwise.
268 CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadTramType rtt, DoCommandFlag flags, bool town_check)
270 if (_game_mode == GM_EDITOR || remove == ROAD_NONE) return CommandCost();
272 /* Water can always flood and towns can always remove "normal" road pieces.
273 * Towns are not be allowed to remove non "normal" road pieces, like tram
274 * tracks as that would result in trams that cannot turn. */
275 if (_current_company == OWNER_WATER ||
276 (rtt == RTT_ROAD && !Company::IsValidID(_current_company))) return CommandCost();
278 /* Only do the special processing if the road is owned
279 * by a town */
280 if (owner != OWNER_TOWN) {
281 if (owner == OWNER_NONE) return CommandCost();
282 CommandCost ret = CheckOwnership(owner);
283 return ret;
286 if (!town_check) return CommandCost();
288 if (_cheats.magic_bulldozer.value) return CommandCost();
290 Town *t = ClosestTownFromTile(tile, UINT_MAX);
291 if (t == nullptr) return CommandCost();
293 /* check if you're allowed to remove the street owned by a town
294 * removal allowance depends on difficulty setting */
295 CommandCost ret = CheckforTownRating(flags, t, ROAD_REMOVE);
296 if (ret.Failed()) return ret;
298 /* Get a bitmask of which neighbouring roads has a tile */
299 RoadBits n = ROAD_NONE;
300 RoadBits present = GetAnyRoadBits(tile, rtt);
301 if ((present & ROAD_NE) && (GetAnyRoadBits(TILE_ADDXY(tile, -1, 0), rtt) & ROAD_SW)) n |= ROAD_NE;
302 if ((present & ROAD_SE) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, 1), rtt) & ROAD_NW)) n |= ROAD_SE;
303 if ((present & ROAD_SW) && (GetAnyRoadBits(TILE_ADDXY(tile, 1, 0), rtt) & ROAD_NE)) n |= ROAD_SW;
304 if ((present & ROAD_NW) && (GetAnyRoadBits(TILE_ADDXY(tile, 0, -1), rtt) & ROAD_SE)) n |= ROAD_NW;
306 int rating_decrease = RATING_ROAD_DOWN_STEP_EDGE;
307 /* If 0 or 1 bits are set in n, or if no bits that match the bits to remove,
308 * then allow it */
309 if (KillFirstBit(n) != ROAD_NONE && (n & remove) != ROAD_NONE) {
310 /* you can remove all kind of roads with extra dynamite */
311 if (!_settings_game.construction.extra_dynamite) {
312 SetDParam(0, t->index);
313 return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
315 rating_decrease = RATING_ROAD_DOWN_STEP_INNER;
317 ChangeTownRating(t, rating_decrease, RATING_ROAD_MINIMUM, flags);
319 return CommandCost();
324 * Delete a piece of road.
325 * @param tile tile where to remove road from
326 * @param flags operation to perform
327 * @param pieces roadbits to remove
328 * @param rt roadtype to remove
329 * @param crossing_check should we check if there is a tram track when we are removing road from crossing?
330 * @param town_check should we check if the town allows removal?
332 static CommandCost RemoveRoad(TileIndex tile, DoCommandFlag flags, RoadBits pieces, RoadTramType rtt, bool crossing_check, bool town_check = true)
334 assert(pieces != ROAD_NONE);
336 RoadType existing_rt = MayHaveRoad(tile) ? GetRoadType(tile, rtt) : INVALID_ROADTYPE;
337 /* The tile doesn't have the given road type */
338 if (existing_rt == INVALID_ROADTYPE) return_cmd_error((rtt == RTT_TRAM) ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
340 switch (GetTileType(tile)) {
341 case MP_ROAD: {
342 CommandCost ret = EnsureNoVehicleOnGround(tile);
343 if (ret.Failed()) return ret;
344 break;
347 case MP_STATION: {
348 if (!IsDriveThroughStopTile(tile)) return CMD_ERROR;
350 CommandCost ret = EnsureNoVehicleOnGround(tile);
351 if (ret.Failed()) return ret;
352 break;
355 case MP_TUNNELBRIDGE: {
356 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) return CMD_ERROR;
357 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
358 if (ret.Failed()) return ret;
359 break;
362 default:
363 return CMD_ERROR;
366 CommandCost ret = CheckAllowRemoveRoad(tile, pieces, GetRoadOwner(tile, rtt), rtt, flags, town_check);
367 if (ret.Failed()) return ret;
369 if (!IsTileType(tile, MP_ROAD)) {
370 /* If it's the last roadtype, just clear the whole tile */
371 if (GetRoadType(tile, OtherRoadTramType(rtt)) == INVALID_ROADTYPE) return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
373 CommandCost cost(EXPENSES_CONSTRUCTION);
374 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
375 /* Removing any roadbit in the bridge axis removes the roadtype (that's the behaviour remove-long-roads needs) */
376 if ((AxisToRoadBits(DiagDirToAxis(GetTunnelBridgeDirection(tile))) & pieces) == ROAD_NONE) return_cmd_error((rtt == RTT_TRAM) ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
378 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
379 /* Pay for *every* tile of the bridge or tunnel */
380 uint len = GetTunnelBridgeLength(other_end, tile) + 2;
381 cost.AddCost(len * 2 * RoadClearCost(existing_rt));
382 if (flags & DC_EXEC) {
383 /* A full diagonal road tile has two road bits. */
384 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -(int)(len * 2 * TUNNELBRIDGE_TRACKBIT_FACTOR));
386 SetRoadType(other_end, rtt, INVALID_ROADTYPE);
387 SetRoadType(tile, rtt, INVALID_ROADTYPE);
389 /* If the owner of the bridge sells all its road, also move the ownership
390 * to the owner of the other roadtype, unless the bridge owner is a town. */
391 Owner other_owner = GetRoadOwner(tile, OtherRoadTramType(rtt));
392 if (!IsTileOwner(tile, other_owner) && !IsTileOwner(tile, OWNER_TOWN)) {
393 SetTileOwner(tile, other_owner);
394 SetTileOwner(other_end, other_owner);
397 /* Mark tiles dirty that have been repaved */
398 if (IsBridge(tile)) {
399 MarkBridgeDirty(tile);
400 } else {
401 MarkTileDirtyByTile(tile);
402 MarkTileDirtyByTile(other_end);
405 } else {
406 assert(IsDriveThroughStopTile(tile));
407 cost.AddCost(RoadClearCost(existing_rt) * 2);
408 if (flags & DC_EXEC) {
409 /* A full diagonal road tile has two road bits. */
410 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -2);
411 SetRoadType(tile, rtt, INVALID_ROADTYPE);
412 MarkTileDirtyByTile(tile);
415 return cost;
418 switch (GetRoadTileType(tile)) {
419 case ROAD_TILE_NORMAL: {
420 Slope tileh = GetTileSlope(tile);
422 /* Steep slopes behave the same as slopes with one corner raised. */
423 if (IsSteepSlope(tileh)) {
424 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
427 RoadBits present = GetRoadBits(tile, rtt);
428 const RoadBits other = GetRoadBits(tile, OtherRoadTramType(rtt));
429 const Foundation f = GetRoadFoundation(tileh, present);
431 if (HasRoadWorks(tile) && _current_company != OWNER_WATER) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
433 /* Autocomplete to a straight road
434 * @li if the bits of the other roadtypes result in another foundation
435 * @li if build on slopes is disabled */
436 if ((IsStraightRoad(other) && (other & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) != ROAD_NONE) ||
437 (tileh != SLOPE_FLAT && !_settings_game.construction.build_on_slopes)) {
438 pieces |= MirrorRoadBits(pieces);
441 /* limit the bits to delete to the existing bits. */
442 pieces &= present;
443 if (pieces == ROAD_NONE) return_cmd_error((rtt == RTT_TRAM) ? STR_ERROR_THERE_IS_NO_TRAMWAY : STR_ERROR_THERE_IS_NO_ROAD);
445 /* Now set present what it will be after the remove */
446 present ^= pieces;
448 /* Check for invalid RoadBit combinations on slopes */
449 if (tileh != SLOPE_FLAT && present != ROAD_NONE &&
450 (present & _invalid_tileh_slopes_road[0][tileh & SLOPE_ELEVATED]) == present) {
451 return CMD_ERROR;
454 if (flags & DC_EXEC) {
455 if (HasRoadWorks(tile)) {
456 /* flooding tile with road works, don't forget to remove the effect vehicle too */
457 assert(_current_company == OWNER_WATER);
458 for (EffectVehicle *v : EffectVehicle::Iterate()) {
459 if (TileVirtXY(v->x_pos, v->y_pos) == tile) {
460 delete v;
465 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -(int)CountBits(pieces));
467 if (present == ROAD_NONE) {
468 /* No other road type, just clear tile. */
469 if (GetRoadType(tile, OtherRoadTramType(rtt)) == INVALID_ROADTYPE) {
470 /* Includes MarkTileDirtyByTile() */
471 DoClearSquare(tile);
472 } else {
473 if (rtt == RTT_ROAD && IsRoadOwner(tile, rtt, OWNER_TOWN)) {
474 /* Update nearest-town index */
475 const Town *town = CalcClosestTownFromTile(tile);
476 SetTownIndex(tile, town == nullptr ? INVALID_TOWN : town->index);
478 SetRoadBits(tile, ROAD_NONE, rtt);
479 SetRoadType(tile, rtt, INVALID_ROADTYPE);
480 MarkTileDirtyByTile(tile);
482 } else {
483 /* When bits are removed, you *always* end up with something that
484 * is not a complete straight road tile. However, trams do not have
485 * onewayness, so they cannot remove it either. */
486 if (rtt == RTT_ROAD) SetDisallowedRoadDirections(tile, DRD_NONE);
487 SetRoadBits(tile, present, rtt);
488 MarkTileDirtyByTile(tile);
492 CommandCost cost(EXPENSES_CONSTRUCTION, CountBits(pieces) * RoadClearCost(existing_rt));
493 /* If we build a foundation we have to pay for it. */
494 if (f == FOUNDATION_NONE && GetRoadFoundation(tileh, present) != FOUNDATION_NONE) cost.AddCost(_price[PR_BUILD_FOUNDATION]);
496 return cost;
499 case ROAD_TILE_CROSSING: {
500 if (pieces & ComplementRoadBits(GetCrossingRoadBits(tile))) {
501 return CMD_ERROR;
504 if (flags & DC_EXEC) {
505 MarkDirtyAdjacentLevelCrossingTiles(tile, GetCrossingRoadAxis(tile));
507 /* A full diagonal road tile has two road bits. */
508 UpdateCompanyRoadInfrastructure(existing_rt, GetRoadOwner(tile, rtt), -2);
510 Track railtrack = GetCrossingRailTrack(tile);
511 if (GetRoadType(tile, OtherRoadTramType(rtt)) == INVALID_ROADTYPE) {
512 TrackBits tracks = GetCrossingRailBits(tile);
513 bool reserved = HasCrossingReservation(tile);
514 MakeRailNormal(tile, GetTileOwner(tile), tracks, GetRailType(tile));
515 if (reserved) SetTrackReservation(tile, tracks);
517 /* Update rail count for level crossings. The plain track should still be accounted
518 * for, so only subtract the difference to the level crossing cost. */
519 Company *c = Company::GetIfValid(GetTileOwner(tile));
520 if (c != nullptr) {
521 c->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR - 1;
522 DirtyCompanyInfrastructureWindows(c->index);
524 } else {
525 SetRoadType(tile, rtt, INVALID_ROADTYPE);
527 MarkTileDirtyByTile(tile);
528 YapfNotifyTrackLayoutChange(tile, railtrack);
530 return CommandCost(EXPENSES_CONSTRUCTION, RoadClearCost(existing_rt) * 2);
533 default:
534 case ROAD_TILE_DEPOT:
535 return CMD_ERROR;
541 * Calculate the costs for roads on slopes
542 * Aside modify the RoadBits to fit on the slopes
544 * @note The RoadBits are modified too!
545 * @param tileh The current slope
546 * @param pieces The RoadBits we want to add
547 * @param existing The existent RoadBits of the current type
548 * @param other The other existent RoadBits
549 * @return The costs for these RoadBits on this slope
551 static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existing, RoadBits other)
553 /* Remove already build pieces */
554 CLRBITS(*pieces, existing);
556 /* If we can't build anything stop here */
557 if (*pieces == ROAD_NONE) return CMD_ERROR;
559 /* All RoadBit combos are valid on flat land */
560 if (tileh == SLOPE_FLAT) return CommandCost();
562 /* Steep slopes behave the same as slopes with one corner raised. */
563 if (IsSteepSlope(tileh)) {
564 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
567 /* Save the merge of all bits of the current type */
568 RoadBits type_bits = existing | *pieces;
570 /* Roads on slopes */
571 if (_settings_game.construction.build_on_slopes && (_invalid_tileh_slopes_road[0][tileh] & (other | type_bits)) == ROAD_NONE) {
573 /* If we add leveling we've got to pay for it */
574 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
576 return CommandCost();
579 /* Autocomplete uphill roads */
580 *pieces |= MirrorRoadBits(*pieces);
581 type_bits = existing | *pieces;
583 /* Uphill roads */
584 if (IsStraightRoad(type_bits) && (other == type_bits || other == ROAD_NONE) &&
585 (_invalid_tileh_slopes_road[1][tileh] & (other | type_bits)) == ROAD_NONE) {
587 /* Slopes with foundation ? */
588 if (IsSlopeWithOneCornerRaised(tileh)) {
590 /* Prevent build on slopes if it isn't allowed */
591 if (_settings_game.construction.build_on_slopes) {
593 /* If we add foundation we've got to pay for it */
594 if ((other | existing) == ROAD_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
596 return CommandCost();
598 } else {
599 if (HasExactlyOneBit(existing) && GetRoadFoundation(tileh, existing) == FOUNDATION_NONE) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
600 return CommandCost();
603 return CMD_ERROR;
607 * Build a piece of road.
608 * @param flags operation to perform
609 * @param tile tile where to build road
610 * @param pieces road pieces to build (RoadBits)
611 * @param rt road type
612 * @param toggle_drd disallowed directions to toggle
613 * @param town_id the town that is building the road (0 if not applicable)
614 * @return the cost of this operation or an error
616 CommandCost CmdBuildRoad(DoCommandFlag flags, TileIndex tile, RoadBits pieces, RoadType rt, DisallowedRoadDirections toggle_drd, TownID town_id)
618 CompanyID company = _current_company;
619 CommandCost cost(EXPENSES_CONSTRUCTION);
621 RoadBits existing = ROAD_NONE;
622 RoadBits other_bits = ROAD_NONE;
624 /* Road pieces are max 4 bitset values (NE, NW, SE, SW) and town can only be non-zero
625 * if a non-company is building the road */
626 if ((Company::IsValidID(company) && town_id != 0) || (company == OWNER_TOWN && !Town::IsValidID(town_id)) || (company == OWNER_DEITY && town_id != 0)) return CMD_ERROR;
627 if (company != OWNER_TOWN) {
628 const Town *town = CalcClosestTownFromTile(tile);
629 town_id = (town != nullptr) ? town->index : INVALID_TOWN;
631 if (company == OWNER_DEITY) {
632 company = OWNER_TOWN;
634 /* If we are not within a town, we are not owned by the town */
635 if (town == nullptr || DistanceSquare(tile, town->xy) > town->cache.squared_town_zone_radius[HZB_TOWN_EDGE]) {
636 company = OWNER_NONE;
641 /* do not allow building 'zero' road bits, code wouldn't handle it */
642 if (pieces == ROAD_NONE || !IsValidRoadBits(pieces) || !IsValidDisallowedRoadDirections(toggle_drd)) return CMD_ERROR;
643 if (!ValParamRoadType(rt)) return CMD_ERROR;
645 Slope tileh = GetTileSlope(tile);
646 RoadTramType rtt = GetRoadTramType(rt);
648 bool need_to_clear = false;
649 switch (GetTileType(tile)) {
650 case MP_ROAD:
651 switch (GetRoadTileType(tile)) {
652 case ROAD_TILE_NORMAL: {
653 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
655 other_bits = GetRoadBits(tile, OtherRoadTramType(rtt));
656 if (!HasTileRoadType(tile, rtt)) break;
658 existing = GetRoadBits(tile, rtt);
659 bool crossing = !IsStraightRoad(existing | pieces);
660 if (rtt == RTT_ROAD && (GetDisallowedRoadDirections(tile) != DRD_NONE || toggle_drd != DRD_NONE) && crossing) {
661 /* Junctions cannot be one-way */
662 return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
664 if ((existing & pieces) == pieces) {
665 /* We only want to set the (dis)allowed road directions */
666 if (toggle_drd != DRD_NONE && rtt == RTT_ROAD) {
667 if (crossing) return_cmd_error(STR_ERROR_ONEWAY_ROADS_CAN_T_HAVE_JUNCTION);
669 Owner owner = GetRoadOwner(tile, rtt);
670 if (owner != OWNER_NONE) {
671 CommandCost ret = CheckOwnership(owner, tile);
672 if (ret.Failed()) return ret;
675 DisallowedRoadDirections dis_existing = GetDisallowedRoadDirections(tile);
676 DisallowedRoadDirections dis_new = dis_existing ^ toggle_drd;
678 /* We allow removing disallowed directions to break up
679 * deadlocks, but adding them can break articulated
680 * vehicles. As such, only when less is disallowed,
681 * i.e. bits are removed, we skip the vehicle check. */
682 if (CountBits(dis_existing) <= CountBits(dis_new)) {
683 CommandCost ret = EnsureNoVehicleOnGround(tile);
684 if (ret.Failed()) return ret;
687 /* Ignore half built tiles */
688 if ((flags & DC_EXEC) && IsStraightRoad(existing)) {
689 SetDisallowedRoadDirections(tile, dis_new);
690 MarkTileDirtyByTile(tile);
692 return CommandCost();
694 return_cmd_error(STR_ERROR_ALREADY_BUILT);
696 /* Disallow breaking end-of-line of someone else
697 * so trams can still reverse on this tile. */
698 if (rtt == RTT_TRAM && HasExactlyOneBit(existing)) {
699 Owner owner = GetRoadOwner(tile, rtt);
700 if (Company::IsValidID(owner)) {
701 CommandCost ret = CheckOwnership(owner);
702 if (ret.Failed()) return ret;
705 break;
708 case ROAD_TILE_CROSSING:
709 if (RoadNoLevelCrossing(rt)) {
710 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
713 other_bits = GetCrossingRoadBits(tile);
714 if (pieces & ComplementRoadBits(other_bits)) goto do_clear;
715 pieces = other_bits; // we need to pay for both roadbits
717 if (HasTileRoadType(tile, rtt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
718 break;
720 case ROAD_TILE_DEPOT:
721 if ((GetAnyRoadBits(tile, rtt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
722 goto do_clear;
724 default: NOT_REACHED();
726 break;
728 case MP_RAILWAY: {
729 if (IsSteepSlope(tileh)) {
730 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
733 /* Level crossings may only be built on these slopes */
734 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) {
735 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
738 if (GetRailTileType(tile) != RAIL_TILE_NORMAL) goto do_clear;
740 if (RoadNoLevelCrossing(rt)) {
741 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
744 if (RailNoLevelCrossings(GetRailType(tile))) {
745 return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_RAIL);
748 Axis roaddir;
749 switch (GetTrackBits(tile)) {
750 case TRACK_BIT_X:
751 if (pieces & ROAD_X) goto do_clear;
752 roaddir = AXIS_Y;
753 break;
755 case TRACK_BIT_Y:
756 if (pieces & ROAD_Y) goto do_clear;
757 roaddir = AXIS_X;
758 break;
760 default: goto do_clear;
763 CommandCost ret = EnsureNoVehicleOnGround(tile);
764 if (ret.Failed()) return ret;
766 if (flags & DC_EXEC) {
767 Track railtrack = AxisToTrack(OtherAxis(roaddir));
768 YapfNotifyTrackLayoutChange(tile, railtrack);
769 /* Update company infrastructure counts. A level crossing has two road bits. */
770 UpdateCompanyRoadInfrastructure(rt, company, 2);
772 /* Update rail count for level crossings. The plain track is already
773 * counted, so only add the difference to the level crossing cost. */
774 Company *c = Company::GetIfValid(GetTileOwner(tile));
775 if (c != nullptr) {
776 c->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR - 1;
777 DirtyCompanyInfrastructureWindows(c->index);
780 /* Always add road to the roadtypes (can't draw without it) */
781 bool reserved = HasBit(GetRailReservationTrackBits(tile), railtrack);
782 MakeRoadCrossing(tile, company, company, GetTileOwner(tile), roaddir, GetRailType(tile), rtt == RTT_ROAD ? rt : INVALID_ROADTYPE, (rtt == RTT_TRAM) ? rt : INVALID_ROADTYPE, town_id);
783 SetCrossingReservation(tile, reserved);
784 UpdateLevelCrossing(tile, false);
785 MarkDirtyAdjacentLevelCrossingTiles(tile, GetCrossingRoadAxis(tile));
786 MarkTileDirtyByTile(tile);
788 return CommandCost(EXPENSES_CONSTRUCTION, 2 * RoadBuildCost(rt));
791 case MP_STATION: {
792 if ((GetAnyRoadBits(tile, rtt) & pieces) == pieces) return_cmd_error(STR_ERROR_ALREADY_BUILT);
793 if (!IsDriveThroughStopTile(tile)) goto do_clear;
795 RoadBits curbits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(tile)));
796 if (pieces & ~curbits) goto do_clear;
797 pieces = curbits; // we need to pay for both roadbits
799 if (HasTileRoadType(tile, rtt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
800 break;
803 case MP_TUNNELBRIDGE: {
804 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) goto do_clear;
805 /* Only allow building the outern roadbit, so building long roads stops at existing bridges */
806 if (MirrorRoadBits(DiagDirToRoadBits(GetTunnelBridgeDirection(tile))) != pieces) goto do_clear;
807 if (HasTileRoadType(tile, rtt)) return_cmd_error(STR_ERROR_ALREADY_BUILT);
808 /* Don't allow adding roadtype to the bridge/tunnel when vehicles are already driving on it */
809 CommandCost ret = TunnelBridgeIsFree(tile, GetOtherTunnelBridgeEnd(tile));
810 if (ret.Failed()) return ret;
811 break;
814 default: {
815 do_clear:;
816 need_to_clear = true;
817 break;
821 if (need_to_clear) {
822 CommandCost ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
823 if (ret.Failed()) return ret;
824 cost.AddCost(ret);
827 if (other_bits != pieces) {
828 /* Check the foundation/slopes when adding road/tram bits */
829 CommandCost ret = CheckRoadSlope(tileh, &pieces, existing, other_bits);
830 /* Return an error if we need to build a foundation (ret != 0) but the
831 * current setting is turned off */
832 if (ret.Failed() || (ret.GetCost() != 0 && !_settings_game.construction.build_on_slopes)) {
833 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
835 cost.AddCost(ret);
838 if (!need_to_clear) {
839 if (IsTileType(tile, MP_ROAD)) {
840 /* Don't put the pieces that already exist */
841 pieces &= ComplementRoadBits(existing);
843 /* Check if new road bits will have the same foundation as other existing road types */
844 if (IsNormalRoad(tile)) {
845 Slope slope = GetTileSlope(tile);
846 Foundation found_new = GetRoadFoundation(slope, pieces | existing);
848 RoadBits bits = GetRoadBits(tile, OtherRoadTramType(rtt));
849 /* do not check if there are not road bits of given type */
850 if (bits != ROAD_NONE && GetRoadFoundation(slope, bits) != found_new) {
851 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
856 CommandCost ret = EnsureNoVehicleOnGround(tile);
857 if (ret.Failed()) return ret;
859 if (IsNormalRoadTile(tile)) {
860 /* If the road types don't match, try to convert only if vehicles of
861 * the new road type are not powered on the present road type and vehicles of
862 * the present road type are powered on the new road type. */
863 RoadType existing_rt = GetRoadType(tile, rtt);
864 if (existing_rt != INVALID_ROADTYPE && existing_rt != rt) {
865 if (HasPowerOnRoad(rt, existing_rt)) {
866 rt = existing_rt;
867 } else if (HasPowerOnRoad(existing_rt, rt)) {
868 CommandCost ret = Command<CMD_CONVERT_ROAD>::Do(flags, tile, tile, rt);
869 if (ret.Failed()) return ret;
870 cost.AddCost(ret);
871 } else {
872 return CMD_ERROR;
878 uint num_pieces = (!need_to_clear && IsTileType(tile, MP_TUNNELBRIDGE)) ?
879 /* There are 2 pieces on *every* tile of the bridge or tunnel */
880 2 * (GetTunnelBridgeLength(GetOtherTunnelBridgeEnd(tile), tile) + 2) :
881 /* Count pieces */
882 CountBits(pieces);
884 cost.AddCost(num_pieces * RoadBuildCost(rt));
886 if (flags & DC_EXEC) {
887 switch (GetTileType(tile)) {
888 case MP_ROAD: {
889 RoadTileType rttype = GetRoadTileType(tile);
890 if (existing == ROAD_NONE || rttype == ROAD_TILE_CROSSING) {
891 SetRoadType(tile, rtt, rt);
892 SetRoadOwner(tile, rtt, company);
893 if (rtt == RTT_ROAD) SetTownIndex(tile, town_id);
895 if (rttype != ROAD_TILE_CROSSING) SetRoadBits(tile, existing | pieces, rtt);
896 break;
899 case MP_TUNNELBRIDGE: {
900 TileIndex other_end = GetOtherTunnelBridgeEnd(tile);
902 SetRoadType(other_end, rtt, rt);
903 SetRoadType(tile, rtt, rt);
904 SetRoadOwner(other_end, rtt, company);
905 SetRoadOwner(tile, rtt, company);
907 /* Mark tiles dirty that have been repaved */
908 if (IsBridge(tile)) {
909 MarkBridgeDirty(tile);
910 } else {
911 MarkTileDirtyByTile(other_end);
912 MarkTileDirtyByTile(tile);
914 break;
917 case MP_STATION: {
918 assert(IsDriveThroughStopTile(tile));
919 SetRoadType(tile, rtt, rt);
920 SetRoadOwner(tile, rtt, company);
921 break;
924 default:
925 MakeRoadNormal(tile, pieces, (rtt == RTT_ROAD) ? rt : INVALID_ROADTYPE, (rtt == RTT_TRAM) ? rt : INVALID_ROADTYPE, town_id, company, company);
926 break;
929 /* Update company infrastructure count. */
930 if (IsTileType(tile, MP_TUNNELBRIDGE)) num_pieces *= TUNNELBRIDGE_TRACKBIT_FACTOR;
931 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), num_pieces);
933 if (rtt == RTT_ROAD && IsNormalRoadTile(tile)) {
934 existing |= pieces;
935 SetDisallowedRoadDirections(tile, IsStraightRoad(existing) ?
936 GetDisallowedRoadDirections(tile) ^ toggle_drd : DRD_NONE);
939 MarkTileDirtyByTile(tile);
941 return cost;
945 * Checks whether a road or tram connection can be found when building a new road or tram.
946 * @param tile Tile at which the road being built will end.
947 * @param rt Roadtype of the road being built.
948 * @param dir Direction that the road is following.
949 * @return True if the next tile at dir direction is suitable for being connected directly by a second roadbit at the end of the road being built.
951 static bool CanConnectToRoad(TileIndex tile, RoadType rt, DiagDirection dir)
953 tile += TileOffsByDiagDir(dir);
954 if (!IsValidTile(tile) || !MayHaveRoad(tile)) return false;
956 RoadTramType rtt = GetRoadTramType(rt);
957 RoadType existing = GetRoadType(tile, rtt);
958 if (existing == INVALID_ROADTYPE) return false;
959 if (!HasPowerOnRoad(existing, rt) && !HasPowerOnRoad(rt, existing)) return false;
961 RoadBits bits = GetAnyRoadBits(tile, rtt, false);
962 return (bits & DiagDirToRoadBits(ReverseDiagDir(dir))) != 0;
966 * Build a long piece of road.
967 * @param flags operation to perform
968 * @param end_tile end tile of drag
969 * @param start_tile start tile of drag
970 * @param rt road type
971 * @param axis direction
972 * @param drd set road direction
973 * @param start_half start tile starts in the 2nd half of tile (p2 & 1). Only used if \c is_ai is set or if we are building a single tile
974 * @param end_half end tile starts in the 2nd half of tile (p2 & 2). Only used if \c is_ai is set or if we are building a single tile
975 * @param is_ai defines two different behaviors for this command:
976 * - false = Build up to an obstacle. Do not build the first and last roadbits unless they can be connected to something, or if we are building a single tile
977 * - true = Fail if an obstacle is found. Always take into account start_half and end_half. This behavior is used for scripts
978 * @return the cost of this operation or an error
980 CommandCost CmdBuildLongRoad(DoCommandFlag flags, TileIndex end_tile, TileIndex start_tile, RoadType rt, Axis axis, DisallowedRoadDirections drd, bool start_half, bool end_half, bool is_ai)
982 if (start_tile >= MapSize()) return CMD_ERROR;
984 if (!ValParamRoadType(rt) || !IsValidAxis(axis) || !IsValidDisallowedRoadDirections(drd)) return CMD_ERROR;
986 /* Only drag in X or Y direction dictated by the direction variable */
987 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return CMD_ERROR; // x-axis
988 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return CMD_ERROR; // y-axis
990 DiagDirection dir = AxisToDiagDir(axis);
992 /* Swap direction, also the half-tile drag vars. */
993 if (start_tile > end_tile || (start_tile == end_tile && start_half)) {
994 dir = ReverseDiagDir(dir);
995 start_half = !start_half;
996 end_half = !end_half;
997 if (drd == DRD_NORTHBOUND || drd == DRD_SOUTHBOUND) drd ^= DRD_BOTH;
1000 /* On the X-axis, we have to swap the initial bits, so they
1001 * will be interpreted correctly in the GTTS. Furthermore
1002 * when you just 'click' on one tile to build them. */
1003 if ((drd == DRD_NORTHBOUND || drd == DRD_SOUTHBOUND) && (axis == AXIS_Y) == (start_tile == end_tile && start_half == end_half)) drd ^= DRD_BOTH;
1005 CommandCost cost(EXPENSES_CONSTRUCTION);
1006 CommandCost last_error = CMD_ERROR;
1007 TileIndex tile = start_tile;
1008 bool had_bridge = false;
1009 bool had_tunnel = false;
1010 bool had_success = false;
1012 /* Start tile is the first tile clicked by the user. */
1013 for (;;) {
1014 RoadBits bits = AxisToRoadBits(axis);
1016 /* Determine which road parts should be built. */
1017 if (!is_ai && start_tile != end_tile) {
1018 /* Only build the first and last roadbit if they can connect to something. */
1019 if (tile == end_tile && !CanConnectToRoad(tile, rt, dir)) {
1020 bits = DiagDirToRoadBits(ReverseDiagDir(dir));
1021 } else if (tile == start_tile && !CanConnectToRoad(tile, rt, ReverseDiagDir(dir))) {
1022 bits = DiagDirToRoadBits(dir);
1024 } else {
1025 /* Road parts only have to be built at the start tile or at the end tile. */
1026 if (tile == end_tile && !end_half) bits &= DiagDirToRoadBits(ReverseDiagDir(dir));
1027 if (tile == start_tile && start_half) bits &= DiagDirToRoadBits(dir);
1030 CommandCost ret = Command<CMD_BUILD_ROAD>::Do(flags, tile, bits, rt, drd, 0);
1031 if (ret.Failed()) {
1032 last_error = ret;
1033 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT) {
1034 if (is_ai) return last_error;
1035 break;
1037 } else {
1038 had_success = true;
1039 /* Only pay for the upgrade on one side of the bridges and tunnels */
1040 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1041 if (IsBridge(tile)) {
1042 if (!had_bridge || GetTunnelBridgeDirection(tile) == dir) {
1043 cost.AddCost(ret);
1045 had_bridge = true;
1046 } else { // IsTunnel(tile)
1047 if (!had_tunnel || GetTunnelBridgeDirection(tile) == dir) {
1048 cost.AddCost(ret);
1050 had_tunnel = true;
1052 } else {
1053 cost.AddCost(ret);
1057 if (tile == end_tile) break;
1059 tile += TileOffsByDiagDir(dir);
1062 return had_success ? cost : last_error;
1066 * Remove a long piece of road.
1067 * @param flags operation to perform
1068 * @param end_tile end tile of drag
1069 * @param start_tile start tile of drag
1070 * @param rt road type
1071 * @param axis direction
1072 * @param start_half start tile starts in the 2nd half of tile
1073 * @param end_half end tile starts in the 2nd half of tile (p2 & 2)
1074 * @return the cost of this operation or an error
1076 std::tuple<CommandCost, Money> CmdRemoveLongRoad(DoCommandFlag flags, TileIndex end_tile, TileIndex start_tile, RoadType rt, Axis axis, bool start_half, bool end_half)
1078 CommandCost cost(EXPENSES_CONSTRUCTION);
1080 if (start_tile >= MapSize()) return { CMD_ERROR, 0 };
1081 if (!ValParamRoadType(rt) || !IsValidAxis(axis)) return { CMD_ERROR, 0 };
1083 /* Only drag in X or Y direction dictated by the direction variable */
1084 if (axis == AXIS_X && TileY(start_tile) != TileY(end_tile)) return { CMD_ERROR, 0 }; // x-axis
1085 if (axis == AXIS_Y && TileX(start_tile) != TileX(end_tile)) return { CMD_ERROR, 0 }; // y-axis
1087 /* Swap start and ending tile, also the half-tile drag vars. */
1088 if (start_tile > end_tile || (start_tile == end_tile && start_half)) {
1089 std::swap(start_tile, end_tile);
1090 std::swap(start_half, end_half);
1093 Money money_available = GetAvailableMoneyForCommand();
1094 Money money_spent = 0;
1095 TileIndex tile = start_tile;
1096 CommandCost last_error = CMD_ERROR;
1097 bool had_success = false;
1098 /* Start tile is the small number. */
1099 for (;;) {
1100 RoadBits bits = AxisToRoadBits(axis);
1102 if (tile == end_tile && !end_half) bits &= ROAD_NW | ROAD_NE;
1103 if (tile == start_tile && start_half) bits &= ROAD_SE | ROAD_SW;
1105 /* try to remove the halves. */
1106 if (bits != 0) {
1107 RoadTramType rtt = GetRoadTramType(rt);
1108 CommandCost ret = RemoveRoad(tile, flags & ~DC_EXEC, bits, rtt, true);
1109 if (ret.Succeeded()) {
1110 if (flags & DC_EXEC) {
1111 money_spent += ret.GetCost();
1112 if (money_spent > 0 && money_spent > money_available) {
1113 return { cost, std::get<0>(Command<CMD_REMOVE_LONG_ROAD>::Do(flags & ~DC_EXEC, end_tile, start_tile, rt, axis, start_half, end_half)).GetCost() };
1115 RemoveRoad(tile, flags, bits, rtt, true, false);
1117 cost.AddCost(ret);
1118 had_success = true;
1119 } else {
1120 /* Some errors are more equal than others. */
1121 switch (last_error.GetErrorMessage()) {
1122 case STR_ERROR_OWNED_BY:
1123 case STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS:
1124 break;
1125 default:
1126 last_error = ret;
1131 if (tile == end_tile) break;
1133 tile += (axis == AXIS_Y) ? TileDiffXY(0, 1) : TileDiffXY(1, 0);
1136 return { had_success ? cost : last_error, 0 };
1140 * Build a road depot.
1141 * @param tile tile where to build the depot
1142 * @param flags operation to perform
1143 * @param rt road type
1144 * @param dir entrance direction
1145 * @return the cost of this operation or an error
1147 * @todo When checking for the tile slope,
1148 * distinguish between "Flat land required" and "land sloped in wrong direction"
1150 CommandCost CmdBuildRoadDepot(DoCommandFlag flags, TileIndex tile, RoadType rt, DiagDirection dir)
1152 if (!ValParamRoadType(rt) || !IsValidDiagDirection(dir)) return CMD_ERROR;
1154 CommandCost cost(EXPENSES_CONSTRUCTION);
1156 Slope tileh = GetTileSlope(tile);
1157 if (tileh != SLOPE_FLAT) {
1158 if (!_settings_game.construction.build_on_slopes || !CanBuildDepotByTileh(dir, tileh)) {
1159 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
1161 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
1164 cost.AddCost(Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile));
1165 if (cost.Failed()) return cost;
1167 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1169 if (!Depot::CanAllocateItem()) return CMD_ERROR;
1171 if (flags & DC_EXEC) {
1172 Depot *dep = new Depot(tile);
1173 dep->build_date = _date;
1175 /* A road depot has two road bits. */
1176 UpdateCompanyRoadInfrastructure(rt, _current_company, ROAD_DEPOT_TRACKBIT_FACTOR);
1178 MakeRoadDepot(tile, _current_company, dep->index, dir, rt);
1179 MarkTileDirtyByTile(tile);
1180 MakeDefaultName(dep);
1182 cost.AddCost(_price[PR_BUILD_DEPOT_ROAD]);
1183 return cost;
1186 static CommandCost RemoveRoadDepot(TileIndex tile, DoCommandFlag flags)
1188 if (_current_company != OWNER_WATER) {
1189 CommandCost ret = CheckTileOwnership(tile);
1190 if (ret.Failed()) return ret;
1193 CommandCost ret = EnsureNoVehicleOnGround(tile);
1194 if (ret.Failed()) return ret;
1196 if (flags & DC_EXEC) {
1197 Company *c = Company::GetIfValid(GetTileOwner(tile));
1198 if (c != nullptr) {
1199 /* A road depot has two road bits. */
1200 RoadType rt = GetRoadTypeRoad(tile);
1201 if (rt == INVALID_ROADTYPE) rt = GetRoadTypeTram(tile);
1202 c->infrastructure.road[rt] -= ROAD_DEPOT_TRACKBIT_FACTOR;
1203 DirtyCompanyInfrastructureWindows(c->index);
1206 delete Depot::GetByTile(tile);
1207 DoClearSquare(tile);
1210 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_ROAD]);
1213 static CommandCost ClearTile_Road(TileIndex tile, DoCommandFlag flags)
1215 switch (GetRoadTileType(tile)) {
1216 case ROAD_TILE_NORMAL: {
1217 RoadBits b = GetAllRoadBits(tile);
1219 /* Clear the road if only one piece is on the tile OR we are not using the DC_AUTO flag */
1220 if ((HasExactlyOneBit(b) && GetRoadBits(tile, RTT_TRAM) == ROAD_NONE) || !(flags & DC_AUTO)) {
1221 CommandCost ret(EXPENSES_CONSTRUCTION);
1222 for (RoadTramType rtt : _roadtramtypes) {
1223 if (!MayHaveRoad(tile) || GetRoadType(tile, rtt) == INVALID_ROADTYPE) continue;
1225 CommandCost tmp_ret = RemoveRoad(tile, flags, GetRoadBits(tile, rtt), rtt, true);
1226 if (tmp_ret.Failed()) return tmp_ret;
1227 ret.AddCost(tmp_ret);
1229 return ret;
1231 return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1234 case ROAD_TILE_CROSSING: {
1235 CommandCost ret(EXPENSES_CONSTRUCTION);
1237 if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_REMOVE_ROAD_FIRST);
1239 /* Must iterate over the roadtypes in a reverse manner because
1240 * tram tracks must be removed before the road bits. */
1241 for (RoadTramType rtt : { RTT_TRAM, RTT_ROAD }) {
1242 if (!MayHaveRoad(tile) || GetRoadType(tile, rtt) == INVALID_ROADTYPE) continue;
1244 CommandCost tmp_ret = RemoveRoad(tile, flags, GetCrossingRoadBits(tile), rtt, false);
1245 if (tmp_ret.Failed()) return tmp_ret;
1246 ret.AddCost(tmp_ret);
1249 if (flags & DC_EXEC) {
1250 Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
1252 return ret;
1255 default:
1256 case ROAD_TILE_DEPOT:
1257 if (flags & DC_AUTO) {
1258 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1260 return RemoveRoadDepot(tile, flags);
1265 struct DrawRoadTileStruct {
1266 uint16 image;
1267 byte subcoord_x;
1268 byte subcoord_y;
1271 #include "table/road_land.h"
1274 * Get the foundationtype of a RoadBits Slope combination
1276 * @param tileh The Slope part
1277 * @param bits The RoadBits part
1278 * @return The resulting Foundation
1280 static Foundation GetRoadFoundation(Slope tileh, RoadBits bits)
1282 /* Flat land and land without a road doesn't require a foundation */
1283 if (tileh == SLOPE_FLAT || bits == ROAD_NONE) return FOUNDATION_NONE;
1285 /* Steep slopes behave the same as slopes with one corner raised. */
1286 if (IsSteepSlope(tileh)) {
1287 tileh = SlopeWithOneCornerRaised(GetHighestSlopeCorner(tileh));
1290 /* Leveled RoadBits on a slope */
1291 if ((_invalid_tileh_slopes_road[0][tileh] & bits) == ROAD_NONE) return FOUNDATION_LEVELED;
1293 /* Straight roads without foundation on a slope */
1294 if (!IsSlopeWithOneCornerRaised(tileh) &&
1295 (_invalid_tileh_slopes_road[1][tileh] & bits) == ROAD_NONE)
1296 return FOUNDATION_NONE;
1298 /* Roads on steep Slopes or on Slopes with one corner raised */
1299 return (bits == ROAD_X ? FOUNDATION_INCLINED_X : FOUNDATION_INCLINED_Y);
1302 const byte _road_sloped_sprites[14] = {
1303 0, 0, 2, 0,
1304 0, 1, 0, 0,
1305 3, 0, 0, 0,
1306 0, 0
1310 * Get the sprite offset within a spritegroup.
1311 * @param slope Slope
1312 * @param bits Roadbits
1313 * @return Offset for the sprite within the spritegroup.
1315 static uint GetRoadSpriteOffset(Slope slope, RoadBits bits)
1317 if (slope != SLOPE_FLAT) {
1318 switch (slope) {
1319 case SLOPE_NE: return 11;
1320 case SLOPE_SE: return 12;
1321 case SLOPE_SW: return 13;
1322 case SLOPE_NW: return 14;
1323 default: NOT_REACHED();
1325 } else {
1326 static const uint offsets[] = {
1327 0, 18, 17, 7,
1328 16, 0, 10, 5,
1329 15, 8, 1, 4,
1330 9, 3, 6, 2
1332 return offsets[bits];
1337 * Should the road be drawn as a unpaved snow/desert road?
1338 * By default, roads are always drawn as unpaved if they are on desert or
1339 * above the snow line, but NewGRFs can override this for desert.
1341 * @param tile The tile the road is on
1342 * @param roadside What sort of road this is
1343 * @return True if snow/desert road sprites should be used.
1345 static bool DrawRoadAsSnowDesert(TileIndex tile, Roadside roadside)
1347 return (IsOnSnow(tile) &&
1348 !(_settings_game.game_creation.landscape == LT_TROPIC && HasGrfMiscBit(GMB_DESERT_PAVED_ROADS) &&
1349 roadside != ROADSIDE_BARREN && roadside != ROADSIDE_GRASS && roadside != ROADSIDE_GRASS_ROAD_WORKS));
1353 * Draws the catenary for the RoadType of the given tile
1354 * @param ti information about the tile (slopes, height etc)
1355 * @param rt road type to draw catenary for
1356 * @param rb the roadbits for the tram
1358 void DrawRoadTypeCatenary(const TileInfo *ti, RoadType rt, RoadBits rb)
1360 /* Don't draw the catenary under a low bridge */
1361 if (IsBridgeAbove(ti->tile) && !IsTransparencySet(TO_CATENARY)) {
1362 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1364 if (height <= GetTileMaxZ(ti->tile) + 1) return;
1367 if (CountBits(rb) > 2) {
1368 /* On junctions we check whether neighbouring tiles also have catenary, and possibly
1369 * do not draw catenary towards those neighbours, which do not have catenary. */
1370 RoadBits rb_new = ROAD_NONE;
1371 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
1372 if (rb & DiagDirToRoadBits(dir)) {
1373 TileIndex neighbour = TileAddByDiagDir(ti->tile, dir);
1374 if (MayHaveRoad(neighbour)) {
1375 RoadType rt_road = GetRoadTypeRoad(neighbour);
1376 RoadType rt_tram = GetRoadTypeTram(neighbour);
1378 if ((rt_road != INVALID_ROADTYPE && HasRoadCatenary(rt_road)) ||
1379 (rt_tram != INVALID_ROADTYPE && HasRoadCatenary(rt_tram))) {
1380 rb_new |= DiagDirToRoadBits(dir);
1385 if (CountBits(rb_new) >= 2) rb = rb_new;
1388 const RoadTypeInfo* rti = GetRoadTypeInfo(rt);
1389 SpriteID front = GetCustomRoadSprite(rti, ti->tile, ROTSG_CATENARY_FRONT);
1390 SpriteID back = GetCustomRoadSprite(rti, ti->tile, ROTSG_CATENARY_BACK);
1392 if (front != 0 || back != 0) {
1393 if (front != 0) front += GetRoadSpriteOffset(ti->tileh, rb);
1394 if (back != 0) back += GetRoadSpriteOffset(ti->tileh, rb);
1395 } else if (ti->tileh != SLOPE_FLAT) {
1396 back = SPR_TRAMWAY_BACK_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1397 front = SPR_TRAMWAY_FRONT_WIRES_SLOPED + _road_sloped_sprites[ti->tileh - 1];
1398 } else {
1399 back = SPR_TRAMWAY_BASE + _road_backpole_sprites_1[rb];
1400 front = SPR_TRAMWAY_BASE + _road_frontwire_sprites_1[rb];
1403 /* Catenary uses 1st company colour to help identify owner.
1404 * For tiles with OWNER_TOWN or OWNER_NONE, recolour CC to grey as a neutral colour. */
1405 Owner owner = GetRoadOwner(ti->tile, GetRoadTramType(rt));
1406 PaletteID pal = (owner == OWNER_NONE || owner == OWNER_TOWN ? GENERAL_SPRITE_COLOUR(COLOUR_GREY) : COMPANY_SPRITE_COLOUR(owner));
1407 int z_wires = (ti->tileh == SLOPE_FLAT ? 0 : TILE_HEIGHT) + BB_HEIGHT_UNDER_BRIDGE;
1408 if (back != 0) {
1409 /* The "back" sprite contains the west, north and east pillars.
1410 * We cut the sprite at 3/8 of the west/east edges to create 3 sprites.
1411 * 3/8 is chosen so that sprites can somewhat graphically extend into the tile. */
1412 static const int INF = 1000; ///< big number compared to sprite size
1413 static const SubSprite west = { -INF, -INF, -12, INF };
1414 static const SubSprite north = { -12, -INF, 12, INF };
1415 static const SubSprite east = { 12, -INF, INF, INF };
1416 AddSortableSpriteToDraw(back, pal, ti->x, ti->y, 16, 1, z_wires, ti->z, IsTransparencySet(TO_CATENARY), 15, 0, GetSlopePixelZInCorner(ti->tileh, CORNER_W), &west);
1417 AddSortableSpriteToDraw(back, pal, ti->x, ti->y, 1, 1, z_wires, ti->z, IsTransparencySet(TO_CATENARY), 0, 0, GetSlopePixelZInCorner(ti->tileh, CORNER_N), &north);
1418 AddSortableSpriteToDraw(back, pal, ti->x, ti->y, 1, 16, z_wires, ti->z, IsTransparencySet(TO_CATENARY), 0, 15, GetSlopePixelZInCorner(ti->tileh, CORNER_E), &east);
1420 if (front != 0) {
1421 /* Draw the "front" sprite (containing south pillar and wires) at a Z height that is both above the vehicles and above the "back" pillars. */
1422 AddSortableSpriteToDraw(front, pal, ti->x, ti->y, 16, 16, z_wires + 1, ti->z, IsTransparencySet(TO_CATENARY), 0, 0, z_wires);
1427 * Draws the catenary for the given tile
1428 * @param ti information about the tile (slopes, height etc)
1430 void DrawRoadCatenary(const TileInfo *ti)
1432 RoadBits road = ROAD_NONE;
1433 RoadBits tram = ROAD_NONE;
1435 if (IsTileType(ti->tile, MP_ROAD)) {
1436 if (IsNormalRoad(ti->tile)) {
1437 road = GetRoadBits(ti->tile, RTT_ROAD);
1438 tram = GetRoadBits(ti->tile, RTT_TRAM);
1439 } else if (IsLevelCrossing(ti->tile)) {
1440 tram = road = (GetCrossingRailAxis(ti->tile) == AXIS_Y ? ROAD_X : ROAD_Y);
1442 } else if (IsTileType(ti->tile, MP_STATION)) {
1443 if (IsRoadStop(ti->tile)) {
1444 if (IsDriveThroughStopTile(ti->tile)) {
1445 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
1446 tram = road = (axis == AXIS_X ? ROAD_X : ROAD_Y);
1447 } else {
1448 tram = road = DiagDirToRoadBits(GetRoadStopDir(ti->tile));
1451 } else {
1452 // No road here, no catenary to draw
1453 return;
1456 RoadType rt = GetRoadTypeRoad(ti->tile);
1457 if (rt != INVALID_ROADTYPE && HasRoadCatenaryDrawn(rt)) {
1458 DrawRoadTypeCatenary(ti, rt, road);
1461 rt = GetRoadTypeTram(ti->tile);
1462 if (rt != INVALID_ROADTYPE && HasRoadCatenaryDrawn(rt)) {
1463 DrawRoadTypeCatenary(ti, rt, tram);
1468 * Draws details on/around the road
1469 * @param img the sprite to draw
1470 * @param ti the tile to draw on
1471 * @param dx the offset from the top of the BB of the tile
1472 * @param dy the offset from the top of the BB of the tile
1473 * @param h the height of the sprite to draw
1474 * @param transparent whether the sprite should be transparent (used for roadside trees)
1476 static void DrawRoadDetail(SpriteID img, const TileInfo *ti, int dx, int dy, int h, bool transparent)
1478 int x = ti->x | dx;
1479 int y = ti->y | dy;
1480 int z = ti->z;
1481 if (ti->tileh != SLOPE_FLAT) z = GetSlopePixelZ(x, y);
1482 AddSortableSpriteToDraw(img, PAL_NONE, x, y, 2, 2, h, z, transparent);
1486 * Draw road underlay and overlay sprites.
1487 * @param ti TileInfo
1488 * @param road_rti Road road type information
1489 * @param tram_rti Tram road type information
1490 * @param road_offset Road sprite offset (based on road bits)
1491 * @param tram_offset Tram sprite offset (based on road bits)
1492 * @param draw_underlay Whether to draw underlays
1494 void DrawRoadOverlays(const TileInfo *ti, PaletteID pal, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, uint road_offset, uint tram_offset, bool draw_underlay)
1496 if (draw_underlay) {
1497 /* Road underlay takes precedence over tram */
1498 if (road_rti != nullptr) {
1499 if (road_rti->UsesOverlay()) {
1500 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_GROUND);
1501 DrawGroundSprite(ground + road_offset, pal);
1503 } else {
1504 if (tram_rti->UsesOverlay()) {
1505 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_GROUND);
1506 DrawGroundSprite(ground + tram_offset, pal);
1507 } else {
1508 DrawGroundSprite(SPR_TRAMWAY_TRAM + tram_offset, pal);
1513 /* Draw road overlay */
1514 if (road_rti != nullptr) {
1515 if (road_rti->UsesOverlay()) {
1516 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_OVERLAY);
1517 if (ground != 0) DrawGroundSprite(ground + road_offset, pal);
1521 /* Draw tram overlay */
1522 if (tram_rti != nullptr) {
1523 if (tram_rti->UsesOverlay()) {
1524 SpriteID ground = GetCustomRoadSprite(tram_rti, ti->tile, ROTSG_OVERLAY);
1525 if (ground != 0) DrawGroundSprite(ground + tram_offset, pal);
1526 } else if (road_rti != nullptr) {
1527 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + tram_offset, pal);
1533 * Get ground sprite to draw for a road tile.
1534 * @param ti TileInof
1535 * @param roadside Road side type
1536 * @param rti Road type info
1537 * @param offset Road sprite offset
1538 * @param[out] pal Palette to draw.
1540 static SpriteID GetRoadGroundSprite(const TileInfo *ti, Roadside roadside, const RoadTypeInfo *rti, uint offset, PaletteID *pal)
1542 /* Draw bare ground sprite if no road or road uses overlay system. */
1543 if (rti == nullptr || rti->UsesOverlay()) {
1544 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1545 return SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh);
1548 switch (roadside) {
1549 case ROADSIDE_BARREN: *pal = PALETTE_TO_BARE_LAND;
1550 return SPR_FLAT_GRASS_TILE + SlopeToSpriteOffset(ti->tileh);
1551 case ROADSIDE_GRASS:
1552 case ROADSIDE_GRASS_ROAD_WORKS: return SPR_FLAT_GRASS_TILE + SlopeToSpriteOffset(ti->tileh);
1553 default: break; // Paved
1557 /* Draw original road base sprite */
1558 SpriteID image = SPR_ROAD_Y + offset;
1559 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1560 image += 19;
1561 } else {
1562 switch (roadside) {
1563 case ROADSIDE_BARREN: *pal = PALETTE_TO_BARE_LAND; break;
1564 case ROADSIDE_GRASS: break;
1565 case ROADSIDE_GRASS_ROAD_WORKS: break;
1566 default: image -= 19; break; // Paved
1570 return image;
1574 * Draw ground sprite and road pieces
1575 * @param ti TileInfo
1577 static void DrawRoadBits(TileInfo *ti)
1579 RoadBits road = GetRoadBits(ti->tile, RTT_ROAD);
1580 RoadBits tram = GetRoadBits(ti->tile, RTT_TRAM);
1582 RoadType road_rt = GetRoadTypeRoad(ti->tile);
1583 RoadType tram_rt = GetRoadTypeTram(ti->tile);
1584 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
1585 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
1587 if (ti->tileh != SLOPE_FLAT) {
1588 DrawFoundation(ti, GetRoadFoundation(ti->tileh, road | tram));
1589 /* DrawFoundation() modifies ti. */
1592 /* Determine sprite offsets */
1593 uint road_offset = GetRoadSpriteOffset(ti->tileh, road);
1594 uint tram_offset = GetRoadSpriteOffset(ti->tileh, tram);
1596 /* Draw baseset underlay */
1597 Roadside roadside = GetRoadside(ti->tile);
1599 PaletteID pal = PAL_NONE;
1600 SpriteID image = GetRoadGroundSprite(ti, roadside, road_rti, road == ROAD_NONE ? tram_offset : road_offset, &pal);
1601 DrawGroundSprite(image, pal);
1603 DrawRoadOverlays(ti, pal, road_rti, tram_rti, road_offset, tram_offset);
1605 /* Draw one way */
1606 if (road_rti != nullptr) {
1607 DisallowedRoadDirections drd = GetDisallowedRoadDirections(ti->tile);
1608 if (drd != DRD_NONE) {
1609 DrawGroundSpriteAt(SPR_ONEWAY_BASE + drd - 1 + ((road == ROAD_X) ? 0 : 3), PAL_NONE, 8, 8, GetPartialPixelZ(8, 8, ti->tileh));
1613 if (HasRoadWorks(ti->tile)) {
1614 /* Road works */
1615 DrawGroundSprite((road | tram) & ROAD_X ? SPR_EXCAVATION_X : SPR_EXCAVATION_Y, PAL_NONE);
1616 return;
1619 /* Draw road, tram catenary */
1620 DrawRoadCatenary(ti);
1622 /* Return if full detail is disabled, or we are zoomed fully out. */
1623 if (!HasBit(_display_opt, DO_FULL_DETAIL) || _cur_dpi->zoom > ZOOM_LVL_DETAIL) return;
1625 /* Do not draw details (street lights, trees) under low bridge */
1626 if (IsBridgeAbove(ti->tile) && (roadside == ROADSIDE_TREES || roadside == ROADSIDE_STREET_LIGHTS)) {
1627 int height = GetBridgeHeight(GetNorthernBridgeEnd(ti->tile));
1628 int minz = GetTileMaxZ(ti->tile) + 2;
1630 if (roadside == ROADSIDE_TREES) minz++;
1632 if (height < minz) return;
1635 /* If there are no road bits, return, as there is nothing left to do */
1636 if (HasAtMostOneBit(road)) return;
1638 if (roadside == ROADSIDE_TREES && IsInvisibilitySet(TO_TREES)) return;
1639 bool is_transparent = roadside == ROADSIDE_TREES && IsTransparencySet(TO_TREES);
1641 /* Draw extra details. */
1642 for (const DrawRoadTileStruct *drts = _road_display_table[roadside][road | tram]; drts->image != 0; drts++) {
1643 DrawRoadDetail(drts->image, ti, drts->subcoord_x, drts->subcoord_y, 0x10, is_transparent);
1647 /** Tile callback function for rendering a road tile to the screen */
1648 static void DrawTile_Road(TileInfo *ti)
1650 switch (GetRoadTileType(ti->tile)) {
1651 case ROAD_TILE_NORMAL:
1652 DrawRoadBits(ti);
1653 break;
1655 case ROAD_TILE_CROSSING: {
1656 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1658 Axis axis = GetCrossingRailAxis(ti->tile);
1660 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
1662 RoadType road_rt = GetRoadTypeRoad(ti->tile);
1663 RoadType tram_rt = GetRoadTypeTram(ti->tile);
1664 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
1665 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
1667 PaletteID pal = PAL_NONE;
1669 /* Draw base ground */
1670 if (rti->UsesOverlay()) {
1671 SpriteID image = SPR_ROAD_Y + axis;
1673 Roadside roadside = GetRoadside(ti->tile);
1674 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1675 image += 19;
1676 } else {
1677 switch (roadside) {
1678 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1679 case ROADSIDE_GRASS: break;
1680 default: image -= 19; break; // Paved
1684 DrawGroundSprite(image, pal);
1685 } else {
1686 SpriteID image = rti->base_sprites.crossing + axis;
1687 if (IsCrossingBarred(ti->tile)) image += 2;
1689 Roadside roadside = GetRoadside(ti->tile);
1690 if (DrawRoadAsSnowDesert(ti->tile, roadside)) {
1691 image += 8;
1692 } else {
1693 switch (roadside) {
1694 case ROADSIDE_BARREN: pal = PALETTE_TO_BARE_LAND; break;
1695 case ROADSIDE_GRASS: break;
1696 default: image += 4; break; // Paved
1700 DrawGroundSprite(image, pal);
1703 DrawRoadOverlays(ti, pal, road_rti, tram_rti, axis, axis);
1705 /* Draw rail/PBS overlay */
1706 bool draw_pbs = _game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasCrossingReservation(ti->tile);
1707 if (rti->UsesOverlay()) {
1708 PaletteID pal = draw_pbs ? PALETTE_CRASH : PAL_NONE;
1709 SpriteID rail = GetCustomRailSprite(rti, ti->tile, RTSG_CROSSING) + axis;
1710 DrawGroundSprite(rail, pal);
1712 const Axis road_axis = GetCrossingRoadAxis(ti->tile);
1713 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1714 const DiagDirection dir2 = ReverseDiagDir(dir1);
1715 uint adjacent_diagdirs = 0;
1716 for (DiagDirection dir : { dir1, dir2 }) {
1717 const TileIndex t = TileAddByDiagDir(ti->tile, dir);
1718 if (t < MapSize() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1719 SetBit(adjacent_diagdirs, dir);
1723 switch (adjacent_diagdirs) {
1724 case 0:
1725 DrawRailTileSeq(ti, &_crossing_layout, TO_CATENARY, rail, 0, PAL_NONE);
1726 break;
1728 case (1 << DIAGDIR_NE):
1729 DrawRailTileSeq(ti, &_crossing_layout_SW, TO_CATENARY, rail, 0, PAL_NONE);
1730 break;
1732 case (1 << DIAGDIR_SE):
1733 DrawRailTileSeq(ti, &_crossing_layout_NW, TO_CATENARY, rail, 0, PAL_NONE);
1734 break;
1736 case (1 << DIAGDIR_SW):
1737 DrawRailTileSeq(ti, &_crossing_layout_NE, TO_CATENARY, rail, 0, PAL_NONE);
1738 break;
1740 case (1 << DIAGDIR_NW):
1741 DrawRailTileSeq(ti, &_crossing_layout_SE, TO_CATENARY, rail, 0, PAL_NONE);
1742 break;
1744 default:
1745 /* Show no sprites */
1746 break;
1748 } else if (draw_pbs || tram_rti != nullptr || road_rti->UsesOverlay()) {
1749 /* Add another rail overlay, unless there is only the base road sprite. */
1750 PaletteID pal = draw_pbs ? PALETTE_CRASH : PAL_NONE;
1751 SpriteID rail = GetCrossingRoadAxis(ti->tile) == AXIS_Y ? GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_x : GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.single_y;
1752 DrawGroundSprite(rail, pal);
1755 /* Draw road, tram catenary */
1756 DrawRoadCatenary(ti);
1758 /* Draw rail catenary */
1759 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
1761 break;
1764 default:
1765 case ROAD_TILE_DEPOT: {
1766 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
1768 PaletteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
1770 RoadType road_rt = GetRoadTypeRoad(ti->tile);
1771 RoadType tram_rt = GetRoadTypeTram(ti->tile);
1772 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt == INVALID_ROADTYPE ? tram_rt : road_rt);
1774 int relocation = GetCustomRoadSprite(rti, ti->tile, ROTSG_DEPOT);
1775 bool default_gfx = relocation == 0;
1776 if (default_gfx) {
1777 if (HasBit(rti->flags, ROTF_CATENARY)) {
1778 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK && road_rt == INVALID_ROADTYPE && !rti->UsesOverlay()) {
1779 /* Sprites with track only work for default tram */
1780 relocation = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_ROAD_DEPOT;
1781 default_gfx = false;
1782 } else {
1783 /* Sprites without track are always better, if provided */
1784 relocation = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_ROAD_DEPOT;
1787 } else {
1788 relocation -= SPR_ROAD_DEPOT;
1791 DiagDirection dir = GetRoadDepotDirection(ti->tile);
1792 const DrawTileSprites *dts = &_road_depot[dir];
1793 DrawGroundSprite(dts->ground.sprite, PAL_NONE);
1795 if (default_gfx) {
1796 uint offset = GetRoadSpriteOffset(SLOPE_FLAT, DiagDirToRoadBits(dir));
1797 if (rti->UsesOverlay()) {
1798 SpriteID ground = GetCustomRoadSprite(rti, ti->tile, ROTSG_OVERLAY);
1799 if (ground != 0) DrawGroundSprite(ground + offset, PAL_NONE);
1800 } else if (road_rt == INVALID_ROADTYPE) {
1801 DrawGroundSprite(SPR_TRAMWAY_OVERLAY + offset, PAL_NONE);
1805 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, palette);
1806 break;
1809 DrawBridgeMiddle(ti);
1813 * Draw the road depot sprite.
1814 * @param x The x offset to draw at.
1815 * @param y The y offset to draw at.
1816 * @param dir The direction the depot must be facing.
1817 * @param rt The road type of the depot to draw.
1819 void DrawRoadDepotSprite(int x, int y, DiagDirection dir, RoadType rt)
1821 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
1823 const RoadTypeInfo* rti = GetRoadTypeInfo(rt);
1824 int relocation = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_DEPOT);
1825 bool default_gfx = relocation == 0;
1826 if (default_gfx) {
1827 if (HasBit(rti->flags, ROTF_CATENARY)) {
1828 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK && RoadTypeIsTram(rt) && !rti->UsesOverlay()) {
1829 /* Sprites with track only work for default tram */
1830 relocation = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_ROAD_DEPOT;
1831 default_gfx = false;
1832 } else {
1833 /* Sprites without track are always better, if provided */
1834 relocation = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_ROAD_DEPOT;
1837 } else {
1838 relocation -= SPR_ROAD_DEPOT;
1841 const DrawTileSprites *dts = &_road_depot[dir];
1842 DrawSprite(dts->ground.sprite, PAL_NONE, x, y);
1844 if (default_gfx) {
1845 uint offset = GetRoadSpriteOffset(SLOPE_FLAT, DiagDirToRoadBits(dir));
1846 if (rti->UsesOverlay()) {
1847 SpriteID ground = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_OVERLAY);
1848 if (ground != 0) DrawSprite(ground + offset, PAL_NONE, x, y);
1849 } else if (RoadTypeIsTram(rt)) {
1850 DrawSprite(SPR_TRAMWAY_OVERLAY + offset, PAL_NONE, x, y);
1854 DrawRailTileSeqInGUI(x, y, dts, relocation, 0, palette);
1858 * Updates cached nearest town for all road tiles
1859 * @param invalidate are we just invalidating cached data?
1860 * @pre invalidate == true implies _generating_world == true
1862 void UpdateNearestTownForRoadTiles(bool invalidate)
1864 assert(!invalidate || _generating_world);
1866 for (TileIndex t = 0; t < MapSize(); t++) {
1867 if (IsTileType(t, MP_ROAD) && !IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1868 TownID tid = INVALID_TOWN;
1869 if (!invalidate) {
1870 const Town *town = CalcClosestTownFromTile(t);
1871 if (town != nullptr) tid = town->index;
1873 SetTownIndex(t, tid);
1878 static int GetSlopePixelZ_Road(TileIndex tile, uint x, uint y)
1881 if (IsNormalRoad(tile)) {
1882 int z;
1883 Slope tileh = GetTilePixelSlope(tile, &z);
1884 if (tileh == SLOPE_FLAT) return z;
1886 Foundation f = GetRoadFoundation(tileh, GetAllRoadBits(tile));
1887 z += ApplyPixelFoundationToSlope(f, &tileh);
1888 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
1889 } else {
1890 return GetTileMaxPixelZ(tile);
1894 static Foundation GetFoundation_Road(TileIndex tile, Slope tileh)
1896 if (IsNormalRoad(tile)) {
1897 return GetRoadFoundation(tileh, GetAllRoadBits(tile));
1898 } else {
1899 return FlatteningFoundation(tileh);
1903 static const Roadside _town_road_types[][2] = {
1904 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1905 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1906 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1907 { ROADSIDE_TREES, ROADSIDE_TREES },
1908 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1911 static const Roadside _town_road_types_2[][2] = {
1912 { ROADSIDE_GRASS, ROADSIDE_GRASS },
1913 { ROADSIDE_PAVED, ROADSIDE_PAVED },
1914 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1915 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED },
1916 { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
1920 static void TileLoop_Road(TileIndex tile)
1922 switch (_settings_game.game_creation.landscape) {
1923 case LT_ARCTIC:
1924 if (IsOnSnow(tile) != (GetTileZ(tile) > GetSnowLine())) {
1925 ToggleSnow(tile);
1926 MarkTileDirtyByTile(tile);
1928 break;
1930 case LT_TROPIC:
1931 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsOnDesert(tile)) {
1932 ToggleDesert(tile);
1933 MarkTileDirtyByTile(tile);
1935 break;
1938 if (IsRoadDepot(tile)) return;
1940 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
1941 if (!HasRoadWorks(tile)) {
1942 HouseZonesBits grp = HZB_TOWN_EDGE;
1944 if (t != nullptr) {
1945 grp = GetTownRadiusGroup(t, tile);
1947 /* Show an animation to indicate road work */
1948 if (t->road_build_months != 0 &&
1949 (DistanceManhattan(t->xy, tile) < 8 || grp != HZB_TOWN_EDGE) &&
1950 IsNormalRoad(tile) && !HasAtMostOneBit(GetAllRoadBits(tile))) {
1951 if (GetFoundationSlope(tile) == SLOPE_FLAT && EnsureNoVehicleOnGround(tile).Succeeded() && Chance16(1, 40)) {
1952 StartRoadWorks(tile);
1954 if (_settings_client.sound.ambient) SndPlayTileFx(SND_21_ROAD_WORKS, tile);
1955 CreateEffectVehicleAbove(
1956 TileX(tile) * TILE_SIZE + 7,
1957 TileY(tile) * TILE_SIZE + 7,
1959 EV_BULLDOZER);
1960 MarkTileDirtyByTile(tile);
1961 return;
1967 /* Adjust road ground type depending on 'grp' (grp is the distance to the center) */
1968 const Roadside *new_rs = (_settings_game.game_creation.landscape == LT_TOYLAND) ? _town_road_types_2[grp] : _town_road_types[grp];
1969 Roadside cur_rs = GetRoadside(tile);
1971 /* We have our desired type, do nothing */
1972 if (cur_rs == new_rs[0]) return;
1974 /* We have the pre-type of the desired type, switch to the desired type */
1975 if (cur_rs == new_rs[1]) {
1976 cur_rs = new_rs[0];
1977 /* We have barren land, install the pre-type */
1978 } else if (cur_rs == ROADSIDE_BARREN) {
1979 cur_rs = new_rs[1];
1980 /* We're totally off limits, remove any installation and make barren land */
1981 } else {
1982 cur_rs = ROADSIDE_BARREN;
1984 SetRoadside(tile, cur_rs);
1985 MarkTileDirtyByTile(tile);
1987 } else if (IncreaseRoadWorksCounter(tile)) {
1988 TerminateRoadWorks(tile);
1990 if (_settings_game.economy.mod_road_rebuild) {
1991 /* Generate a nicer town surface */
1992 const RoadBits old_rb = GetAnyRoadBits(tile, RTT_ROAD);
1993 const RoadBits new_rb = CleanUpRoadBits(tile, old_rb);
1995 if (old_rb != new_rb) {
1996 RemoveRoad(tile, DC_EXEC | DC_AUTO | DC_NO_WATER, (old_rb ^ new_rb), RTT_ROAD, true);
1998 /* If new_rb is 0, there are now no road pieces left and the tile is no longer a road tile */
1999 if (new_rb == 0) {
2000 MarkTileDirtyByTile(tile);
2001 return;
2006 /* Possibly change road type */
2007 if (GetRoadOwner(tile, RTT_ROAD) == OWNER_TOWN) {
2008 RoadType rt = GetTownRoadType(t);
2009 if (rt != GetRoadTypeRoad(tile)) {
2010 SetRoadType(tile, RTT_ROAD, rt);
2014 MarkTileDirtyByTile(tile);
2018 static bool ClickTile_Road(TileIndex tile)
2020 if (!IsRoadDepot(tile)) return false;
2022 ShowDepotWindow(tile, VEH_ROAD);
2023 return true;
2026 /* Converts RoadBits to TrackBits */
2027 static const TrackBits _road_trackbits[16] = {
2028 TRACK_BIT_NONE, // ROAD_NONE
2029 TRACK_BIT_NONE, // ROAD_NW
2030 TRACK_BIT_NONE, // ROAD_SW
2031 TRACK_BIT_LEFT, // ROAD_W
2032 TRACK_BIT_NONE, // ROAD_SE
2033 TRACK_BIT_Y, // ROAD_Y
2034 TRACK_BIT_LOWER, // ROAD_S
2035 TRACK_BIT_LEFT | TRACK_BIT_LOWER | TRACK_BIT_Y, // ROAD_Y | ROAD_SW
2036 TRACK_BIT_NONE, // ROAD_NE
2037 TRACK_BIT_UPPER, // ROAD_N
2038 TRACK_BIT_X, // ROAD_X
2039 TRACK_BIT_LEFT | TRACK_BIT_UPPER | TRACK_BIT_X, // ROAD_X | ROAD_NW
2040 TRACK_BIT_RIGHT, // ROAD_E
2041 TRACK_BIT_RIGHT | TRACK_BIT_UPPER | TRACK_BIT_Y, // ROAD_Y | ROAD_NE
2042 TRACK_BIT_RIGHT | TRACK_BIT_LOWER | TRACK_BIT_X, // ROAD_X | ROAD_SE
2043 TRACK_BIT_ALL, // ROAD_ALL
2046 static TrackStatus GetTileTrackStatus_Road(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
2048 TrackdirBits trackdirbits = TRACKDIR_BIT_NONE;
2049 TrackdirBits red_signals = TRACKDIR_BIT_NONE; // crossing barred
2050 switch (mode) {
2051 case TRANSPORT_RAIL:
2052 if (IsLevelCrossing(tile)) trackdirbits = TrackBitsToTrackdirBits(GetCrossingRailBits(tile));
2053 break;
2055 case TRANSPORT_ROAD: {
2056 RoadTramType rtt = (RoadTramType)sub_mode;
2057 if (!HasTileRoadType(tile, rtt)) break;
2058 switch (GetRoadTileType(tile)) {
2059 case ROAD_TILE_NORMAL: {
2060 const uint drd_to_multiplier[DRD_END] = { 0x101, 0x100, 0x1, 0x0 };
2061 RoadBits bits = GetRoadBits(tile, rtt);
2063 /* no roadbit at this side of tile, return 0 */
2064 if (side != INVALID_DIAGDIR && (DiagDirToRoadBits(side) & bits) == 0) break;
2066 uint multiplier = drd_to_multiplier[(rtt == RTT_TRAM) ? DRD_NONE : GetDisallowedRoadDirections(tile)];
2067 if (!HasRoadWorks(tile)) trackdirbits = (TrackdirBits)(_road_trackbits[bits] * multiplier);
2068 break;
2071 case ROAD_TILE_CROSSING: {
2072 Axis axis = GetCrossingRoadAxis(tile);
2074 if (side != INVALID_DIAGDIR && axis != DiagDirToAxis(side)) break;
2076 trackdirbits = TrackBitsToTrackdirBits(AxisToTrackBits(axis));
2077 if (IsCrossingBarred(tile)) {
2078 red_signals = trackdirbits;
2079 auto mask_red_signal_bits_if_crossing_barred = [&](TileIndex t, TrackdirBits mask) {
2080 if (IsLevelCrossingTile(t) && IsCrossingBarred(t)) red_signals &= mask;
2082 /* Check for blocked adjacent crossing to south, keep only southbound red signal trackdirs, allow northbound traffic */
2083 mask_red_signal_bits_if_crossing_barred(TileAddByDiagDir(tile, AxisToDiagDir(axis)), TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_SE);
2084 /* Check for blocked adjacent crossing to north, keep only northbound red signal trackdirs, allow southbound traffic */
2085 mask_red_signal_bits_if_crossing_barred(TileAddByDiagDir(tile, ReverseDiagDir(AxisToDiagDir(axis))), TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_NW);
2087 break;
2090 default:
2091 case ROAD_TILE_DEPOT: {
2092 DiagDirection dir = GetRoadDepotDirection(tile);
2094 if (side != INVALID_DIAGDIR && side != dir) break;
2096 trackdirbits = TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir));
2097 break;
2100 break;
2103 default: break;
2105 return CombineTrackStatus(trackdirbits, red_signals);
2108 static const StringID _road_tile_strings[] = {
2109 STR_LAI_ROAD_DESCRIPTION_ROAD,
2110 STR_LAI_ROAD_DESCRIPTION_ROAD,
2111 STR_LAI_ROAD_DESCRIPTION_ROAD,
2112 STR_LAI_ROAD_DESCRIPTION_ROAD_WITH_STREETLIGHTS,
2113 STR_LAI_ROAD_DESCRIPTION_ROAD,
2114 STR_LAI_ROAD_DESCRIPTION_TREE_LINED_ROAD,
2115 STR_LAI_ROAD_DESCRIPTION_ROAD,
2116 STR_LAI_ROAD_DESCRIPTION_ROAD,
2119 static void GetTileDesc_Road(TileIndex tile, TileDesc *td)
2121 Owner rail_owner = INVALID_OWNER;
2122 Owner road_owner = INVALID_OWNER;
2123 Owner tram_owner = INVALID_OWNER;
2125 RoadType road_rt = GetRoadTypeRoad(tile);
2126 RoadType tram_rt = GetRoadTypeTram(tile);
2127 if (road_rt != INVALID_ROADTYPE) {
2128 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
2129 td->roadtype = rti->strings.name;
2130 td->road_speed = rti->max_speed / 2;
2131 road_owner = GetRoadOwner(tile, RTT_ROAD);
2133 if (tram_rt != INVALID_ROADTYPE) {
2134 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
2135 td->tramtype = rti->strings.name;
2136 td->tram_speed = rti->max_speed / 2;
2137 tram_owner = GetRoadOwner(tile, RTT_TRAM);
2140 switch (GetRoadTileType(tile)) {
2141 case ROAD_TILE_CROSSING: {
2142 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_RAIL_LEVEL_CROSSING;
2143 rail_owner = GetTileOwner(tile);
2145 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2146 td->railtype = rti->strings.name;
2147 td->rail_speed = rti->max_speed;
2149 break;
2152 case ROAD_TILE_DEPOT:
2153 td->str = STR_LAI_ROAD_DESCRIPTION_ROAD_VEHICLE_DEPOT;
2154 td->build_date = Depot::GetByTile(tile)->build_date;
2155 break;
2157 default: {
2158 td->str = (road_rt != INVALID_ROADTYPE ? _road_tile_strings[GetRoadside(tile)] : STR_LAI_ROAD_DESCRIPTION_TRAMWAY);
2159 break;
2163 /* Now we have to discover, if the tile has only one owner or many:
2164 * - Find a first_owner of the tile. (Currently road or tram must be present, but this will break when the third type becomes available)
2165 * - Compare the found owner with the other owners, and test if they differ.
2166 * Note: If road exists it will be the first_owner.
2168 Owner first_owner = (road_owner == INVALID_OWNER ? tram_owner : road_owner);
2169 bool mixed_owners = (tram_owner != INVALID_OWNER && tram_owner != first_owner) || (rail_owner != INVALID_OWNER && rail_owner != first_owner);
2171 if (mixed_owners) {
2172 /* Multiple owners */
2173 td->owner_type[0] = (rail_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_RAIL_OWNER);
2174 td->owner[0] = rail_owner;
2175 td->owner_type[1] = (road_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_ROAD_OWNER);
2176 td->owner[1] = road_owner;
2177 td->owner_type[2] = (tram_owner == INVALID_OWNER ? STR_NULL : STR_LAND_AREA_INFORMATION_TRAM_OWNER);
2178 td->owner[2] = tram_owner;
2179 } else {
2180 /* One to rule them all */
2181 td->owner[0] = first_owner;
2186 * Given the direction the road depot is pointing, this is the direction the
2187 * vehicle should be travelling in in order to enter the depot.
2189 static const byte _roadveh_enter_depot_dir[4] = {
2190 TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
2193 static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
2195 switch (GetRoadTileType(tile)) {
2196 case ROAD_TILE_DEPOT: {
2197 if (v->type != VEH_ROAD) break;
2199 RoadVehicle *rv = RoadVehicle::From(v);
2200 if (rv->frame == RVC_DEPOT_STOP_FRAME &&
2201 _roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
2202 rv->state = RVSB_IN_DEPOT;
2203 rv->vehstatus |= VS_HIDDEN;
2204 rv->direction = ReverseDir(rv->direction);
2205 if (rv->Next() == nullptr) VehicleEnterDepot(rv->First());
2206 rv->tile = tile;
2208 InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
2209 return VETSB_ENTERED_WORMHOLE;
2211 break;
2214 default: break;
2216 return VETSB_CONTINUE;
2220 static void ChangeTileOwner_Road(TileIndex tile, Owner old_owner, Owner new_owner)
2222 if (IsRoadDepot(tile)) {
2223 if (GetTileOwner(tile) == old_owner) {
2224 if (new_owner == INVALID_OWNER) {
2225 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
2226 } else {
2227 /* A road depot has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
2228 RoadType rt = GetRoadTypeRoad(tile);
2229 if (rt == INVALID_ROADTYPE) rt = GetRoadTypeTram(tile);
2230 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
2231 Company::Get(new_owner)->infrastructure.road[rt] += 2;
2233 SetTileOwner(tile, new_owner);
2234 for (RoadTramType rtt : _roadtramtypes) {
2235 if (GetRoadOwner(tile, rtt) == old_owner) {
2236 SetRoadOwner(tile, rtt, new_owner);
2241 return;
2244 for (RoadTramType rtt : _roadtramtypes) {
2245 /* Update all roadtypes, no matter if they are present */
2246 if (GetRoadOwner(tile, rtt) == old_owner) {
2247 RoadType rt = GetRoadType(tile, rtt);
2248 if (rt != INVALID_ROADTYPE) {
2249 /* A level crossing has two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
2250 uint num_bits = IsLevelCrossing(tile) ? 2 : CountBits(GetRoadBits(tile, rtt));
2251 Company::Get(old_owner)->infrastructure.road[rt] -= num_bits;
2252 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += num_bits;
2255 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
2259 if (IsLevelCrossing(tile)) {
2260 if (GetTileOwner(tile) == old_owner) {
2261 if (new_owner == INVALID_OWNER) {
2262 Command<CMD_REMOVE_SINGLE_RAIL>::Do(DC_EXEC | DC_BANKRUPT, tile, GetCrossingRailTrack(tile));
2263 } else {
2264 /* Update infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2265 Company::Get(old_owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
2266 Company::Get(new_owner)->infrastructure.rail[GetRailType(tile)] += LEVELCROSSING_TRACKBIT_FACTOR;
2268 SetTileOwner(tile, new_owner);
2274 static CommandCost TerraformTile_Road(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2276 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
2277 switch (GetRoadTileType(tile)) {
2278 case ROAD_TILE_CROSSING:
2279 if (!IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) && HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2280 break;
2282 case ROAD_TILE_DEPOT:
2283 if (AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRoadDepotDirection(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2284 break;
2286 case ROAD_TILE_NORMAL: {
2287 RoadBits bits = GetAllRoadBits(tile);
2288 RoadBits bits_copy = bits;
2289 /* Check if the slope-road_bits combination is valid at all, i.e. it is safe to call GetRoadFoundation(). */
2290 if (CheckRoadSlope(tileh_new, &bits_copy, ROAD_NONE, ROAD_NONE).Succeeded()) {
2291 /* CheckRoadSlope() sometimes changes the road_bits, if it does not agree with them. */
2292 if (bits == bits_copy) {
2293 int z_old;
2294 Slope tileh_old = GetTileSlope(tile, &z_old);
2296 /* Get the slope on top of the foundation */
2297 z_old += ApplyFoundationToSlope(GetRoadFoundation(tileh_old, bits), &tileh_old);
2298 z_new += ApplyFoundationToSlope(GetRoadFoundation(tileh_new, bits), &tileh_new);
2300 /* The surface slope must not be changed */
2301 if ((z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2304 break;
2307 default: NOT_REACHED();
2311 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2314 /** Update power of road vehicle under which is the roadtype being converted */
2315 static Vehicle *UpdateRoadVehPowerProc(Vehicle *v, void *data)
2317 if (v->type != VEH_ROAD) return nullptr;
2319 RoadVehicleList *affected_rvs = static_cast<RoadVehicleList*>(data);
2320 include(*affected_rvs, RoadVehicle::From(v)->First());
2322 return nullptr;
2326 * Checks the tile and returns whether the current player is allowed to convert the roadtype to another roadtype without taking ownership
2327 * @param owner the tile owner.
2328 * @param rtt Road/tram type.
2329 * @return whether the road is convertible
2331 static bool CanConvertUnownedRoadType(Owner owner, RoadTramType rtt)
2333 return (owner == OWNER_NONE || (owner == OWNER_TOWN && rtt == RTT_ROAD));
2337 * Convert the ownership of the RoadType of the tile if applicable
2338 * @param tile the tile of which convert ownership
2339 * @param num_pieces the count of the roadbits to assign to the new owner
2340 * @param owner the current owner of the RoadType
2341 * @param from_type the old road type
2342 * @param to_type the new road type
2344 static void ConvertRoadTypeOwner(TileIndex tile, uint num_pieces, Owner owner, RoadType from_type, RoadType to_type)
2346 // Scenario editor, maybe? Don't touch the owners when converting roadtypes...
2347 if (_current_company >= MAX_COMPANIES) return;
2349 // We can't get a company from invalid owners but we can get ownership of roads without an owner
2350 if (owner >= MAX_COMPANIES && owner != OWNER_NONE) return;
2352 Company *c;
2354 switch (owner) {
2355 case OWNER_NONE:
2356 SetRoadOwner(tile, GetRoadTramType(to_type), (Owner)_current_company);
2357 UpdateCompanyRoadInfrastructure(to_type, _current_company, num_pieces);
2358 break;
2360 default:
2361 c = Company::Get(owner);
2362 c->infrastructure.road[from_type] -= num_pieces;
2363 c->infrastructure.road[to_type] += num_pieces;
2364 DirtyCompanyInfrastructureWindows(c->index);
2365 break;
2370 * Convert one road subtype to another.
2371 * Not meant to convert from road to tram.
2373 * @param flags operation to perform
2374 * @param tile end tile of road conversion drag
2375 * @param area_start start tile of drag
2376 * @param to_type new roadtype to convert to.
2377 * @return the cost of this operation or an error
2379 CommandCost CmdConvertRoad(DoCommandFlag flags, TileIndex tile, TileIndex area_start, RoadType to_type)
2381 TileIndex area_end = tile;
2383 if (!ValParamRoadType(to_type)) return CMD_ERROR;
2384 if (area_start >= MapSize()) return CMD_ERROR;
2386 RoadVehicleList affected_rvs;
2387 RoadTramType rtt = GetRoadTramType(to_type);
2389 CommandCost cost(EXPENSES_CONSTRUCTION);
2390 CommandCost error = CommandCost((rtt == RTT_TRAM) ? STR_ERROR_NO_SUITABLE_TRAMWAY : STR_ERROR_NO_SUITABLE_ROAD); // by default, there is no road to convert.
2391 bool found_convertible_road = false; // whether we actually did convert any road/tram (see bug #7633)
2393 TileIterator *iter = new OrthogonalTileIterator(area_start, area_end);
2394 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
2395 /* Is road present on tile? */
2396 if (!MayHaveRoad(tile)) continue;
2398 /* Converting to the same subtype? */
2399 RoadType from_type = GetRoadType(tile, rtt);
2400 if (from_type == INVALID_ROADTYPE || from_type == to_type) continue;
2402 /* Check if there is any infrastructure on tile */
2403 TileType tt = GetTileType(tile);
2404 switch (tt) {
2405 case MP_STATION:
2406 if (!IsRoadStop(tile)) continue;
2407 break;
2408 case MP_ROAD:
2409 if (IsLevelCrossing(tile) && RoadNoLevelCrossing(to_type)) {
2410 error.MakeError(STR_ERROR_CROSSING_DISALLOWED_ROAD);
2411 continue;
2413 break;
2414 case MP_TUNNELBRIDGE:
2415 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_ROAD) continue;
2416 break;
2417 default: continue;
2420 /* Trying to convert other's road */
2421 Owner owner = GetRoadOwner(tile, rtt);
2422 if (!CanConvertUnownedRoadType(owner, rtt)) {
2423 CommandCost ret = CheckOwnership(owner, tile);
2424 if (ret.Failed()) {
2425 error = ret;
2426 continue;
2430 /* Base the ability to replace town roads and bridges on the town's
2431 * acceptance of destructive actions. */
2432 if (owner == OWNER_TOWN) {
2433 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
2434 CommandCost ret = CheckforTownRating(DC_NONE, t, tt == MP_TUNNELBRIDGE ? TUNNELBRIDGE_REMOVE : ROAD_REMOVE);
2435 if (ret.Failed()) {
2436 error = ret;
2437 continue;
2441 /* Vehicle on the tile when not converting normal <-> powered
2442 * Tunnels and bridges have special check later */
2443 if (tt != MP_TUNNELBRIDGE) {
2444 if (!HasPowerOnRoad(from_type, to_type)) {
2445 CommandCost ret = EnsureNoVehicleOnGround(tile);
2446 if (ret.Failed()) {
2447 error = ret;
2448 continue;
2451 if (rtt == RTT_ROAD && owner == OWNER_TOWN) {
2452 error.MakeError(STR_ERROR_OWNED_BY);
2453 GetNameOfOwner(OWNER_TOWN, tile);
2454 continue;
2458 uint num_pieces = CountBits(GetAnyRoadBits(tile, rtt));
2459 if (tt == MP_STATION && IsStandardRoadStopTile(tile)) {
2460 num_pieces *= ROAD_STOP_TRACKBIT_FACTOR;
2461 } else if (tt == MP_ROAD && IsRoadDepot(tile)) {
2462 num_pieces *= ROAD_DEPOT_TRACKBIT_FACTOR;
2465 found_convertible_road = true;
2466 cost.AddCost(num_pieces * RoadConvertCost(from_type, to_type));
2468 if (flags & DC_EXEC) { // we can safely convert, too
2469 /* Call ConvertRoadTypeOwner() to update the company infrastructure counters. */
2470 if (owner == _current_company) {
2471 ConvertRoadTypeOwner(tile, num_pieces, owner, from_type, to_type);
2474 /* Perform the conversion */
2475 SetRoadType(tile, rtt, to_type);
2476 MarkTileDirtyByTile(tile);
2478 /* update power of train on this tile */
2479 FindVehicleOnPos(tile, &affected_rvs, &UpdateRoadVehPowerProc);
2481 if (IsRoadDepotTile(tile)) {
2482 /* Update build vehicle window related to this depot */
2483 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
2484 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
2487 } else {
2488 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
2490 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
2491 * it would cause assert because of different test and exec runs */
2492 if (endtile < tile) {
2493 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
2496 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
2497 if (!HasPowerOnRoad(from_type, to_type)) {
2498 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
2499 if (ret.Failed()) {
2500 error = ret;
2501 continue;
2504 if (rtt == RTT_ROAD && owner == OWNER_TOWN) {
2505 error.MakeError(STR_ERROR_OWNED_BY);
2506 GetNameOfOwner(OWNER_TOWN, tile);
2507 continue;
2511 /* There are 2 pieces on *every* tile of the bridge or tunnel */
2512 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * 2;
2513 found_convertible_road = true;
2514 cost.AddCost(num_pieces * RoadConvertCost(from_type, to_type));
2516 if (flags & DC_EXEC) {
2517 /* Update the company infrastructure counters. */
2518 if (owner == _current_company) {
2519 /* Each piece should be counted TUNNELBRIDGE_TRACKBIT_FACTOR times
2520 * for the infrastructure counters (cause of #8297). */
2521 ConvertRoadTypeOwner(tile, num_pieces * TUNNELBRIDGE_TRACKBIT_FACTOR, owner, from_type, to_type);
2522 SetTunnelBridgeOwner(tile, endtile, _current_company);
2525 /* Perform the conversion */
2526 SetRoadType(tile, rtt, to_type);
2527 SetRoadType(endtile, rtt, to_type);
2529 FindVehicleOnPos(tile, &affected_rvs, &UpdateRoadVehPowerProc);
2530 FindVehicleOnPos(endtile, &affected_rvs, &UpdateRoadVehPowerProc);
2532 if (IsBridge(tile)) {
2533 MarkBridgeDirty(tile);
2534 } else {
2535 MarkTileDirtyByTile(tile);
2536 MarkTileDirtyByTile(endtile);
2542 if (flags & DC_EXEC) {
2543 /* Roadtype changed, update roadvehicles as when entering different track */
2544 for (RoadVehicle *v : affected_rvs) {
2545 v->CargoChanged();
2549 delete iter;
2550 return found_convertible_road ? cost : error;
2554 /** Tile callback functions for road tiles */
2555 extern const TileTypeProcs _tile_type_road_procs = {
2556 DrawTile_Road, // draw_tile_proc
2557 GetSlopePixelZ_Road, // get_slope_z_proc
2558 ClearTile_Road, // clear_tile_proc
2559 nullptr, // add_accepted_cargo_proc
2560 GetTileDesc_Road, // get_tile_desc_proc
2561 GetTileTrackStatus_Road, // get_tile_track_status_proc
2562 ClickTile_Road, // click_tile_proc
2563 nullptr, // animate_tile_proc
2564 TileLoop_Road, // tile_loop_proc
2565 ChangeTileOwner_Road, // change_tile_owner_proc
2566 nullptr, // add_produced_cargo_proc
2567 VehicleEnter_Road, // vehicle_enter_tile_proc
2568 GetFoundation_Road, // get_foundation_proc
2569 TerraformTile_Road, // terraform_tile_proc