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 rail_cmd.cpp Handling of rail tiles. */
11 #include "viewport_func.h"
12 #include "command_func.h"
13 #include "depot_base.h"
14 #include "pathfinder/yapf/yapf_cache.h"
15 #include "newgrf_debug.h"
16 #include "newgrf_railtype.h"
18 #include "autoslope.h"
20 #include "tunnelbridge_map.h"
21 #include "vehicle_func.h"
22 #include "sound_func.h"
23 #include "tunnelbridge.h"
24 #include "elrail_func.h"
27 #include "company_base.h"
28 #include "core/backup_type.hpp"
29 #include "date_func.h"
30 #include "strings_func.h"
31 #include "company_gui.h"
32 #include "object_map.h"
34 #include "landscape_cmd.h"
36 #include "table/strings.h"
37 #include "table/railtypes.h"
38 #include "table/track_land.h"
40 #include "safeguards.h"
42 /** Helper type for lists/vectors of trains */
43 typedef std::vector
<Train
*> TrainList
;
45 RailtypeInfo _railtypes
[RAILTYPE_END
];
46 std::vector
<RailType
> _sorted_railtypes
;
47 RailTypes _railtypes_hidden_mask
;
49 /** Enum holding the signal offset in the sprite sheet according to the side it is representing. */
62 * Reset all rail type information to its default values.
66 static_assert(lengthof(_original_railtypes
) <= lengthof(_railtypes
));
69 for (; i
< lengthof(_original_railtypes
); i
++) _railtypes
[i
] = _original_railtypes
[i
];
71 static const RailtypeInfo empty_railtype
= {
72 {0,0,0,0,0,0,0,0,0,0,0,0},
76 0, RAILTYPES_NONE
, RAILTYPES_NONE
, 0, 0, 0, RTFB_NONE
, 0, 0, 0, 0, 0,
77 RailTypeLabelList(), 0, 0, RAILTYPES_NONE
, RAILTYPES_NONE
, 0,
79 for (; i
< lengthof(_railtypes
); i
++) _railtypes
[i
] = empty_railtype
;
81 _railtypes_hidden_mask
= RAILTYPES_NONE
;
84 void ResolveRailTypeGUISprites(RailtypeInfo
*rti
)
86 SpriteID cursors_base
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_CURSORS
);
87 if (cursors_base
!= 0) {
88 rti
->gui_sprites
.build_ns_rail
= cursors_base
+ 0;
89 rti
->gui_sprites
.build_x_rail
= cursors_base
+ 1;
90 rti
->gui_sprites
.build_ew_rail
= cursors_base
+ 2;
91 rti
->gui_sprites
.build_y_rail
= cursors_base
+ 3;
92 rti
->gui_sprites
.auto_rail
= cursors_base
+ 4;
93 rti
->gui_sprites
.build_depot
= cursors_base
+ 5;
94 rti
->gui_sprites
.build_tunnel
= cursors_base
+ 6;
95 rti
->gui_sprites
.convert_rail
= cursors_base
+ 7;
96 rti
->cursor
.rail_ns
= cursors_base
+ 8;
97 rti
->cursor
.rail_swne
= cursors_base
+ 9;
98 rti
->cursor
.rail_ew
= cursors_base
+ 10;
99 rti
->cursor
.rail_nwse
= cursors_base
+ 11;
100 rti
->cursor
.autorail
= cursors_base
+ 12;
101 rti
->cursor
.depot
= cursors_base
+ 13;
102 rti
->cursor
.tunnel
= cursors_base
+ 14;
103 rti
->cursor
.convert
= cursors_base
+ 15;
106 /* Array of default GUI signal sprite numbers. */
107 const SpriteID _signal_lookup
[2][SIGTYPE_END
] = {
108 {SPR_IMG_SIGNAL_ELECTRIC_NORM
, SPR_IMG_SIGNAL_ELECTRIC_ENTRY
, SPR_IMG_SIGNAL_ELECTRIC_EXIT
,
109 SPR_IMG_SIGNAL_ELECTRIC_COMBO
, SPR_IMG_SIGNAL_ELECTRIC_PBS
, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY
},
111 {SPR_IMG_SIGNAL_SEMAPHORE_NORM
, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY
, SPR_IMG_SIGNAL_SEMAPHORE_EXIT
,
112 SPR_IMG_SIGNAL_SEMAPHORE_COMBO
, SPR_IMG_SIGNAL_SEMAPHORE_PBS
, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY
},
115 for (SignalType type
= SIGTYPE_NORMAL
; type
< SIGTYPE_END
; type
= (SignalType
)(type
+ 1)) {
116 for (SignalVariant var
= SIG_ELECTRIC
; var
<= SIG_SEMAPHORE
; var
= (SignalVariant
)(var
+ 1)) {
117 SpriteID red
= GetCustomSignalSprite(rti
, INVALID_TILE
, type
, var
, SIGNAL_STATE_RED
, true);
118 SpriteID green
= GetCustomSignalSprite(rti
, INVALID_TILE
, type
, var
, SIGNAL_STATE_GREEN
, true);
119 rti
->gui_sprites
.signals
[type
][var
][0] = (red
!= 0) ? red
+ SIGNAL_TO_SOUTH
: _signal_lookup
[var
][type
];
120 rti
->gui_sprites
.signals
[type
][var
][1] = (green
!= 0) ? green
+ SIGNAL_TO_SOUTH
: _signal_lookup
[var
][type
] + 1;
126 * Compare railtypes based on their sorting order.
127 * @param first The railtype to compare to.
128 * @param second The railtype to compare.
129 * @return True iff the first should be sorted before the second.
131 static bool CompareRailTypes(const RailType
&first
, const RailType
&second
)
133 return GetRailTypeInfo(first
)->sorting_order
< GetRailTypeInfo(second
)->sorting_order
;
137 * Resolve sprites of custom rail types
141 for (RailType rt
= RAILTYPE_BEGIN
; rt
!= RAILTYPE_END
; rt
++) {
142 RailtypeInfo
*rti
= &_railtypes
[rt
];
143 ResolveRailTypeGUISprites(rti
);
144 if (HasBit(rti
->flags
, RTF_HIDDEN
)) SetBit(_railtypes_hidden_mask
, rt
);
147 _sorted_railtypes
.clear();
148 for (RailType rt
= RAILTYPE_BEGIN
; rt
!= RAILTYPE_END
; rt
++) {
149 if (_railtypes
[rt
].label
!= 0 && !HasBit(_railtypes_hidden_mask
, rt
)) {
150 _sorted_railtypes
.push_back(rt
);
153 std::sort(_sorted_railtypes
.begin(), _sorted_railtypes
.end(), CompareRailTypes
);
157 * Allocate a new rail type label
159 RailType
AllocateRailType(RailTypeLabel label
)
161 for (RailType rt
= RAILTYPE_BEGIN
; rt
!= RAILTYPE_END
; rt
++) {
162 RailtypeInfo
*rti
= &_railtypes
[rt
];
164 if (rti
->label
== 0) {
165 /* Set up new rail type */
166 *rti
= _original_railtypes
[RAILTYPE_RAIL
];
168 rti
->alternate_labels
.clear();
170 /* Make us compatible with ourself. */
171 rti
->powered_railtypes
= (RailTypes
)(1LL << rt
);
172 rti
->compatible_railtypes
= (RailTypes
)(1LL << rt
);
174 /* We also introduce ourself. */
175 rti
->introduces_railtypes
= (RailTypes
)(1LL << rt
);
177 /* Default sort order; order of allocation, but with some
178 * offsets so it's easier for NewGRF to pick a spot without
179 * changing the order of other (original) rail types.
180 * The << is so you can place other railtypes in between the
181 * other railtypes, the 7 is to be able to place something
182 * before the first (default) rail type. */
183 rti
->sorting_order
= rt
<< 4 | 7;
188 return INVALID_RAILTYPE
;
191 static const byte _track_sloped_sprites
[14] = {
216 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
217 * MAP3LO byte: abcd???? => Signal Exists?
218 * a and b are for diagonals, upper and left,
219 * one for each direction. (ie a == NE->SW, b ==
220 * SW->NE, or v.v., I don't know. b and c are
221 * similar for lower and right.
222 * MAP2 byte: ????abcd => Type of ground.
223 * MAP3LO byte: ????abcd => Type of rail.
224 * MAP5: 00abcdef => rail
225 * 01abcdef => rail w/ signals
227 * 11uuuudd => rail depot
231 * Tests if a vehicle interacts with the specified track.
232 * All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
234 * @param tile The tile.
235 * @param track The track.
236 * @return Succeeded command (no train found), or a failed command (a train was found).
238 static CommandCost
EnsureNoTrainOnTrack(TileIndex tile
, Track track
)
240 TrackBits rail_bits
= TrackToTrackBits(track
);
241 return EnsureNoTrainOnTrackBits(tile
, rail_bits
);
245 * Check that the new track bits may be built.
246 * @param tile %Tile to build on.
247 * @param to_build New track bits.
248 * @param flags Flags of the operation.
249 * @return Succeeded or failed command.
251 static CommandCost
CheckTrackCombination(TileIndex tile
, TrackBits to_build
, uint flags
)
253 if (!IsPlainRail(tile
)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION
);
255 /* So, we have a tile with tracks on it (and possibly signals). Let's see
256 * what tracks first */
257 TrackBits current
= GetTrackBits(tile
); // The current track layout.
258 TrackBits future
= current
| to_build
; // The track layout we want to build.
260 /* Are we really building something new? */
261 if (current
== future
) {
262 /* Nothing new is being built */
263 return_cmd_error(STR_ERROR_ALREADY_BUILT
);
266 /* Normally, we may overlap and any combination is valid */
267 return CommandCost();
271 /** Valid TrackBits on a specific (non-steep)-slope without foundation */
272 static const TrackBits _valid_tracks_without_foundation
[15] = {
293 /** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
294 static const TrackBits _valid_tracks_on_leveled_foundation
[15] = {
298 TRACK_BIT_Y
| TRACK_BIT_LOWER
| TRACK_BIT_LEFT
,
302 TRACK_BIT_X
| TRACK_BIT_LOWER
| TRACK_BIT_RIGHT
,
306 TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_LEFT
,
310 TRACK_BIT_Y
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
,
316 * Checks if a track combination is valid on a specific slope and returns the needed foundation.
318 * @param tileh Tile slope.
319 * @param bits Trackbits.
320 * @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
322 Foundation
GetRailFoundation(Slope tileh
, TrackBits bits
)
324 if (bits
== TRACK_BIT_NONE
) return FOUNDATION_NONE
;
326 if (IsSteepSlope(tileh
)) {
327 /* Test for inclined foundations */
328 if (bits
== TRACK_BIT_X
) return FOUNDATION_INCLINED_X
;
329 if (bits
== TRACK_BIT_Y
) return FOUNDATION_INCLINED_Y
;
331 /* Get higher track */
332 Corner highest_corner
= GetHighestSlopeCorner(tileh
);
333 TrackBits higher_track
= CornerToTrackBits(highest_corner
);
335 /* Only higher track? */
336 if (bits
== higher_track
) return HalftileFoundation(highest_corner
);
338 /* Overlap with higher track? */
339 if (TracksOverlap(bits
| higher_track
)) return FOUNDATION_INVALID
;
341 /* either lower track or both higher and lower track */
342 return ((bits
& higher_track
) != 0 ? FOUNDATION_STEEP_BOTH
: FOUNDATION_STEEP_LOWER
);
344 if ((~_valid_tracks_without_foundation
[tileh
] & bits
) == 0) return FOUNDATION_NONE
;
346 bool valid_on_leveled
= ((~_valid_tracks_on_leveled_foundation
[tileh
] & bits
) == 0);
350 case TRACK_BIT_LEFT
: track_corner
= CORNER_W
; break;
351 case TRACK_BIT_LOWER
: track_corner
= CORNER_S
; break;
352 case TRACK_BIT_RIGHT
: track_corner
= CORNER_E
; break;
353 case TRACK_BIT_UPPER
: track_corner
= CORNER_N
; break;
356 if (tileh
== SLOPE_N
) return HalftileFoundation(CORNER_N
);
357 if (tileh
== SLOPE_S
) return HalftileFoundation(CORNER_S
);
358 return (valid_on_leveled
? FOUNDATION_LEVELED
: FOUNDATION_INVALID
);
361 if (tileh
== SLOPE_W
) return HalftileFoundation(CORNER_W
);
362 if (tileh
== SLOPE_E
) return HalftileFoundation(CORNER_E
);
363 return (valid_on_leveled
? FOUNDATION_LEVELED
: FOUNDATION_INVALID
);
366 if (IsSlopeWithOneCornerRaised(tileh
)) return FOUNDATION_INCLINED_X
;
367 return (valid_on_leveled
? FOUNDATION_LEVELED
: FOUNDATION_INVALID
);
370 if (IsSlopeWithOneCornerRaised(tileh
)) return FOUNDATION_INCLINED_Y
;
371 return (valid_on_leveled
? FOUNDATION_LEVELED
: FOUNDATION_INVALID
);
374 return (valid_on_leveled
? FOUNDATION_LEVELED
: FOUNDATION_INVALID
);
376 /* Single diagonal track */
378 /* Track must be at least valid on leveled foundation */
379 if (!valid_on_leveled
) return FOUNDATION_INVALID
;
381 /* If slope has three raised corners, build leveled foundation */
382 if (IsSlopeWithThreeCornersRaised(tileh
)) return FOUNDATION_LEVELED
;
384 /* If neighboured corners of track_corner are lowered, build halftile foundation */
385 if ((tileh
& SlopeWithThreeCornersRaised(OppositeCorner(track_corner
))) == SlopeWithOneCornerRaised(track_corner
)) return HalftileFoundation(track_corner
);
387 /* else special anti-zig-zag foundation */
388 return SpecialRailFoundation(track_corner
);
394 * Tests if a track can be build on a tile.
396 * @param tileh Tile slope.
397 * @param rail_bits Tracks to build.
398 * @param existing Tracks already built.
399 * @param tile Tile (used for water test)
400 * @return Error message or cost for foundation building.
402 static CommandCost
CheckRailSlope(Slope tileh
, TrackBits rail_bits
, TrackBits existing
, TileIndex tile
)
404 /* don't allow building on the lower side of a coast */
405 if (GetFloodingBehaviour(tile
) != FLOOD_NONE
) {
406 if (!IsSteepSlope(tileh
) && ((~_valid_tracks_on_leveled_foundation
[tileh
] & (rail_bits
| existing
)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER
);
409 Foundation f_new
= GetRailFoundation(tileh
, rail_bits
| existing
);
411 /* check track/slope combination */
412 if ((f_new
== FOUNDATION_INVALID
) ||
413 ((f_new
!= FOUNDATION_NONE
) && (!_settings_game
.construction
.build_on_slopes
))) {
414 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
417 Foundation f_old
= GetRailFoundation(tileh
, existing
);
418 return CommandCost(EXPENSES_CONSTRUCTION
, f_new
!= f_old
? _price
[PR_BUILD_FOUNDATION
] : (Money
)0);
421 /* Validate functions for rail building */
422 static inline bool ValParamTrackOrientation(Track track
)
424 return IsValidTrack(track
);
428 * Build a single piece of rail
429 * @param flags operation to perform
430 * @param tile tile to build on
431 * @param railtype railtype of being built piece (normal, mono, maglev)
432 * @param track track-orientation
433 * @param auto_remove_signals false = error on signal in the way, true = auto remove signals when in the way
434 * @return the cost of this operation or an error
436 CommandCost
CmdBuildSingleRail(DoCommandFlag flags
, TileIndex tile
, RailType railtype
, Track track
, bool auto_remove_signals
)
438 CommandCost
cost(EXPENSES_CONSTRUCTION
);
440 if (!ValParamRailtype(railtype
) || !ValParamTrackOrientation(track
)) return CMD_ERROR
;
442 Slope tileh
= GetTileSlope(tile
);
443 TrackBits trackbit
= TrackToTrackBits(track
);
445 switch (GetTileType(tile
)) {
447 CommandCost ret
= CheckTileOwnership(tile
);
448 if (ret
.Failed()) return ret
;
450 if (!IsPlainRail(tile
)) return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
); // just get appropriate error message
452 if (!IsCompatibleRail(GetRailType(tile
), railtype
)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION
);
454 ret
= CheckTrackCombination(tile
, trackbit
, flags
);
455 if (ret
.Succeeded()) ret
= EnsureNoTrainOnTrack(tile
, track
);
456 if (ret
.Failed()) return ret
;
458 ret
= CheckRailSlope(tileh
, trackbit
, GetTrackBits(tile
), tile
);
459 if (ret
.Failed()) return ret
;
462 if (HasSignals(tile
) && TracksOverlap(GetTrackBits(tile
) | TrackToTrackBits(track
))) {
463 /* If adding the new track causes any overlap, all signals must be removed first */
464 if (!auto_remove_signals
) return_cmd_error(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST
);
466 for (Track track_it
= TRACK_BEGIN
; track_it
< TRACK_END
; track_it
++) {
467 if (HasTrack(tile
, track_it
) && HasSignalOnTrack(tile
, track_it
)) {
468 CommandCost ret_remove_signals
= Command
<CMD_REMOVE_SIGNALS
>::Do(flags
, tile
, track_it
);
469 if (ret_remove_signals
.Failed()) return ret_remove_signals
;
470 cost
.AddCost(ret_remove_signals
);
475 /* If the rail types don't match, try to convert only if engines of
476 * the new rail type are not powered on the present rail type and engines of
477 * the present rail type are powered on the new rail type. */
478 if (GetRailType(tile
) != railtype
&& !HasPowerOnRail(railtype
, GetRailType(tile
))) {
479 if (HasPowerOnRail(GetRailType(tile
), railtype
)) {
480 ret
= Command
<CMD_CONVERT_RAIL
>::Do(flags
, tile
, tile
, railtype
, false);
481 if (ret
.Failed()) return ret
;
488 if (flags
& DC_EXEC
) {
489 SetRailGroundType(tile
, RAIL_GROUND_BARREN
);
490 TrackBits bits
= GetTrackBits(tile
);
491 SetTrackBits(tile
, bits
| trackbit
);
492 /* Subtract old infrastructure count. */
493 uint pieces
= CountBits(bits
);
494 if (TracksOverlap(bits
)) pieces
*= pieces
;
495 Company::Get(GetTileOwner(tile
))->infrastructure
.rail
[GetRailType(tile
)] -= pieces
;
496 /* Add new infrastructure count. */
497 pieces
= CountBits(bits
| trackbit
);
498 if (TracksOverlap(bits
| trackbit
)) pieces
*= pieces
;
499 Company::Get(GetTileOwner(tile
))->infrastructure
.rail
[GetRailType(tile
)] += pieces
;
500 DirtyCompanyInfrastructureWindows(GetTileOwner(tile
));
506 /* Level crossings may only be built on these slopes */
507 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES
, tileh
)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
509 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
510 if (ret
.Failed()) return ret
;
512 if (IsNormalRoad(tile
)) {
513 if (HasRoadWorks(tile
)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS
);
515 if (GetDisallowedRoadDirections(tile
) != DRD_NONE
) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD
);
517 if (RailNoLevelCrossings(railtype
)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_RAIL
);
519 RoadType roadtype_road
= GetRoadTypeRoad(tile
);
520 RoadType roadtype_tram
= GetRoadTypeTram(tile
);
522 if (roadtype_road
!= INVALID_ROADTYPE
&& RoadNoLevelCrossing(roadtype_road
)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD
);
523 if (roadtype_tram
!= INVALID_ROADTYPE
&& RoadNoLevelCrossing(roadtype_tram
)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD
);
525 RoadBits road
= GetRoadBits(tile
, RTT_ROAD
);
526 RoadBits tram
= GetRoadBits(tile
, RTT_TRAM
);
527 if ((track
== TRACK_X
&& ((road
| tram
) & ROAD_X
) == 0) ||
528 (track
== TRACK_Y
&& ((road
| tram
) & ROAD_Y
) == 0)) {
529 Owner road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
530 Owner tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
531 /* Disallow breaking end-of-line of someone else
532 * so trams can still reverse on this tile. */
533 if (Company::IsValidID(tram_owner
) && HasExactlyOneBit(tram
)) {
534 CommandCost ret
= CheckOwnership(tram_owner
);
535 if (ret
.Failed()) return ret
;
538 uint num_new_road_pieces
= (road
!= ROAD_NONE
) ? 2 - CountBits(road
) : 0;
539 if (num_new_road_pieces
> 0) {
540 cost
.AddCost(num_new_road_pieces
* RoadBuildCost(roadtype_road
));
543 uint num_new_tram_pieces
= (tram
!= ROAD_NONE
) ? 2 - CountBits(tram
) : 0;
544 if (num_new_tram_pieces
> 0) {
545 cost
.AddCost(num_new_tram_pieces
* RoadBuildCost(roadtype_tram
));
548 if (flags
& DC_EXEC
) {
549 MakeRoadCrossing(tile
, road_owner
, tram_owner
, _current_company
, (track
== TRACK_X
? AXIS_Y
: AXIS_X
), railtype
, roadtype_road
, roadtype_tram
, GetTownIndex(tile
));
550 UpdateLevelCrossing(tile
, false);
551 Company::Get(_current_company
)->infrastructure
.rail
[railtype
] += LEVELCROSSING_TRACKBIT_FACTOR
;
552 DirtyCompanyInfrastructureWindows(_current_company
);
553 if (num_new_road_pieces
> 0 && Company::IsValidID(road_owner
)) {
554 Company::Get(road_owner
)->infrastructure
.road
[roadtype_road
] += num_new_road_pieces
;
555 DirtyCompanyInfrastructureWindows(road_owner
);
557 if (num_new_tram_pieces
> 0 && Company::IsValidID(tram_owner
)) {
558 Company::Get(tram_owner
)->infrastructure
.road
[roadtype_tram
] += num_new_tram_pieces
;
559 DirtyCompanyInfrastructureWindows(tram_owner
);
566 if (IsLevelCrossing(tile
) && GetCrossingRailBits(tile
) == trackbit
) {
567 return_cmd_error(STR_ERROR_ALREADY_BUILT
);
573 /* Will there be flat water on the lower halftile? */
574 bool water_ground
= IsTileType(tile
, MP_WATER
) && IsSlopeWithOneCornerRaised(tileh
);
576 CommandCost ret
= CheckRailSlope(tileh
, trackbit
, TRACK_BIT_NONE
, tile
);
577 if (ret
.Failed()) return ret
;
580 ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
581 if (ret
.Failed()) return ret
;
585 cost
.AddCost(-_price
[PR_CLEAR_WATER
]);
586 cost
.AddCost(_price
[PR_CLEAR_ROUGH
]);
589 if (flags
& DC_EXEC
) {
590 MakeRailNormal(tile
, _current_company
, trackbit
, railtype
);
592 SetRailGroundType(tile
, RAIL_GROUND_WATER
);
593 if (IsPossibleDockingTile(tile
)) CheckForDockingTile(tile
);
595 Company::Get(_current_company
)->infrastructure
.rail
[railtype
]++;
596 DirtyCompanyInfrastructureWindows(_current_company
);
602 if (flags
& DC_EXEC
) {
603 MarkTileDirtyByTile(tile
);
604 AddTrackToSignalBuffer(tile
, track
, _current_company
);
605 YapfNotifyTrackLayoutChange(tile
, track
);
608 cost
.AddCost(RailBuildCost(railtype
));
613 * Remove a single piece of track
614 * @param flags operation to perform
615 * @param tile tile to remove track from
616 * @param track rail orientation
617 * @return the cost of this operation or an error
619 CommandCost
CmdRemoveSingleRail(DoCommandFlag flags
, TileIndex tile
, Track track
)
621 CommandCost
cost(EXPENSES_CONSTRUCTION
);
622 bool crossing
= false;
624 if (!ValParamTrackOrientation(track
)) return CMD_ERROR
;
625 TrackBits trackbit
= TrackToTrackBits(track
);
627 /* Need to read tile owner now because it may change when the rail is removed
628 * Also, in case of floods, _current_company != owner
629 * There may be invalid tiletype even in exec run (when removing long track),
630 * so do not call GetTileOwner(tile) in any case here */
631 Owner owner
= INVALID_OWNER
;
635 switch (GetTileType(tile
)) {
637 if (!IsLevelCrossing(tile
) || GetCrossingRailBits(tile
) != trackbit
) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
639 if (_current_company
!= OWNER_WATER
) {
640 CommandCost ret
= CheckTileOwnership(tile
);
641 if (ret
.Failed()) return ret
;
644 if (!(flags
& DC_BANKRUPT
)) {
645 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
646 if (ret
.Failed()) return ret
;
649 cost
.AddCost(RailClearCost(GetRailType(tile
)));
651 if (flags
& DC_EXEC
) {
652 if (HasReservedTracks(tile
, trackbit
)) {
653 v
= GetTrainForReservation(tile
, track
);
654 if (v
!= nullptr) FreeTrainTrackReservation(v
);
657 owner
= GetTileOwner(tile
);
658 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] -= LEVELCROSSING_TRACKBIT_FACTOR
;
659 DirtyCompanyInfrastructureWindows(owner
);
660 MakeRoadNormal(tile
, GetCrossingRoadBits(tile
), GetRoadTypeRoad(tile
), GetRoadTypeTram(tile
), GetTownIndex(tile
), GetRoadOwner(tile
, RTT_ROAD
), GetRoadOwner(tile
, RTT_TRAM
));
661 DeleteNewGRFInspectWindow(GSF_RAILTYPES
, tile
);
668 /* There are no rails present at depots. */
669 if (!IsPlainRail(tile
)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
671 if (_current_company
!= OWNER_WATER
) {
672 CommandCost ret
= CheckTileOwnership(tile
);
673 if (ret
.Failed()) return ret
;
676 CommandCost ret
= EnsureNoTrainOnTrack(tile
, track
);
677 if (ret
.Failed()) return ret
;
679 present
= GetTrackBits(tile
);
680 if ((present
& trackbit
) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
681 if (present
== (TRACK_BIT_X
| TRACK_BIT_Y
)) crossing
= true;
683 cost
.AddCost(RailClearCost(GetRailType(tile
)));
685 /* Charge extra to remove signals on the track, if they are there */
686 if (HasSignalOnTrack(tile
, track
)) {
687 cost
.AddCost(Command
<CMD_REMOVE_SIGNALS
>::Do(flags
, tile
, track
));
690 if (flags
& DC_EXEC
) {
691 if (HasReservedTracks(tile
, trackbit
)) {
692 v
= GetTrainForReservation(tile
, track
);
693 if (v
!= nullptr) FreeTrainTrackReservation(v
);
696 owner
= GetTileOwner(tile
);
698 /* Subtract old infrastructure count. */
699 uint pieces
= CountBits(present
);
700 if (TracksOverlap(present
)) pieces
*= pieces
;
701 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] -= pieces
;
702 /* Add new infrastructure count. */
704 pieces
= CountBits(present
);
705 if (TracksOverlap(present
)) pieces
*= pieces
;
706 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] += pieces
;
707 DirtyCompanyInfrastructureWindows(owner
);
710 Slope tileh
= GetTileSlope(tile
);
711 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
712 if (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh
)) {
713 bool docking
= IsDockingTile(tile
);
715 SetDockingTile(tile
, docking
);
719 DeleteNewGRFInspectWindow(GSF_RAILTYPES
, tile
);
721 SetTrackBits(tile
, present
);
722 SetTrackReservation(tile
, GetRailReservationTrackBits(tile
) & present
);
728 default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
731 if (flags
& DC_EXEC
) {
732 /* if we got that far, 'owner' variable is set correctly */
733 assert(Company::IsValidID(owner
));
735 MarkTileDirtyByTile(tile
);
737 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
738 * are removing one of these pieces, we'll need to update signals for
739 * both directions explicitly, as after the track is removed it won't
740 * 'connect' with the other piece. */
741 AddTrackToSignalBuffer(tile
, TRACK_X
, owner
);
742 AddTrackToSignalBuffer(tile
, TRACK_Y
, owner
);
743 YapfNotifyTrackLayoutChange(tile
, TRACK_X
);
744 YapfNotifyTrackLayoutChange(tile
, TRACK_Y
);
746 AddTrackToSignalBuffer(tile
, track
, owner
);
747 YapfNotifyTrackLayoutChange(tile
, track
);
750 if (v
!= nullptr) TryPathReserve(v
, true);
758 * Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
759 * The function floods the lower halftile, if the tile has a halftile foundation.
761 * @param t The tile to flood.
762 * @return true if something was flooded.
764 bool FloodHalftile(TileIndex t
)
766 assert(IsPlainRailTile(t
));
768 bool flooded
= false;
769 if (GetRailGroundType(t
) == RAIL_GROUND_WATER
) return flooded
;
771 Slope tileh
= GetTileSlope(t
);
772 TrackBits rail_bits
= GetTrackBits(t
);
774 if (IsSlopeWithOneCornerRaised(tileh
)) {
775 TrackBits lower_track
= CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh
)));
777 TrackBits to_remove
= lower_track
& rail_bits
;
778 if (to_remove
!= 0) {
779 Backup
<CompanyID
> cur_company(_current_company
, OWNER_WATER
, FILE_LINE
);
780 flooded
= Command
<CMD_REMOVE_SINGLE_RAIL
>::Do(DC_EXEC
, t
, FindFirstTrack(to_remove
)).Succeeded();
781 cur_company
.Restore();
782 if (!flooded
) return flooded
; // not yet floodable
783 rail_bits
= rail_bits
& ~to_remove
;
784 if (rail_bits
== 0) {
786 MarkTileDirtyByTile(t
);
791 if (IsNonContinuousFoundation(GetRailFoundation(tileh
, rail_bits
))) {
793 SetRailGroundType(t
, RAIL_GROUND_WATER
);
794 MarkTileDirtyByTile(t
);
797 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
798 if (ApplyFoundationToSlope(GetRailFoundation(tileh
, rail_bits
), &tileh
) == 0) {
799 if (IsSteepSlope(tileh
) || IsSlopeWithThreeCornersRaised(tileh
)) {
801 SetRailGroundType(t
, RAIL_GROUND_WATER
);
802 MarkTileDirtyByTile(t
);
809 static const TileIndexDiffC _trackdelta
[] = {
810 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
813 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
819 static CommandCost
ValidateAutoDrag(Trackdir
*trackdir
, TileIndex start
, TileIndex end
)
821 int x
= TileX(start
);
822 int y
= TileY(start
);
826 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir
))) return CMD_ERROR
;
828 /* calculate delta x,y from start to end tile */
832 /* calculate delta x,y for the first direction */
833 int trdx
= _trackdelta
[*trackdir
].x
;
834 int trdy
= _trackdelta
[*trackdir
].y
;
836 if (!IsDiagonalTrackdir(*trackdir
)) {
837 trdx
+= _trackdelta
[*trackdir
^ 1].x
;
838 trdy
+= _trackdelta
[*trackdir
^ 1].y
;
841 /* validate the direction */
842 while ((trdx
<= 0 && dx
> 0) ||
843 (trdx
>= 0 && dx
< 0) ||
844 (trdy
<= 0 && dy
> 0) ||
845 (trdy
>= 0 && dy
< 0)) {
846 if (!HasBit(*trackdir
, 3)) { // first direction is invalid, try the other
847 SetBit(*trackdir
, 3); // reverse the direction
850 } else { // other direction is invalid too, invalid drag
855 /* (for diagonal tracks, this is already made sure of by above test), but:
856 * for non-diagonal tracks, check if the start and end tile are on 1 line */
857 if (!IsDiagonalTrackdir(*trackdir
)) {
858 trdx
= _trackdelta
[*trackdir
].x
;
859 trdy
= _trackdelta
[*trackdir
].y
;
860 if (abs(dx
) != abs(dy
) && abs(dx
) + abs(trdy
) != abs(dy
) + abs(trdx
)) return CMD_ERROR
;
863 return CommandCost();
867 * Build or remove a stretch of railroad tracks.
868 * @param flags operation to perform
869 * @param tile start tile of drag
870 * @param end_tile end tile of drag
871 * @param railtype railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
872 * @param track track-orientation
873 * @param remove remove tracks?
874 * @param auto_remove_signals false = build up to an obstacle, true = fail if an obstacle is found (used for AIs), only used for building
875 * @param fail_on_obstacle false = error on signal in the way, true = auto remove signals when in the way, only used for building
876 * @return the cost of this operation or an error
878 static CommandCost
CmdRailTrackHelper(DoCommandFlag flags
, TileIndex tile
, TileIndex end_tile
, RailType railtype
, Track track
, bool remove
, bool auto_remove_signals
, bool fail_on_obstacle
)
880 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
882 if ((!remove
&& !ValParamRailtype(railtype
)) || !ValParamTrackOrientation(track
)) return CMD_ERROR
;
883 if (end_tile
>= MapSize() || tile
>= MapSize()) return CMD_ERROR
;
885 Trackdir trackdir
= TrackToTrackdir(track
);
887 CommandCost ret
= ValidateAutoDrag(&trackdir
, tile
, end_tile
);
888 if (ret
.Failed()) return ret
;
890 bool had_success
= false;
891 CommandCost last_error
= CMD_ERROR
;
893 CommandCost ret
= remove
? Command
<CMD_REMOVE_SINGLE_RAIL
>::Do(flags
, tile
, TrackdirToTrack(trackdir
)) : Command
<CMD_BUILD_SINGLE_RAIL
>::Do(flags
, tile
, railtype
, TrackdirToTrack(trackdir
), auto_remove_signals
);
897 if (last_error
.GetErrorMessage() != STR_ERROR_ALREADY_BUILT
&& !remove
) {
898 if (fail_on_obstacle
) return last_error
;
902 /* Ownership errors are more important. */
903 if (last_error
.GetErrorMessage() == STR_ERROR_OWNED_BY
&& remove
) break;
906 total_cost
.AddCost(ret
);
909 if (tile
== end_tile
) break;
911 tile
+= ToTileIndexDiff(_trackdelta
[trackdir
]);
913 /* toggle railbit for the non-diagonal tracks */
914 if (!IsDiagonalTrackdir(trackdir
)) ToggleBit(trackdir
, 0);
917 if (had_success
) return total_cost
;
922 * Build rail on a stretch of track.
923 * Stub for the unified rail builder/remover
924 * @param flags operation to perform
925 * @param end_tile end tile of drag
926 * @param start_tile start tile of drag
927 * @param railtype railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
928 * @param track track-orientation
929 * @param auto_remove_signals false = build up to an obstacle, true = fail if an obstacle is found (used for AIs).
930 * @param fail_on_obstacle false = error on signal in the way, true = auto remove signals when in the way
932 * @see CmdRailTrackHelper
934 CommandCost
CmdBuildRailroadTrack(DoCommandFlag flags
, TileIndex end_tile
, TileIndex start_tile
, RailType railtype
, Track track
, bool auto_remove_signals
, bool fail_on_obstacle
)
936 return CmdRailTrackHelper(flags
, start_tile
, end_tile
, railtype
, track
, false, auto_remove_signals
, fail_on_obstacle
);
940 * Build rail on a stretch of track.
941 * Stub for the unified rail builder/remover
942 * @param flags operation to perform
943 * @param end_tile end tile of drag
944 * @param start_tile start tile of drag
945 * @param track track-orientation
946 * @return the cost of this operation or an error
947 * @see CmdRailTrackHelper
949 CommandCost
CmdRemoveRailroadTrack(DoCommandFlag flags
, TileIndex end_tile
, TileIndex start_tile
, Track track
)
951 return CmdRailTrackHelper(flags
, start_tile
, end_tile
, INVALID_RAILTYPE
, track
, true, false, false);
955 * Build a train depot
956 * @param flags operation to perform
957 * @param tile position of the train depot
958 * @param railtype rail type
959 * @param dir entrance direction
960 * @return the cost of this operation or an error
962 * @todo When checking for the tile slope,
963 * distinguish between "Flat land required" and "land sloped in wrong direction"
965 CommandCost
CmdBuildTrainDepot(DoCommandFlag flags
, TileIndex tile
, RailType railtype
, DiagDirection dir
)
967 /* check railtype and valid direction for depot (0 through 3), 4 in total */
968 if (!ValParamRailtype(railtype
) || !IsValidDiagDirection(dir
)) return CMD_ERROR
;
970 Slope tileh
= GetTileSlope(tile
);
972 CommandCost
cost(EXPENSES_CONSTRUCTION
);
974 /* Prohibit construction if
975 * The tile is non-flat AND
976 * 1) build-on-slopes is disabled
977 * 2) the tile is steep i.e. spans two height levels
978 * 3) the exit points in the wrong direction
981 if (tileh
!= SLOPE_FLAT
) {
982 if (!_settings_game
.construction
.build_on_slopes
|| !CanBuildDepotByTileh(dir
, tileh
)) {
983 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
985 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
988 cost
.AddCost(Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
));
989 if (cost
.Failed()) return cost
;
991 if (IsBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
993 if (!Depot::CanAllocateItem()) return CMD_ERROR
;
995 if (flags
& DC_EXEC
) {
996 Depot
*d
= new Depot(tile
);
997 d
->build_date
= _date
;
999 MakeRailDepot(tile
, _current_company
, d
->index
, dir
, railtype
);
1000 MarkTileDirtyByTile(tile
);
1003 Company::Get(_current_company
)->infrastructure
.rail
[railtype
]++;
1004 DirtyCompanyInfrastructureWindows(_current_company
);
1006 AddSideToSignalBuffer(tile
, INVALID_DIAGDIR
, _current_company
);
1007 YapfNotifyTrackLayoutChange(tile
, DiagDirToDiagTrack(dir
));
1010 cost
.AddCost(_price
[PR_BUILD_DEPOT_TRAIN
]);
1011 cost
.AddCost(RailBuildCost(railtype
));
1016 * Build signals, alternate between double/single, signal/semaphore,
1017 * pre/exit/combo-signals, and what-else not. If the rail piece does not
1018 * have any signals, signal cycling is ignored
1019 * @param flags operation to perform
1020 * @param tile tile where to build the signals
1021 * @param track track-orientation
1022 * @param sigtype type of the signal
1023 * @param sigvar variant of signal type (normal/semaphore)
1024 * @param ctrl_pressed true = override signal/semaphore, or pre/exit/combo signal or toggle variant (CTRL-toggle)
1025 * @param convert_signal convert the present signal type and variant
1026 * @param cycle_start start cycle from this signal type
1027 * @param cycle_stop wrap around after this signal type
1028 * @param num_dir_cycle cycle the signal direction this many times
1029 * @param skip_existing_signals true = don't modify an existing signal but don't fail either, false = always set new signal type
1030 * @param signals_copy used for CmdBuildManySignals() to copy direction of first signal
1031 * @return the cost of this operation or an error
1032 * @todo p2 should be replaced by two bits for "along" and "against" the track.
1034 CommandCost
CmdBuildSingleSignal(DoCommandFlag flags
, TileIndex tile
, Track track
, SignalType sigtype
, SignalVariant sigvar
, bool convert_signal
, bool skip_existing_signals
, bool ctrl_pressed
, SignalType cycle_start
, SignalType cycle_stop
, uint8 num_dir_cycle
, byte signals_copy
)
1036 if (sigtype
> SIGTYPE_LAST
|| sigvar
> SIG_SEMAPHORE
) return CMD_ERROR
;
1037 if (cycle_start
> cycle_stop
|| cycle_stop
> SIGTYPE_LAST
) return CMD_ERROR
;
1039 if (ctrl_pressed
) sigvar
= (SignalVariant
)(sigvar
^ SIG_SEMAPHORE
);
1041 /* You can only build signals on plain rail tiles, and the selected track must exist */
1042 if (!ValParamTrackOrientation(track
) || !IsPlainRailTile(tile
) ||
1043 !HasTrack(tile
, track
)) {
1044 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
1046 /* Protect against invalid signal copying */
1047 if (signals_copy
!= 0 && (signals_copy
& SignalOnTrack(track
)) == 0) return CMD_ERROR
;
1049 CommandCost ret
= CheckTileOwnership(tile
);
1050 if (ret
.Failed()) return ret
;
1052 /* See if this is a valid track combination for signals (no overlap) */
1053 if (TracksOverlap(GetTrackBits(tile
))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK
);
1055 /* In case we don't want to change an existing signal, return without error. */
1056 if (skip_existing_signals
&& HasSignalOnTrack(tile
, track
)) return CommandCost();
1058 /* you can not convert a signal if no signal is on track */
1059 if (convert_signal
&& !HasSignalOnTrack(tile
, track
)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS
);
1062 if (!HasSignalOnTrack(tile
, track
)) {
1063 /* build new signals */
1064 cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_SIGNALS
]);
1066 if (signals_copy
!= 0 && sigvar
!= GetSignalVariant(tile
, track
)) {
1067 /* convert signals <-> semaphores */
1068 cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_SIGNALS
] + _price
[PR_CLEAR_SIGNALS
]);
1070 } else if (convert_signal
) {
1071 /* convert button pressed */
1072 if (ctrl_pressed
|| GetSignalVariant(tile
, track
) != sigvar
) {
1073 /* convert electric <-> semaphore */
1074 cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_SIGNALS
] + _price
[PR_CLEAR_SIGNALS
]);
1076 /* it is free to change signal type: normal-pre-exit-combo */
1077 cost
= CommandCost();
1081 /* it is free to change orientation/pre-exit-combo signals */
1082 cost
= CommandCost();
1086 if (flags
& DC_EXEC
) {
1088 /* The new/changed signal could block our path. As this can lead to
1089 * stale reservations, we clear the path reservation here and try
1090 * to redo it later on. */
1091 if (HasReservedTracks(tile
, TrackToTrackBits(track
))) {
1092 v
= GetTrainForReservation(tile
, track
);
1093 if (v
!= nullptr) FreeTrainTrackReservation(v
);
1096 if (!HasSignals(tile
)) {
1097 /* there are no signals at all on this tile yet */
1098 SetHasSignals(tile
, true);
1099 SetSignalStates(tile
, 0xF); // all signals are on
1100 SetPresentSignals(tile
, 0); // no signals built by default
1101 SetSignalType(tile
, track
, sigtype
);
1102 SetSignalVariant(tile
, track
, sigvar
);
1105 /* Subtract old signal infrastructure count. */
1106 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
-= CountBits(GetPresentSignals(tile
));
1108 if (signals_copy
== 0) {
1109 if (!HasSignalOnTrack(tile
, track
)) {
1110 /* build new signals */
1111 SetPresentSignals(tile
, GetPresentSignals(tile
) | (IsPbsSignal(sigtype
) ? KillFirstBit(SignalOnTrack(track
)) : SignalOnTrack(track
)));
1112 SetSignalType(tile
, track
, sigtype
);
1113 SetSignalVariant(tile
, track
, sigvar
);
1114 while (num_dir_cycle
-- > 0) CycleSignalSide(tile
, track
);
1116 if (convert_signal
) {
1117 /* convert signal button pressed */
1119 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1120 SetSignalVariant(tile
, track
, (GetSignalVariant(tile
, track
) == SIG_ELECTRIC
) ? SIG_SEMAPHORE
: SIG_ELECTRIC
);
1121 /* Query current signal type so the check for PBS signals below works. */
1122 sigtype
= GetSignalType(tile
, track
);
1124 /* convert the present signal to the chosen type and variant */
1125 SetSignalType(tile
, track
, sigtype
);
1126 SetSignalVariant(tile
, track
, sigvar
);
1127 if (IsPbsSignal(sigtype
) && (GetPresentSignals(tile
) & SignalOnTrack(track
)) == SignalOnTrack(track
)) {
1128 SetPresentSignals(tile
, (GetPresentSignals(tile
) & ~SignalOnTrack(track
)) | KillFirstBit(SignalOnTrack(track
)));
1132 } else if (ctrl_pressed
) {
1133 /* cycle between cycle_start and cycle_end */
1134 sigtype
= (SignalType
)(GetSignalType(tile
, track
) + 1);
1136 if (sigtype
< cycle_start
|| sigtype
> cycle_stop
) sigtype
= cycle_start
;
1138 SetSignalType(tile
, track
, sigtype
);
1139 if (IsPbsSignal(sigtype
) && (GetPresentSignals(tile
) & SignalOnTrack(track
)) == SignalOnTrack(track
)) {
1140 SetPresentSignals(tile
, (GetPresentSignals(tile
) & ~SignalOnTrack(track
)) | KillFirstBit(SignalOnTrack(track
)));
1143 /* cycle the signal side: both -> left -> right -> both -> ... */
1144 CycleSignalSide(tile
, track
);
1145 /* Query current signal type so the check for PBS signals below works. */
1146 sigtype
= GetSignalType(tile
, track
);
1150 /* If CmdBuildManySignals is called with copying signals, just copy the
1151 * direction of the first signal given as parameter by CmdBuildManySignals */
1152 SetPresentSignals(tile
, (GetPresentSignals(tile
) & ~SignalOnTrack(track
)) | (signals_copy
& SignalOnTrack(track
)));
1153 SetSignalVariant(tile
, track
, sigvar
);
1154 SetSignalType(tile
, track
, sigtype
);
1157 /* Add new signal infrastructure count. */
1158 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
+= CountBits(GetPresentSignals(tile
));
1159 DirtyCompanyInfrastructureWindows(GetTileOwner(tile
));
1161 if (IsPbsSignal(sigtype
)) {
1162 /* PBS signals should show red unless they are on reserved tiles without a train. */
1163 uint mask
= GetPresentSignals(tile
) & SignalOnTrack(track
);
1164 SetSignalStates(tile
, (GetSignalStates(tile
) & ~mask
) | ((HasBit(GetRailReservationTrackBits(tile
), track
) && EnsureNoVehicleOnGround(tile
).Succeeded() ? UINT_MAX
: 0) & mask
));
1166 MarkTileDirtyByTile(tile
);
1167 AddTrackToSignalBuffer(tile
, track
, _current_company
);
1168 YapfNotifyTrackLayoutChange(tile
, track
);
1169 if (v
!= nullptr && v
->track
!= TRACK_BIT_DEPOT
) {
1170 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1171 if (!(((v
->vehstatus
& VS_STOPPED
) && v
->cur_speed
== 0) || v
->current_order
.IsType(OT_LOADING
)) ||
1172 !IsSafeWaitingPosition(v
, v
->tile
, v
->GetVehicleTrackdir(), true, _settings_game
.pf
.forbid_90_deg
)) {
1173 TryPathReserve(v
, true);
1181 static bool AdvanceSignalAutoFill(TileIndex
&tile
, Trackdir
&trackdir
, bool remove
)
1183 /* We only process starting tiles of tunnels or bridges so jump to the other end before moving further. */
1184 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) tile
= GetOtherTunnelBridgeEnd(tile
);
1186 tile
= AddTileIndexDiffCWrap(tile
, _trackdelta
[trackdir
]);
1187 if (tile
== INVALID_TILE
) return false;
1189 /* Check for track bits on the new tile */
1190 TrackdirBits trackdirbits
= TrackStatusToTrackdirBits(GetTileTrackStatus(tile
, TRANSPORT_RAIL
, 0));
1192 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits
))) return false;
1193 trackdirbits
&= TrackdirReachesTrackdirs(trackdir
);
1195 /* No track bits, must stop */
1196 if (trackdirbits
== TRACKDIR_BIT_NONE
) return false;
1198 /* Get the first track dir */
1199 trackdir
= RemoveFirstTrackdir(&trackdirbits
);
1201 /* Any left? It's a junction so we stop */
1202 if (trackdirbits
!= TRACKDIR_BIT_NONE
) return false;
1204 switch (GetTileType(tile
)) {
1206 if (IsRailDepot(tile
)) return false;
1207 if (!remove
&& HasSignalOnTrack(tile
, TrackdirToTrack(trackdir
))) return false;
1211 if (!IsLevelCrossing(tile
)) return false;
1214 case MP_TUNNELBRIDGE
: {
1215 if (GetTunnelBridgeTransportType(tile
) != TRANSPORT_RAIL
) return false;
1216 if (GetTunnelBridgeDirection(tile
) != TrackdirToExitdir(trackdir
)) return false;
1220 default: return false;
1226 * Build many signals by dragging; AutoSignals
1227 * @param flags operation to perform
1228 * @param tile start tile of drag
1229 * @param end_tile end tile of drag
1230 * @param track track-orientation
1231 * @param sigtype default signal type
1232 * @param sigvar signal variant to build
1233 * @param mode true = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1234 * @param remove remove signals?
1235 * @param autofill fill beyond selected stretch?
1236 * @param minimise_gaps false = keep fixed distance, true = minimise gaps between signals
1237 * @param signal_density user defined signals_density
1238 * @return the cost of this operation or an error
1240 static CommandCost
CmdSignalTrackHelper(DoCommandFlag flags
, TileIndex tile
, TileIndex end_tile
, Track track
, SignalType sigtype
, SignalVariant sigvar
, bool mode
, bool remove
, bool autofill
, bool minimise_gaps
, int signal_density
)
1242 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1244 if (end_tile
>= MapSize() || !ValParamTrackOrientation(track
)) return CMD_ERROR
;
1245 if (signal_density
== 0 || signal_density
> 20) return CMD_ERROR
;
1246 if (!remove
&& (sigtype
> SIGTYPE_LAST
|| sigvar
> SIG_SEMAPHORE
)) return CMD_ERROR
;
1248 if (!IsPlainRailTile(tile
)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
1249 TileIndex start_tile
= tile
;
1251 /* Interpret signal_density as the logical length of said amount of tiles in X/Y direction. */
1252 signal_density
*= TILE_AXIAL_DISTANCE
;
1254 Trackdir trackdir
= TrackToTrackdir(track
);
1255 CommandCost ret
= ValidateAutoDrag(&trackdir
, tile
, end_tile
);
1256 if (ret
.Failed()) return ret
;
1258 track
= TrackdirToTrack(trackdir
); // trackdir might have changed, keep track in sync
1259 Trackdir start_trackdir
= trackdir
;
1261 /* Must start on a valid track to be able to avoid loops */
1262 if (!HasTrack(tile
, track
)) return CMD_ERROR
;
1265 /* copy the signal-style of the first rail-piece if existing */
1266 if (HasSignalOnTrack(tile
, track
)) {
1267 signals
= GetPresentSignals(tile
) & SignalOnTrack(track
);
1268 assert(signals
!= 0);
1270 /* copy signal/semaphores style (independent of CTRL) */
1271 sigvar
= GetSignalVariant(tile
, track
);
1273 sigtype
= GetSignalType(tile
, track
);
1274 /* Don't but copy entry or exit-signal type */
1275 if (sigtype
== SIGTYPE_ENTRY
|| sigtype
== SIGTYPE_EXIT
) sigtype
= SIGTYPE_NORMAL
;
1276 } else { // no signals exist, drag a two-way signal stretch
1277 signals
= IsPbsSignal(sigtype
) ? SignalAlongTrackdir(trackdir
) : SignalOnTrack(track
);
1280 byte signal_dir
= 0;
1281 if (signals
& SignalAlongTrackdir(trackdir
)) SetBit(signal_dir
, 0);
1282 if (signals
& SignalAgainstTrackdir(trackdir
)) SetBit(signal_dir
, 1);
1284 /* signal_ctr - amount of tiles already processed
1285 * last_used_ctr - amount of tiles before previously placed signal
1286 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1287 * last_suitable_ctr - amount of tiles before last possible signal place
1288 * last_suitable_tile - last tile where it is possible to place a signal
1289 * last_suitable_trackdir - trackdir of the last tile
1291 * trackdir - trackdir to build with autorail
1292 * semaphores - semaphores or signals
1293 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1294 * and convert all others to semaphore/signal
1295 * remove - 1 remove signals, 0 build signals */
1297 int last_used_ctr
= -signal_density
; // to force signal at first tile
1298 int last_suitable_ctr
= 0;
1299 TileIndex last_suitable_tile
= INVALID_TILE
;
1300 Trackdir last_suitable_trackdir
= INVALID_TRACKDIR
;
1301 CommandCost last_error
= CMD_ERROR
;
1302 bool had_success
= false;
1303 auto build_signal
= [&](TileIndex tile
, Trackdir trackdir
, bool test_only
) {
1304 /* Pick the correct orientation for the track direction */
1306 if (HasBit(signal_dir
, 0)) signals
|= SignalAlongTrackdir(trackdir
);
1307 if (HasBit(signal_dir
, 1)) signals
|= SignalAgainstTrackdir(trackdir
);
1309 DoCommandFlag do_flags
= test_only
? flags
& ~DC_EXEC
: flags
;
1310 CommandCost ret
= remove
? Command
<CMD_REMOVE_SIGNALS
>::Do(do_flags
, tile
, TrackdirToTrack(trackdir
)) : Command
<CMD_BUILD_SIGNALS
>::Do(do_flags
, tile
, TrackdirToTrack(trackdir
), sigtype
, sigvar
, false, signal_ctr
== 0, mode
, SIGTYPE_NORMAL
, SIGTYPE_NORMAL
, 0, signals
);
1312 if (test_only
) return ret
.Succeeded();
1314 if (ret
.Succeeded()) {
1316 total_cost
.AddCost(ret
);
1318 /* The "No railway" error is the least important one. */
1319 if (ret
.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
||
1320 last_error
.GetErrorMessage() == INVALID_STRING_ID
) {
1324 return ret
.Succeeded();
1329 /* In remove mode last_* stuff doesn't matter, we simply try to clear every tile. */
1330 build_signal(tile
, trackdir
, false);
1331 } else if (minimise_gaps
) {
1332 /* We're trying to minimize gaps wherever possible, so keep track of last suitable
1333 * position and use it if current gap exceeds required signal density. */
1335 if (signal_ctr
> last_used_ctr
+ signal_density
&& last_suitable_tile
!= INVALID_TILE
) {
1336 /* We overshot so build a signal in last good location. */
1337 if (build_signal(last_suitable_tile
, last_suitable_trackdir
, false)) {
1338 last_suitable_tile
= INVALID_TILE
;
1339 last_used_ctr
= last_suitable_ctr
;
1343 if (signal_ctr
== last_used_ctr
+ signal_density
) {
1344 /* Current gap matches the required density, build a signal. */
1345 if (build_signal(tile
, trackdir
, false)) {
1346 last_used_ctr
= signal_ctr
;
1347 last_suitable_tile
= INVALID_TILE
;
1350 /* Test tile for a potential signal spot. */
1351 if (build_signal(tile
, trackdir
, true)) {
1352 last_suitable_tile
= tile
;
1353 last_suitable_ctr
= signal_ctr
;
1354 last_suitable_trackdir
= trackdir
;
1357 } else if(signal_ctr
>= last_used_ctr
+ signal_density
) {
1358 /* We're always keeping regular interval between signals so doesn't matter whether we succeed or not. */
1359 build_signal(tile
, trackdir
, false);
1360 last_used_ctr
= signal_ctr
;
1364 switch (GetTileType(tile
)) {
1366 signal_ctr
+= (IsDiagonalTrackdir(trackdir
) ? TILE_AXIAL_DISTANCE
: TILE_CORNER_DISTANCE
);
1370 signal_ctr
+= TILE_AXIAL_DISTANCE
;
1373 case MP_TUNNELBRIDGE
: {
1374 uint len
= (GetTunnelBridgeLength(tile
, GetOtherTunnelBridgeEnd(tile
)) + 2) * TILE_AXIAL_DISTANCE
;
1375 if (remove
|| minimise_gaps
) {
1378 /* To keep regular interval we need to emulate placing signals on a bridge.
1379 * We start with TILE_AXIAL_DISTANCE as one bridge tile gets processed in the main loop. */
1380 signal_ctr
+= TILE_AXIAL_DISTANCE
;
1381 for(uint i
= TILE_AXIAL_DISTANCE
; i
< len
; i
+= TILE_AXIAL_DISTANCE
) {
1382 if (signal_ctr
>= last_used_ctr
+ signal_density
) last_used_ctr
= signal_ctr
;
1383 signal_ctr
+= TILE_AXIAL_DISTANCE
;
1392 if (!AdvanceSignalAutoFill(tile
, trackdir
, remove
)) break;
1394 /* Prevent possible loops */
1395 if (tile
== start_tile
&& trackdir
== start_trackdir
) break;
1397 if (tile
== end_tile
) break;
1399 signal_ctr
+= (IsDiagonalTrackdir(trackdir
) ? TILE_AXIAL_DISTANCE
: TILE_CORNER_DISTANCE
);
1400 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1402 tile
+= ToTileIndexDiff(_trackdelta
[trackdir
]);
1403 if (!IsDiagonalTrackdir(trackdir
)) ToggleBit(trackdir
, 0);
1407 /* We may end up with the current gap exceeding the signal density so fix that if needed. */
1408 if (!remove
&& minimise_gaps
&& signal_ctr
> last_used_ctr
+ signal_density
&& last_suitable_tile
!= INVALID_TILE
) {
1409 build_signal(last_suitable_tile
, last_suitable_trackdir
, false);
1412 return had_success
? total_cost
: last_error
;
1416 * Build signals on a stretch of track.
1417 * Stub for the unified signal builder/remover
1418 * @param flags operation to perform
1419 * @param tile start tile of drag
1420 * @param end_tile end tile of drag
1421 * @param track track-orientation
1422 * @param sigtype default signal type
1423 * @param sigvar signal variant to build
1424 * @param mode true = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1425 * @param autofill fill beyond selected stretch?
1426 * @param minimise_gaps false = keep fixed distance, true = minimise gaps between signals
1427 * @param signal_density user defined signals_density
1428 * @return the cost of this operation or an error
1429 * @see CmdSignalTrackHelper
1431 CommandCost
CmdBuildSignalTrack(DoCommandFlag flags
, TileIndex tile
, TileIndex end_tile
, Track track
, SignalType sigtype
, SignalVariant sigvar
, bool mode
, bool autofill
, bool minimise_gaps
, byte signal_density
)
1433 return CmdSignalTrackHelper(flags
, tile
, end_tile
, track
, sigtype
, sigvar
, mode
, false, autofill
, minimise_gaps
, signal_density
);
1438 * @param flags operation to perform
1439 * @param tile coordinates where signal is being deleted from
1440 * @param track track-orientation
1441 * @return the cost of this operation or an error
1443 CommandCost
CmdRemoveSingleSignal(DoCommandFlag flags
, TileIndex tile
, Track track
)
1445 if (!ValParamTrackOrientation(track
) || !IsPlainRailTile(tile
) || !HasTrack(tile
, track
)) {
1446 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
1448 if (!HasSignalOnTrack(tile
, track
)) {
1449 return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS
);
1452 /* Only water can remove signals from anyone */
1453 if (_current_company
!= OWNER_WATER
) {
1454 CommandCost ret
= CheckTileOwnership(tile
);
1455 if (ret
.Failed()) return ret
;
1459 if (flags
& DC_EXEC
) {
1461 if (HasReservedTracks(tile
, TrackToTrackBits(track
))) {
1462 v
= GetTrainForReservation(tile
, track
);
1463 } else if (IsPbsSignal(GetSignalType(tile
, track
))) {
1464 /* PBS signal, might be the end of a path reservation. */
1465 Trackdir td
= TrackToTrackdir(track
);
1466 for (int i
= 0; v
== nullptr && i
< 2; i
++, td
= ReverseTrackdir(td
)) {
1467 /* Only test the active signal side. */
1468 if (!HasSignalOnTrackdir(tile
, ReverseTrackdir(td
))) continue;
1469 TileIndex next
= TileAddByDiagDir(tile
, TrackdirToExitdir(td
));
1470 TrackBits tracks
= TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td
));
1471 if (HasReservedTracks(next
, tracks
)) {
1472 v
= GetTrainForReservation(next
, TrackBitsToTrack(GetReservedTrackbits(next
) & tracks
));
1476 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
-= CountBits(GetPresentSignals(tile
));
1477 SetPresentSignals(tile
, GetPresentSignals(tile
) & ~SignalOnTrack(track
));
1478 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
+= CountBits(GetPresentSignals(tile
));
1479 DirtyCompanyInfrastructureWindows(GetTileOwner(tile
));
1481 /* removed last signal from tile? */
1482 if (GetPresentSignals(tile
) == 0) {
1483 SetSignalStates(tile
, 0);
1484 SetHasSignals(tile
, false);
1485 SetSignalVariant(tile
, INVALID_TRACK
, SIG_ELECTRIC
); // remove any possible semaphores
1488 AddTrackToSignalBuffer(tile
, track
, GetTileOwner(tile
));
1489 YapfNotifyTrackLayoutChange(tile
, track
);
1490 if (v
!= nullptr) TryPathReserve(v
, false);
1492 MarkTileDirtyByTile(tile
);
1495 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_SIGNALS
]);
1499 * Remove signals on a stretch of track.
1500 * Stub for the unified signal builder/remover
1501 * @param flags operation to perform
1502 * @param tile start tile of drag
1503 * @param end_tile end tile of drag
1504 * @param track track-orientation
1505 * @param autofill fill beyond selected stretch?
1506 * @return the cost of this operation or an error
1507 * @see CmdSignalTrackHelper
1509 CommandCost
CmdRemoveSignalTrack(DoCommandFlag flags
, TileIndex tile
, TileIndex end_tile
, Track track
, bool autofill
)
1511 return CmdSignalTrackHelper(flags
, tile
, end_tile
, track
, SIGTYPE_NORMAL
, SIG_ELECTRIC
, false, true, autofill
, false, 1); // bit 5 is remove bit
1514 /** Update power of train under which is the railtype being converted */
1515 static Vehicle
*UpdateTrainPowerProc(Vehicle
*v
, void *data
)
1517 if (v
->type
!= VEH_TRAIN
) return nullptr;
1519 TrainList
*affected_trains
= static_cast<TrainList
*>(data
);
1520 include(*affected_trains
, Train::From(v
)->First());
1526 * Convert one rail type to the other. You can convert normal rail to
1527 * monorail/maglev easily or vice-versa.
1528 * @param flags operation to perform
1529 * @param tile end tile of rail conversion drag
1530 * @param area_start start tile of drag
1531 * @param totype new railtype to convert to.
1532 * @param diagonal build diagonally or not.
1533 * @return the cost of this operation or an error
1535 CommandCost
CmdConvertRail(DoCommandFlag flags
, TileIndex tile
, TileIndex area_start
, RailType totype
, bool diagonal
)
1537 TileIndex area_end
= tile
;
1539 if (!ValParamRailtype(totype
)) return CMD_ERROR
;
1540 if (area_start
>= MapSize()) return CMD_ERROR
;
1542 TrainList affected_trains
;
1544 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1545 CommandCost error
= CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK
); // by default, there is no track to convert.
1546 bool found_convertible_track
= false; // whether we actually did convert some track (see bug #7633)
1548 TileIterator
*iter
= diagonal
? (TileIterator
*)new DiagonalTileIterator(area_start
, area_end
) : new OrthogonalTileIterator(area_start
, area_end
);
1549 for (; (tile
= *iter
) != INVALID_TILE
; ++(*iter
)) {
1550 TileType tt
= GetTileType(tile
);
1552 /* Check if there is any track on tile */
1557 if (!HasStationRail(tile
)) continue;
1560 if (!IsLevelCrossing(tile
)) continue;
1561 if (RailNoLevelCrossings(totype
)) {
1562 error
.MakeError(STR_ERROR_CROSSING_DISALLOWED_RAIL
);
1566 case MP_TUNNELBRIDGE
:
1567 if (GetTunnelBridgeTransportType(tile
) != TRANSPORT_RAIL
) continue;
1572 /* Original railtype we are converting from */
1573 RailType type
= GetRailType(tile
);
1575 /* Converting to the same type or converting 'hidden' elrail -> rail */
1576 if (type
== totype
|| (_settings_game
.vehicle
.disable_elrails
&& totype
== RAILTYPE_RAIL
&& type
== RAILTYPE_ELECTRIC
)) continue;
1578 /* Trying to convert other's rail */
1579 CommandCost ret
= CheckTileOwnership(tile
);
1585 std::vector
<Train
*> vehicles_affected
;
1587 /* Vehicle on the tile when not converting Rail <-> ElRail
1588 * Tunnels and bridges have special check later */
1589 if (tt
!= MP_TUNNELBRIDGE
) {
1590 if (!IsCompatibleRail(type
, totype
)) {
1591 CommandCost ret
= IsPlainRailTile(tile
) ? EnsureNoTrainOnTrackBits(tile
, GetTrackBits(tile
)) : EnsureNoVehicleOnGround(tile
);
1597 if (flags
& DC_EXEC
) { // we can safely convert, too
1598 TrackBits reserved
= GetReservedTrackbits(tile
);
1600 while ((track
= RemoveFirstTrack(&reserved
)) != INVALID_TRACK
) {
1601 Train
*v
= GetTrainForReservation(tile
, track
);
1602 if (v
!= nullptr && !HasPowerOnRail(v
->railtype
, totype
)) {
1603 /* No power on new rail type, reroute. */
1604 FreeTrainTrackReservation(v
);
1605 vehicles_affected
.push_back(v
);
1609 /* Update the company infrastructure counters. */
1610 if (!IsRailStationTile(tile
) || !IsStationTileBlocked(tile
)) {
1611 Company
*c
= Company::Get(GetTileOwner(tile
));
1612 uint num_pieces
= IsLevelCrossingTile(tile
) ? LEVELCROSSING_TRACKBIT_FACTOR
: 1;
1613 if (IsPlainRailTile(tile
)) {
1614 TrackBits bits
= GetTrackBits(tile
);
1615 num_pieces
= CountBits(bits
);
1616 if (TracksOverlap(bits
)) num_pieces
*= num_pieces
;
1618 c
->infrastructure
.rail
[type
] -= num_pieces
;
1619 c
->infrastructure
.rail
[totype
] += num_pieces
;
1620 DirtyCompanyInfrastructureWindows(c
->index
);
1623 SetRailType(tile
, totype
);
1624 MarkTileDirtyByTile(tile
);
1625 /* update power of train on this tile */
1626 FindVehicleOnPos(tile
, &affected_trains
, &UpdateTrainPowerProc
);
1632 switch (GetRailTileType(tile
)) {
1633 case RAIL_TILE_DEPOT
:
1634 if (flags
& DC_EXEC
) {
1635 /* notify YAPF about the track layout change */
1636 YapfNotifyTrackLayoutChange(tile
, GetRailDepotTrack(tile
));
1638 /* Update build vehicle window related to this depot */
1639 InvalidateWindowData(WC_VEHICLE_DEPOT
, tile
);
1640 InvalidateWindowData(WC_BUILD_VEHICLE
, tile
);
1642 found_convertible_track
= true;
1643 cost
.AddCost(RailConvertCost(type
, totype
));
1646 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1647 if (flags
& DC_EXEC
) {
1648 /* notify YAPF about the track layout change */
1649 TrackBits tracks
= GetTrackBits(tile
);
1650 while (tracks
!= TRACK_BIT_NONE
) {
1651 YapfNotifyTrackLayoutChange(tile
, RemoveFirstTrack(&tracks
));
1654 found_convertible_track
= true;
1655 cost
.AddCost(RailConvertCost(type
, totype
) * CountBits(GetTrackBits(tile
)));
1660 case MP_TUNNELBRIDGE
: {
1661 TileIndex endtile
= GetOtherTunnelBridgeEnd(tile
);
1663 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1664 * it would cause assert because of different test and exec runs */
1665 if (endtile
< tile
) {
1667 if (DiagonalTileArea(area_start
, area_end
).Contains(endtile
)) continue;
1669 if (OrthogonalTileArea(area_start
, area_end
).Contains(endtile
)) continue;
1673 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1674 if (!IsCompatibleRail(GetRailType(tile
), totype
)) {
1675 CommandCost ret
= TunnelBridgeIsFree(tile
, endtile
);
1682 if (flags
& DC_EXEC
) {
1683 Track track
= DiagDirToDiagTrack(GetTunnelBridgeDirection(tile
));
1684 if (HasTunnelBridgeReservation(tile
)) {
1685 Train
*v
= GetTrainForReservation(tile
, track
);
1686 if (v
!= nullptr && !HasPowerOnRail(v
->railtype
, totype
)) {
1687 /* No power on new rail type, reroute. */
1688 FreeTrainTrackReservation(v
);
1689 vehicles_affected
.push_back(v
);
1693 /* Update the company infrastructure counters. */
1694 uint num_pieces
= (GetTunnelBridgeLength(tile
, endtile
) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
1695 Company
*c
= Company::Get(GetTileOwner(tile
));
1696 c
->infrastructure
.rail
[GetRailType(tile
)] -= num_pieces
;
1697 c
->infrastructure
.rail
[totype
] += num_pieces
;
1698 DirtyCompanyInfrastructureWindows(c
->index
);
1700 SetRailType(tile
, totype
);
1701 SetRailType(endtile
, totype
);
1703 FindVehicleOnPos(tile
, &affected_trains
, &UpdateTrainPowerProc
);
1704 FindVehicleOnPos(endtile
, &affected_trains
, &UpdateTrainPowerProc
);
1706 YapfNotifyTrackLayoutChange(tile
, track
);
1707 YapfNotifyTrackLayoutChange(endtile
, track
);
1709 if (IsBridge(tile
)) {
1710 MarkBridgeDirty(tile
);
1712 MarkTileDirtyByTile(tile
);
1713 MarkTileDirtyByTile(endtile
);
1717 found_convertible_track
= true;
1718 cost
.AddCost((GetTunnelBridgeLength(tile
, endtile
) + 2) * RailConvertCost(type
, totype
));
1722 default: // MP_STATION, MP_ROAD
1723 if (flags
& DC_EXEC
) {
1724 Track track
= ((tt
== MP_STATION
) ? GetRailStationTrack(tile
) : GetCrossingRailTrack(tile
));
1725 YapfNotifyTrackLayoutChange(tile
, track
);
1728 found_convertible_track
= true;
1729 cost
.AddCost(RailConvertCost(type
, totype
));
1733 for (uint i
= 0; i
< vehicles_affected
.size(); ++i
) {
1734 TryPathReserve(vehicles_affected
[i
], true);
1738 if (flags
& DC_EXEC
) {
1739 /* Railtype changed, update trains as when entering different track */
1740 for (Train
*v
: affected_trains
) {
1741 v
->ConsistChanged(CCF_TRACK
);
1746 return found_convertible_track
? cost
: error
;
1749 static CommandCost
RemoveTrainDepot(TileIndex tile
, DoCommandFlag flags
)
1751 if (_current_company
!= OWNER_WATER
) {
1752 CommandCost ret
= CheckTileOwnership(tile
);
1753 if (ret
.Failed()) return ret
;
1756 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1757 if (ret
.Failed()) return ret
;
1759 if (flags
& DC_EXEC
) {
1760 /* read variables before the depot is removed */
1761 DiagDirection dir
= GetRailDepotDirection(tile
);
1762 Owner owner
= GetTileOwner(tile
);
1765 if (HasDepotReservation(tile
)) {
1766 v
= GetTrainForReservation(tile
, DiagDirToDiagTrack(dir
));
1767 if (v
!= nullptr) FreeTrainTrackReservation(v
);
1770 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)]--;
1771 DirtyCompanyInfrastructureWindows(owner
);
1773 delete Depot::GetByTile(tile
);
1774 DoClearSquare(tile
);
1775 AddSideToSignalBuffer(tile
, dir
, owner
);
1776 YapfNotifyTrackLayoutChange(tile
, DiagDirToDiagTrack(dir
));
1777 if (v
!= nullptr) TryPathReserve(v
, true);
1780 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_DEPOT_TRAIN
]);
1783 static CommandCost
ClearTile_Track(TileIndex tile
, DoCommandFlag flags
)
1785 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1787 if (flags
& DC_AUTO
) {
1788 if (!IsTileOwner(tile
, _current_company
)) {
1789 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER
);
1792 if (IsPlainRail(tile
)) {
1793 return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
1795 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
1799 switch (GetRailTileType(tile
)) {
1800 case RAIL_TILE_SIGNALS
:
1801 case RAIL_TILE_NORMAL
: {
1802 Slope tileh
= GetTileSlope(tile
);
1803 /* Is there flat water on the lower halftile that gets cleared expensively? */
1804 bool water_ground
= (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh
));
1806 TrackBits tracks
= GetTrackBits(tile
);
1807 while (tracks
!= TRACK_BIT_NONE
) {
1808 Track track
= RemoveFirstTrack(&tracks
);
1809 CommandCost ret
= Command
<CMD_REMOVE_SINGLE_RAIL
>::Do(flags
, tile
, track
);
1810 if (ret
.Failed()) return ret
;
1814 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
1815 * Same holds for non-companies clearing the tile, e.g. disasters. */
1816 if (water_ground
&& !(flags
& DC_BANKRUPT
) && Company::IsValidID(_current_company
)) {
1817 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1818 if (ret
.Failed()) return ret
;
1820 /* The track was removed, and left a coast tile. Now also clear the water. */
1821 if (flags
& DC_EXEC
) {
1822 DoClearSquare(tile
);
1824 cost
.AddCost(_price
[PR_CLEAR_WATER
]);
1830 case RAIL_TILE_DEPOT
:
1831 return RemoveTrainDepot(tile
, flags
);
1839 * Get surface height in point (x,y)
1840 * On tiles with halftile foundations move (x,y) to a safe point wrt. track
1842 static uint
GetSaveSlopeZ(uint x
, uint y
, Track track
)
1845 case TRACK_UPPER
: x
&= ~0xF; y
&= ~0xF; break;
1846 case TRACK_LOWER
: x
|= 0xF; y
|= 0xF; break;
1847 case TRACK_LEFT
: x
|= 0xF; y
&= ~0xF; break;
1848 case TRACK_RIGHT
: x
&= ~0xF; y
|= 0xF; break;
1851 return GetSlopePixelZ(x
, y
);
1854 static void DrawSingleSignal(TileIndex tile
, const RailtypeInfo
*rti
, Track track
, SignalState condition
, SignalOffsets image
, uint pos
)
1857 switch (_settings_game
.construction
.train_signal_side
) {
1858 case 0: side
= false; break; // left
1859 case 2: side
= true; break; // right
1860 default: side
= _settings_game
.vehicle
.road_side
!= 0; break; // driving side
1862 static const Point SignalPositions
[2][12] = {
1863 { // Signals on the left side
1864 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1865 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
1866 /* LOWER LOWER X X Y Y */
1867 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1868 }, { // Signals on the right side
1869 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1870 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
1871 /* LOWER LOWER X X Y Y */
1872 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1876 uint x
= TileX(tile
) * TILE_SIZE
+ SignalPositions
[side
][pos
].x
;
1877 uint y
= TileY(tile
) * TILE_SIZE
+ SignalPositions
[side
][pos
].y
;
1879 SignalType type
= GetSignalType(tile
, track
);
1880 SignalVariant variant
= GetSignalVariant(tile
, track
);
1882 SpriteID sprite
= GetCustomSignalSprite(rti
, tile
, type
, variant
, condition
);
1886 /* Normal electric signals are stored in a different sprite block than all other signals. */
1887 sprite
= (type
== SIGTYPE_NORMAL
&& variant
== SIG_ELECTRIC
) ? SPR_ORIGINAL_SIGNALS_BASE
: SPR_SIGNALS_BASE
- 16;
1888 sprite
+= type
* 16 + variant
* 64 + image
* 2 + condition
+ (type
> SIGTYPE_LAST_NOPBS
? 64 : 0);
1891 AddSortableSpriteToDraw(sprite
, PAL_NONE
, x
, y
, 1, 1, BB_HEIGHT_UNDER_BRIDGE
, GetSaveSlopeZ(x
, y
, track
));
1894 static uint32 _drawtile_track_palette
;
1898 /** Offsets for drawing fences */
1899 struct FenceOffset
{
1900 Corner height_ref
; //!< Corner to use height offset from.
1901 int x_offs
; //!< Bounding box X offset.
1902 int y_offs
; //!< Bounding box Y offset.
1903 int x_size
; //!< Bounding box X size.
1904 int y_size
; //!< Bounding box Y size.
1907 /** Offsets for drawing fences */
1908 static FenceOffset _fence_offsets
[] = {
1909 { CORNER_INVALID
, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
1910 { CORNER_INVALID
, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
1911 { CORNER_W
, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
1912 { CORNER_N
, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
1913 { CORNER_INVALID
, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
1914 { CORNER_INVALID
, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
1915 { CORNER_INVALID
, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
1916 { CORNER_INVALID
, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
1917 { CORNER_INVALID
, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
1918 { CORNER_INVALID
, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
1919 { CORNER_E
, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
1920 { CORNER_S
, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
1921 { CORNER_INVALID
, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
1922 { CORNER_INVALID
, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
1923 { CORNER_INVALID
, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
1924 { CORNER_INVALID
, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
1928 * Draw a track fence.
1929 * @param ti Tile drawing information.
1930 * @param base_image First fence sprite.
1931 * @param num_sprites Number of fence sprites.
1932 * @param rfo Fence to draw.
1934 static void DrawTrackFence(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
, RailFenceOffset rfo
)
1937 if (_fence_offsets
[rfo
].height_ref
!= CORNER_INVALID
) {
1938 z
+= GetSlopePixelZInCorner(RemoveHalftileSlope(ti
->tileh
), _fence_offsets
[rfo
].height_ref
);
1940 AddSortableSpriteToDraw(base_image
+ (rfo
% num_sprites
), _drawtile_track_palette
,
1941 ti
->x
+ _fence_offsets
[rfo
].x_offs
,
1942 ti
->y
+ _fence_offsets
[rfo
].y_offs
,
1943 _fence_offsets
[rfo
].x_size
,
1944 _fence_offsets
[rfo
].y_size
,
1949 * Draw fence at NW border matching the tile slope.
1951 static void DrawTrackFence_NW(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
1953 RailFenceOffset rfo
= RFO_FLAT_X_NW
;
1954 if (ti
->tileh
& SLOPE_NW
) rfo
= (ti
->tileh
& SLOPE_W
) ? RFO_SLOPE_SW_NW
: RFO_SLOPE_NE_NW
;
1955 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
1959 * Draw fence at SE border matching the tile slope.
1961 static void DrawTrackFence_SE(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
1963 RailFenceOffset rfo
= RFO_FLAT_X_SE
;
1964 if (ti
->tileh
& SLOPE_SE
) rfo
= (ti
->tileh
& SLOPE_S
) ? RFO_SLOPE_SW_SE
: RFO_SLOPE_NE_SE
;
1965 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
1969 * Draw fence at NE border matching the tile slope.
1971 static void DrawTrackFence_NE(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
1973 RailFenceOffset rfo
= RFO_FLAT_Y_NE
;
1974 if (ti
->tileh
& SLOPE_NE
) rfo
= (ti
->tileh
& SLOPE_E
) ? RFO_SLOPE_SE_NE
: RFO_SLOPE_NW_NE
;
1975 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
1979 * Draw fence at SW border matching the tile slope.
1981 static void DrawTrackFence_SW(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
1983 RailFenceOffset rfo
= RFO_FLAT_Y_SW
;
1984 if (ti
->tileh
& SLOPE_SW
) rfo
= (ti
->tileh
& SLOPE_S
) ? RFO_SLOPE_SE_SW
: RFO_SLOPE_NW_SW
;
1985 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
1989 * Draw track fences.
1990 * @param ti Tile drawing information.
1991 * @param rti Rail type information.
1993 static void DrawTrackDetails(const TileInfo
*ti
, const RailtypeInfo
*rti
)
1995 /* Base sprite for track fences.
1996 * Note: Halftile slopes only have fences on the upper part. */
1997 uint num_sprites
= 0;
1998 SpriteID base_image
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_FENCES
, IsHalftileSlope(ti
->tileh
) ? TCX_UPPER_HALFTILE
: TCX_NORMAL
, &num_sprites
);
1999 if (base_image
== 0) {
2000 base_image
= SPR_TRACK_FENCE_FLAT_X
;
2004 assert(num_sprites
> 0);
2006 switch (GetRailGroundType(ti
->tile
)) {
2007 case RAIL_GROUND_FENCE_NW
: DrawTrackFence_NW(ti
, base_image
, num_sprites
); break;
2008 case RAIL_GROUND_FENCE_SE
: DrawTrackFence_SE(ti
, base_image
, num_sprites
); break;
2009 case RAIL_GROUND_FENCE_SENW
: DrawTrackFence_NW(ti
, base_image
, num_sprites
);
2010 DrawTrackFence_SE(ti
, base_image
, num_sprites
); break;
2011 case RAIL_GROUND_FENCE_NE
: DrawTrackFence_NE(ti
, base_image
, num_sprites
); break;
2012 case RAIL_GROUND_FENCE_SW
: DrawTrackFence_SW(ti
, base_image
, num_sprites
); break;
2013 case RAIL_GROUND_FENCE_NESW
: DrawTrackFence_NE(ti
, base_image
, num_sprites
);
2014 DrawTrackFence_SW(ti
, base_image
, num_sprites
); break;
2015 case RAIL_GROUND_FENCE_VERT1
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LEFT
); break;
2016 case RAIL_GROUND_FENCE_VERT2
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_RIGHT
); break;
2017 case RAIL_GROUND_FENCE_HORIZ1
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_UPPER
); break;
2018 case RAIL_GROUND_FENCE_HORIZ2
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LOWER
); break;
2019 case RAIL_GROUND_WATER
: {
2020 Corner track_corner
;
2021 if (IsHalftileSlope(ti
->tileh
)) {
2022 /* Steep slope or one-corner-raised slope with halftile foundation */
2023 track_corner
= GetHalftileSlopeCorner(ti
->tileh
);
2025 /* Three-corner-raised slope */
2026 track_corner
= OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti
->tileh
)));
2028 switch (track_corner
) {
2029 case CORNER_W
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LEFT
); break;
2030 case CORNER_S
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LOWER
); break;
2031 case CORNER_E
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_RIGHT
); break;
2032 case CORNER_N
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_UPPER
); break;
2033 default: NOT_REACHED();
2041 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2042 static const int INF
= 1000; // big number compared to tilesprite size
2043 static const SubSprite _halftile_sub_sprite
[4] = {
2044 { -INF
, -INF
, 32 - 33, INF
}, // CORNER_W, clip 33 pixels from right
2045 { -INF
, 0 + 7, INF
, INF
}, // CORNER_S, clip 7 pixels from top
2046 { -31 + 33, -INF
, INF
, INF
}, // CORNER_E, clip 33 pixels from left
2047 { -INF
, -INF
, INF
, 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2050 static inline void DrawTrackSprite(SpriteID sprite
, PaletteID pal
, const TileInfo
*ti
, Slope s
)
2052 DrawGroundSprite(sprite
, pal
, nullptr, 0, (ti
->tileh
& s
) ? -8 : 0);
2055 static void DrawTrackBitsOverlay(TileInfo
*ti
, TrackBits track
, const RailtypeInfo
*rti
)
2057 RailGroundType rgt
= GetRailGroundType(ti
->tile
);
2058 Foundation f
= GetRailFoundation(ti
->tileh
, track
);
2059 Corner halftile_corner
= CORNER_INVALID
;
2061 if (IsNonContinuousFoundation(f
)) {
2062 /* Save halftile corner */
2063 halftile_corner
= (f
== FOUNDATION_STEEP_BOTH
? GetHighestSlopeCorner(ti
->tileh
) : GetHalftileFoundationCorner(f
));
2064 /* Draw lower part first */
2065 track
&= ~CornerToTrackBits(halftile_corner
);
2066 f
= (f
== FOUNDATION_STEEP_BOTH
? FOUNDATION_STEEP_LOWER
: FOUNDATION_NONE
);
2069 DrawFoundation(ti
, f
);
2070 /* DrawFoundation modifies ti */
2073 if (rgt
== RAIL_GROUND_WATER
) {
2074 if (track
!= TRACK_BIT_NONE
|| IsSteepSlope(ti
->tileh
)) {
2075 /* three-corner-raised slope or steep slope with track on upper part */
2076 DrawShoreTile(ti
->tileh
);
2078 /* single-corner-raised slope with track on upper part */
2079 DrawGroundSprite(SPR_FLAT_WATER_TILE
, PAL_NONE
);
2085 case RAIL_GROUND_BARREN
: image
= SPR_FLAT_BARE_LAND
; break;
2086 case RAIL_GROUND_ICE_DESERT
: image
= SPR_FLAT_SNOW_DESERT_TILE
; break;
2087 default: image
= SPR_FLAT_GRASS_TILE
; break;
2090 image
+= SlopeToSpriteOffset(ti
->tileh
);
2092 DrawGroundSprite(image
, PAL_NONE
);
2095 bool no_combine
= ti
->tileh
== SLOPE_FLAT
&& HasBit(rti
->flags
, RTF_NO_SPRITE_COMBINE
);
2096 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
2097 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, no_combine
? RTSG_GROUND_COMPLETE
: RTSG_GROUND
);
2098 TrackBits pbs
= _settings_client
.gui
.show_track_reservation
? GetRailReservationTrackBits(ti
->tile
) : TRACK_BIT_NONE
;
2100 if (track
== TRACK_BIT_NONE
) {
2101 /* Half-tile foundation, no track here? */
2102 } else if (no_combine
) {
2103 /* Use trackbits as direct index from ground sprite, subtract 1
2104 * because there is no sprite for no bits. */
2105 DrawGroundSprite(ground
+ track
- 1, PAL_NONE
);
2107 /* Draw reserved track bits */
2108 if (pbs
& TRACK_BIT_X
) DrawGroundSprite(overlay
+ RTO_X
, PALETTE_CRASH
);
2109 if (pbs
& TRACK_BIT_Y
) DrawGroundSprite(overlay
+ RTO_Y
, PALETTE_CRASH
);
2110 if (pbs
& TRACK_BIT_UPPER
) DrawTrackSprite(overlay
+ RTO_N
, PALETTE_CRASH
, ti
, SLOPE_N
);
2111 if (pbs
& TRACK_BIT_LOWER
) DrawTrackSprite(overlay
+ RTO_S
, PALETTE_CRASH
, ti
, SLOPE_S
);
2112 if (pbs
& TRACK_BIT_RIGHT
) DrawTrackSprite(overlay
+ RTO_E
, PALETTE_CRASH
, ti
, SLOPE_E
);
2113 if (pbs
& TRACK_BIT_LEFT
) DrawTrackSprite(overlay
+ RTO_W
, PALETTE_CRASH
, ti
, SLOPE_W
);
2114 } else if (ti
->tileh
== SLOPE_NW
&& track
== TRACK_BIT_Y
) {
2115 DrawGroundSprite(ground
+ RTO_SLOPE_NW
, PAL_NONE
);
2116 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_NW
, PALETTE_CRASH
);
2117 } else if (ti
->tileh
== SLOPE_NE
&& track
== TRACK_BIT_X
) {
2118 DrawGroundSprite(ground
+ RTO_SLOPE_NE
, PAL_NONE
);
2119 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_NE
, PALETTE_CRASH
);
2120 } else if (ti
->tileh
== SLOPE_SE
&& track
== TRACK_BIT_Y
) {
2121 DrawGroundSprite(ground
+ RTO_SLOPE_SE
, PAL_NONE
);
2122 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_SE
, PALETTE_CRASH
);
2123 } else if (ti
->tileh
== SLOPE_SW
&& track
== TRACK_BIT_X
) {
2124 DrawGroundSprite(ground
+ RTO_SLOPE_SW
, PAL_NONE
);
2125 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_SW
, PALETTE_CRASH
);
2128 /* Draw single ground sprite when not overlapping. No track overlay
2129 * is necessary for these sprites. */
2130 case TRACK_BIT_X
: DrawGroundSprite(ground
+ RTO_X
, PAL_NONE
); break;
2131 case TRACK_BIT_Y
: DrawGroundSprite(ground
+ RTO_Y
, PAL_NONE
); break;
2132 case TRACK_BIT_UPPER
: DrawTrackSprite(ground
+ RTO_N
, PAL_NONE
, ti
, SLOPE_N
); break;
2133 case TRACK_BIT_LOWER
: DrawTrackSprite(ground
+ RTO_S
, PAL_NONE
, ti
, SLOPE_S
); break;
2134 case TRACK_BIT_RIGHT
: DrawTrackSprite(ground
+ RTO_E
, PAL_NONE
, ti
, SLOPE_E
); break;
2135 case TRACK_BIT_LEFT
: DrawTrackSprite(ground
+ RTO_W
, PAL_NONE
, ti
, SLOPE_W
); break;
2136 case TRACK_BIT_CROSS
: DrawGroundSprite(ground
+ RTO_CROSSING_XY
, PAL_NONE
); break;
2137 case TRACK_BIT_HORZ
: DrawTrackSprite(ground
+ RTO_N
, PAL_NONE
, ti
, SLOPE_N
);
2138 DrawTrackSprite(ground
+ RTO_S
, PAL_NONE
, ti
, SLOPE_S
); break;
2139 case TRACK_BIT_VERT
: DrawTrackSprite(ground
+ RTO_E
, PAL_NONE
, ti
, SLOPE_E
);
2140 DrawTrackSprite(ground
+ RTO_W
, PAL_NONE
, ti
, SLOPE_W
); break;
2143 /* We're drawing a junction tile */
2144 if ((track
& TRACK_BIT_3WAY_NE
) == 0) {
2145 DrawGroundSprite(ground
+ RTO_JUNCTION_SW
, PAL_NONE
);
2146 } else if ((track
& TRACK_BIT_3WAY_SW
) == 0) {
2147 DrawGroundSprite(ground
+ RTO_JUNCTION_NE
, PAL_NONE
);
2148 } else if ((track
& TRACK_BIT_3WAY_NW
) == 0) {
2149 DrawGroundSprite(ground
+ RTO_JUNCTION_SE
, PAL_NONE
);
2150 } else if ((track
& TRACK_BIT_3WAY_SE
) == 0) {
2151 DrawGroundSprite(ground
+ RTO_JUNCTION_NW
, PAL_NONE
);
2153 DrawGroundSprite(ground
+ RTO_JUNCTION_NSEW
, PAL_NONE
);
2156 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2159 /* Draw regular track bits */
2160 if (track
& TRACK_BIT_X
) DrawGroundSprite(overlay
+ RTO_X
, PAL_NONE
);
2161 if (track
& TRACK_BIT_Y
) DrawGroundSprite(overlay
+ RTO_Y
, PAL_NONE
);
2162 if (track
& TRACK_BIT_UPPER
) DrawGroundSprite(overlay
+ RTO_N
, PAL_NONE
);
2163 if (track
& TRACK_BIT_LOWER
) DrawGroundSprite(overlay
+ RTO_S
, PAL_NONE
);
2164 if (track
& TRACK_BIT_RIGHT
) DrawGroundSprite(overlay
+ RTO_E
, PAL_NONE
);
2165 if (track
& TRACK_BIT_LEFT
) DrawGroundSprite(overlay
+ RTO_W
, PAL_NONE
);
2168 /* Draw reserved track bits */
2169 if (pbs
& TRACK_BIT_X
) DrawGroundSprite(overlay
+ RTO_X
, PALETTE_CRASH
);
2170 if (pbs
& TRACK_BIT_Y
) DrawGroundSprite(overlay
+ RTO_Y
, PALETTE_CRASH
);
2171 if (pbs
& TRACK_BIT_UPPER
) DrawTrackSprite(overlay
+ RTO_N
, PALETTE_CRASH
, ti
, SLOPE_N
);
2172 if (pbs
& TRACK_BIT_LOWER
) DrawTrackSprite(overlay
+ RTO_S
, PALETTE_CRASH
, ti
, SLOPE_S
);
2173 if (pbs
& TRACK_BIT_RIGHT
) DrawTrackSprite(overlay
+ RTO_E
, PALETTE_CRASH
, ti
, SLOPE_E
);
2174 if (pbs
& TRACK_BIT_LEFT
) DrawTrackSprite(overlay
+ RTO_W
, PALETTE_CRASH
, ti
, SLOPE_W
);
2177 if (IsValidCorner(halftile_corner
)) {
2178 DrawFoundation(ti
, HalftileFoundation(halftile_corner
));
2179 overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
, TCX_UPPER_HALFTILE
);
2180 ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
, TCX_UPPER_HALFTILE
);
2182 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2183 Slope fake_slope
= SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner
));
2187 case RAIL_GROUND_BARREN
: image
= SPR_FLAT_BARE_LAND
; break;
2188 case RAIL_GROUND_ICE_DESERT
:
2189 case RAIL_GROUND_HALF_SNOW
: image
= SPR_FLAT_SNOW_DESERT_TILE
; break;
2190 default: image
= SPR_FLAT_GRASS_TILE
; break;
2193 image
+= SlopeToSpriteOffset(fake_slope
);
2195 DrawGroundSprite(image
, PAL_NONE
, &(_halftile_sub_sprite
[halftile_corner
]));
2197 track
= CornerToTrackBits(halftile_corner
);
2201 default: NOT_REACHED();
2202 case TRACK_BIT_UPPER
: offset
= RTO_N
; break;
2203 case TRACK_BIT_LOWER
: offset
= RTO_S
; break;
2204 case TRACK_BIT_RIGHT
: offset
= RTO_E
; break;
2205 case TRACK_BIT_LEFT
: offset
= RTO_W
; break;
2208 DrawTrackSprite(ground
+ offset
, PAL_NONE
, ti
, fake_slope
);
2209 if (_settings_client
.gui
.show_track_reservation
&& HasReservedTracks(ti
->tile
, track
)) {
2210 DrawTrackSprite(overlay
+ offset
, PALETTE_CRASH
, ti
, fake_slope
);
2216 * Draw ground sprite and track bits
2217 * @param ti TileInfo
2218 * @param track TrackBits to draw
2220 static void DrawTrackBits(TileInfo
*ti
, TrackBits track
)
2222 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2224 if (rti
->UsesOverlay()) {
2225 DrawTrackBitsOverlay(ti
, track
, rti
);
2229 RailGroundType rgt
= GetRailGroundType(ti
->tile
);
2230 Foundation f
= GetRailFoundation(ti
->tileh
, track
);
2231 Corner halftile_corner
= CORNER_INVALID
;
2233 if (IsNonContinuousFoundation(f
)) {
2234 /* Save halftile corner */
2235 halftile_corner
= (f
== FOUNDATION_STEEP_BOTH
? GetHighestSlopeCorner(ti
->tileh
) : GetHalftileFoundationCorner(f
));
2236 /* Draw lower part first */
2237 track
&= ~CornerToTrackBits(halftile_corner
);
2238 f
= (f
== FOUNDATION_STEEP_BOTH
? FOUNDATION_STEEP_LOWER
: FOUNDATION_NONE
);
2241 DrawFoundation(ti
, f
);
2242 /* DrawFoundation modifies ti */
2245 PaletteID pal
= PAL_NONE
;
2246 const SubSprite
*sub
= nullptr;
2247 bool junction
= false;
2249 /* Select the sprite to use. */
2251 /* Clear ground (only track on halftile foundation) */
2252 if (rgt
== RAIL_GROUND_WATER
) {
2253 if (IsSteepSlope(ti
->tileh
)) {
2254 DrawShoreTile(ti
->tileh
);
2257 image
= SPR_FLAT_WATER_TILE
;
2261 case RAIL_GROUND_BARREN
: image
= SPR_FLAT_BARE_LAND
; break;
2262 case RAIL_GROUND_ICE_DESERT
: image
= SPR_FLAT_SNOW_DESERT_TILE
; break;
2263 default: image
= SPR_FLAT_GRASS_TILE
; break;
2265 image
+= SlopeToSpriteOffset(ti
->tileh
);
2268 if (ti
->tileh
!= SLOPE_FLAT
) {
2269 /* track on non-flat ground */
2270 image
= _track_sloped_sprites
[ti
->tileh
- 1] + rti
->base_sprites
.track_y
;
2272 /* track on flat ground */
2274 /* single track, select combined track + ground sprite*/
2275 case TRACK_BIT_Y
: image
= rti
->base_sprites
.track_y
; break;
2276 case TRACK_BIT_X
: image
= rti
->base_sprites
.track_y
+ 1; break;
2277 case TRACK_BIT_UPPER
: image
= rti
->base_sprites
.track_y
+ 2; break;
2278 case TRACK_BIT_LOWER
: image
= rti
->base_sprites
.track_y
+ 3; break;
2279 case TRACK_BIT_RIGHT
: image
= rti
->base_sprites
.track_y
+ 4; break;
2280 case TRACK_BIT_LEFT
: image
= rti
->base_sprites
.track_y
+ 5; break;
2281 case TRACK_BIT_CROSS
: image
= rti
->base_sprites
.track_y
+ 6; break;
2283 /* double diagonal track, select combined track + ground sprite*/
2284 case TRACK_BIT_HORZ
: image
= rti
->base_sprites
.track_ns
; break;
2285 case TRACK_BIT_VERT
: image
= rti
->base_sprites
.track_ns
+ 1; break;
2287 /* junction, select only ground sprite, handle track sprite later */
2290 if ((track
& TRACK_BIT_3WAY_NE
) == 0) { image
= rti
->base_sprites
.ground
; break; }
2291 if ((track
& TRACK_BIT_3WAY_SW
) == 0) { image
= rti
->base_sprites
.ground
+ 1; break; }
2292 if ((track
& TRACK_BIT_3WAY_NW
) == 0) { image
= rti
->base_sprites
.ground
+ 2; break; }
2293 if ((track
& TRACK_BIT_3WAY_SE
) == 0) { image
= rti
->base_sprites
.ground
+ 3; break; }
2294 image
= rti
->base_sprites
.ground
+ 4;
2300 case RAIL_GROUND_BARREN
: pal
= PALETTE_TO_BARE_LAND
; break;
2301 case RAIL_GROUND_ICE_DESERT
: image
+= rti
->snow_offset
; break;
2302 case RAIL_GROUND_WATER
: {
2303 /* three-corner-raised slope */
2304 DrawShoreTile(ti
->tileh
);
2305 Corner track_corner
= OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti
->tileh
)));
2306 sub
= &(_halftile_sub_sprite
[track_corner
]);
2313 if (image
!= 0) DrawGroundSprite(image
, pal
, sub
);
2315 /* Draw track pieces individually for junction tiles */
2317 if (track
& TRACK_BIT_X
) DrawGroundSprite(rti
->base_sprites
.single_x
, PAL_NONE
);
2318 if (track
& TRACK_BIT_Y
) DrawGroundSprite(rti
->base_sprites
.single_y
, PAL_NONE
);
2319 if (track
& TRACK_BIT_UPPER
) DrawGroundSprite(rti
->base_sprites
.single_n
, PAL_NONE
);
2320 if (track
& TRACK_BIT_LOWER
) DrawGroundSprite(rti
->base_sprites
.single_s
, PAL_NONE
);
2321 if (track
& TRACK_BIT_LEFT
) DrawGroundSprite(rti
->base_sprites
.single_w
, PAL_NONE
);
2322 if (track
& TRACK_BIT_RIGHT
) DrawGroundSprite(rti
->base_sprites
.single_e
, PAL_NONE
);
2325 /* PBS debugging, draw reserved tracks darker */
2326 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
) {
2327 /* Get reservation, but mask track on halftile slope */
2328 TrackBits pbs
= GetRailReservationTrackBits(ti
->tile
) & track
;
2329 if (pbs
& TRACK_BIT_X
) {
2330 if (ti
->tileh
== SLOPE_FLAT
|| ti
->tileh
== SLOPE_ELEVATED
) {
2331 DrawGroundSprite(rti
->base_sprites
.single_x
, PALETTE_CRASH
);
2333 DrawGroundSprite(_track_sloped_sprites
[ti
->tileh
- 1] + rti
->base_sprites
.single_sloped
- 20, PALETTE_CRASH
);
2336 if (pbs
& TRACK_BIT_Y
) {
2337 if (ti
->tileh
== SLOPE_FLAT
|| ti
->tileh
== SLOPE_ELEVATED
) {
2338 DrawGroundSprite(rti
->base_sprites
.single_y
, PALETTE_CRASH
);
2340 DrawGroundSprite(_track_sloped_sprites
[ti
->tileh
- 1] + rti
->base_sprites
.single_sloped
- 20, PALETTE_CRASH
);
2343 if (pbs
& TRACK_BIT_UPPER
) DrawGroundSprite(rti
->base_sprites
.single_n
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_N
? -(int)TILE_HEIGHT
: 0);
2344 if (pbs
& TRACK_BIT_LOWER
) DrawGroundSprite(rti
->base_sprites
.single_s
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_S
? -(int)TILE_HEIGHT
: 0);
2345 if (pbs
& TRACK_BIT_LEFT
) DrawGroundSprite(rti
->base_sprites
.single_w
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_W
? -(int)TILE_HEIGHT
: 0);
2346 if (pbs
& TRACK_BIT_RIGHT
) DrawGroundSprite(rti
->base_sprites
.single_e
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_E
? -(int)TILE_HEIGHT
: 0);
2349 if (IsValidCorner(halftile_corner
)) {
2350 DrawFoundation(ti
, HalftileFoundation(halftile_corner
));
2352 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2353 Slope fake_slope
= SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner
));
2354 image
= _track_sloped_sprites
[fake_slope
- 1] + rti
->base_sprites
.track_y
;
2357 case RAIL_GROUND_BARREN
: pal
= PALETTE_TO_BARE_LAND
; break;
2358 case RAIL_GROUND_ICE_DESERT
:
2359 case RAIL_GROUND_HALF_SNOW
: image
+= rti
->snow_offset
; break; // higher part has snow in this case too
2362 DrawGroundSprite(image
, pal
, &(_halftile_sub_sprite
[halftile_corner
]));
2364 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasReservedTracks(ti
->tile
, CornerToTrackBits(halftile_corner
))) {
2365 static const byte _corner_to_track_sprite
[] = {3, 1, 2, 0};
2366 DrawGroundSprite(_corner_to_track_sprite
[halftile_corner
] + rti
->base_sprites
.single_n
, PALETTE_CRASH
, nullptr, 0, -(int)TILE_HEIGHT
);
2371 static void DrawSignals(TileIndex tile
, TrackBits rails
, const RailtypeInfo
*rti
)
2373 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2375 if (!(rails
& TRACK_BIT_Y
)) {
2376 if (!(rails
& TRACK_BIT_X
)) {
2377 if (rails
& TRACK_BIT_LEFT
) {
2378 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH
, 0, TRACK_LEFT
);
2379 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH
, 1, TRACK_LEFT
);
2381 if (rails
& TRACK_BIT_RIGHT
) {
2382 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH
, 2, TRACK_RIGHT
);
2383 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH
, 3, TRACK_RIGHT
);
2385 if (rails
& TRACK_BIT_UPPER
) {
2386 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST
, 4, TRACK_UPPER
);
2387 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST
, 5, TRACK_UPPER
);
2389 if (rails
& TRACK_BIT_LOWER
) {
2390 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST
, 6, TRACK_LOWER
);
2391 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST
, 7, TRACK_LOWER
);
2394 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST
, 8, TRACK_X
);
2395 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST
, 9, TRACK_X
);
2398 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST
, 10, TRACK_Y
);
2399 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST
, 11, TRACK_Y
);
2403 static void DrawTile_Track(TileInfo
*ti
)
2405 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2407 _drawtile_track_palette
= COMPANY_SPRITE_COLOUR(GetTileOwner(ti
->tile
));
2409 if (IsPlainRail(ti
->tile
)) {
2410 TrackBits rails
= GetTrackBits(ti
->tile
);
2412 DrawTrackBits(ti
, rails
);
2414 if (HasBit(_display_opt
, DO_FULL_DETAIL
)) DrawTrackDetails(ti
, rti
);
2416 if (HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
2418 if (HasSignals(ti
->tile
)) DrawSignals(ti
->tile
, rails
, rti
);
2421 const DrawTileSprites
*dts
;
2422 PaletteID pal
= PAL_NONE
;
2423 SpriteID relocation
;
2425 if (ti
->tileh
!= SLOPE_FLAT
) DrawFoundation(ti
, FOUNDATION_LEVELED
);
2427 if (IsInvisibilitySet(TO_BUILDINGS
)) {
2428 /* Draw rail instead of depot */
2429 dts
= &_depot_invisible_gfx_table
[GetRailDepotDirection(ti
->tile
)];
2431 dts
= &_depot_gfx_table
[GetRailDepotDirection(ti
->tile
)];
2435 if (rti
->UsesOverlay()) {
2436 image
= SPR_FLAT_GRASS_TILE
;
2438 image
= dts
->ground
.sprite
;
2439 if (image
!= SPR_FLAT_GRASS_TILE
) image
+= rti
->GetRailtypeSpriteOffset();
2442 /* Adjust ground tile for desert and snow. */
2443 if (IsSnowRailGround(ti
->tile
)) {
2444 if (image
!= SPR_FLAT_GRASS_TILE
) {
2445 image
+= rti
->snow_offset
; // tile with tracks
2447 image
= SPR_FLAT_SNOW_DESERT_TILE
; // flat ground
2451 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, _drawtile_track_palette
));
2453 if (rti
->UsesOverlay()) {
2454 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
2456 switch (GetRailDepotDirection(ti
->tile
)) {
2458 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2461 DrawGroundSprite(ground
+ RTO_X
, PAL_NONE
);
2464 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2467 DrawGroundSprite(ground
+ RTO_Y
, PAL_NONE
);
2473 if (_settings_client
.gui
.show_track_reservation
&& HasDepotReservation(ti
->tile
)) {
2474 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
2476 switch (GetRailDepotDirection(ti
->tile
)) {
2478 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2481 DrawGroundSprite(overlay
+ RTO_X
, PALETTE_CRASH
);
2484 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2487 DrawGroundSprite(overlay
+ RTO_Y
, PALETTE_CRASH
);
2494 /* PBS debugging, draw reserved tracks darker */
2495 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasDepotReservation(ti
->tile
)) {
2496 switch (GetRailDepotDirection(ti
->tile
)) {
2498 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2501 DrawGroundSprite(rti
->base_sprites
.single_x
, PALETTE_CRASH
);
2504 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2507 DrawGroundSprite(rti
->base_sprites
.single_y
, PALETTE_CRASH
);
2514 int depot_sprite
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_DEPOT
);
2515 relocation
= depot_sprite
!= 0 ? depot_sprite
- SPR_RAIL_DEPOT_SE_1
: rti
->GetRailtypeSpriteOffset();
2517 if (HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
2519 DrawRailTileSeq(ti
, dts
, TO_BUILDINGS
, relocation
, 0, _drawtile_track_palette
);
2521 DrawBridgeMiddle(ti
);
2524 void DrawTrainDepotSprite(int x
, int y
, int dir
, RailType railtype
)
2526 const DrawTileSprites
*dts
= &_depot_gfx_table
[dir
];
2527 const RailtypeInfo
*rti
= GetRailTypeInfo(railtype
);
2528 SpriteID image
= rti
->UsesOverlay() ? SPR_FLAT_GRASS_TILE
: dts
->ground
.sprite
;
2529 uint32 offset
= rti
->GetRailtypeSpriteOffset();
2531 if (image
!= SPR_FLAT_GRASS_TILE
) image
+= offset
;
2532 PaletteID palette
= COMPANY_SPRITE_COLOUR(_local_company
);
2534 DrawSprite(image
, PAL_NONE
, x
, y
);
2536 if (rti
->UsesOverlay()) {
2537 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
2540 case DIAGDIR_SW
: DrawSprite(ground
+ RTO_X
, PAL_NONE
, x
, y
); break;
2541 case DIAGDIR_SE
: DrawSprite(ground
+ RTO_Y
, PAL_NONE
, x
, y
); break;
2545 int depot_sprite
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_DEPOT
);
2546 if (depot_sprite
!= 0) offset
= depot_sprite
- SPR_RAIL_DEPOT_SE_1
;
2548 DrawRailTileSeqInGUI(x
, y
, dts
, offset
, 0, palette
);
2551 static int GetSlopePixelZ_Track(TileIndex tile
, uint x
, uint y
)
2553 if (IsPlainRail(tile
)) {
2555 Slope tileh
= GetTilePixelSlope(tile
, &z
);
2556 if (tileh
== SLOPE_FLAT
) return z
;
2558 z
+= ApplyPixelFoundationToSlope(GetRailFoundation(tileh
, GetTrackBits(tile
)), &tileh
);
2559 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
2561 return GetTileMaxPixelZ(tile
);
2565 static Foundation
GetFoundation_Track(TileIndex tile
, Slope tileh
)
2567 return IsPlainRail(tile
) ? GetRailFoundation(tileh
, GetTrackBits(tile
)) : FlatteningFoundation(tileh
);
2570 static void TileLoop_Track(TileIndex tile
)
2572 RailGroundType old_ground
= GetRailGroundType(tile
);
2573 RailGroundType new_ground
;
2575 if (old_ground
== RAIL_GROUND_WATER
) {
2576 TileLoop_Water(tile
);
2580 switch (_settings_game
.game_creation
.landscape
) {
2583 Slope slope
= GetTileSlope(tile
, &z
);
2586 /* for non-flat track, use lower part of track
2587 * in other cases, use the highest part with track */
2588 if (IsPlainRail(tile
)) {
2589 TrackBits track
= GetTrackBits(tile
);
2590 Foundation f
= GetRailFoundation(slope
, track
);
2593 case FOUNDATION_NONE
:
2594 /* no foundation - is the track on the upper side of three corners raised tile? */
2595 if (IsSlopeWithThreeCornersRaised(slope
)) z
++;
2598 case FOUNDATION_INCLINED_X
:
2599 case FOUNDATION_INCLINED_Y
:
2600 /* sloped track - is it on a steep slope? */
2601 if (IsSteepSlope(slope
)) z
++;
2604 case FOUNDATION_STEEP_LOWER
:
2605 /* only lower part of steep slope */
2610 /* if it is a steep slope, then there is a track on higher part */
2611 if (IsSteepSlope(slope
)) z
++;
2616 half
= IsInsideMM(f
, FOUNDATION_STEEP_BOTH
, FOUNDATION_HALFTILE_N
+ 1);
2618 /* is the depot on a non-flat tile? */
2619 if (slope
!= SLOPE_FLAT
) z
++;
2622 /* 'z' is now the lowest part of the highest track bit -
2623 * for sloped track, it is 'z' of lower part
2624 * for two track bits, it is 'z' of higher track bit
2625 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2626 if (z
> GetSnowLine()) {
2627 if (half
&& z
- GetSnowLine() == 1) {
2628 /* track on non-continuous foundation, lower part is not under snow */
2629 new_ground
= RAIL_GROUND_HALF_SNOW
;
2631 new_ground
= RAIL_GROUND_ICE_DESERT
;
2639 if (GetTropicZone(tile
) == TROPICZONE_DESERT
) {
2640 new_ground
= RAIL_GROUND_ICE_DESERT
;
2646 new_ground
= RAIL_GROUND_GRASS
;
2648 if (IsPlainRail(tile
) && old_ground
!= RAIL_GROUND_BARREN
) { // wait until bottom is green
2649 /* determine direction of fence */
2650 TrackBits rail
= GetTrackBits(tile
);
2652 Owner owner
= GetTileOwner(tile
);
2655 for (DiagDirection d
= DIAGDIR_BEGIN
; d
< DIAGDIR_END
; d
++) {
2656 static const TrackBits dir_to_trackbits
[DIAGDIR_END
] = {TRACK_BIT_3WAY_NE
, TRACK_BIT_3WAY_SE
, TRACK_BIT_3WAY_SW
, TRACK_BIT_3WAY_NW
};
2658 /* Track bit on this edge => no fence. */
2659 if ((rail
& dir_to_trackbits
[d
]) != TRACK_BIT_NONE
) continue;
2661 TileIndex tile2
= tile
+ TileOffsByDiagDir(d
);
2663 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
2664 if (!IsValidTile(tile2
) || IsTileType(tile2
, MP_HOUSE
) || IsTileType(tile2
, MP_INDUSTRY
) ||
2665 IsTileType(tile2
, MP_ROAD
) || (IsTileType(tile2
, MP_OBJECT
) && !IsObjectType(tile2
, OBJECT_OWNED_LAND
)) || IsTileType(tile2
, MP_TUNNELBRIDGE
) || !IsTileOwner(tile2
, owner
)) {
2672 case (1 << DIAGDIR_NE
): new_ground
= RAIL_GROUND_FENCE_NE
; break;
2673 case (1 << DIAGDIR_SE
): new_ground
= RAIL_GROUND_FENCE_SE
; break;
2674 case (1 << DIAGDIR_SW
): new_ground
= RAIL_GROUND_FENCE_SW
; break;
2675 case (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_NW
; break;
2676 case (1 << DIAGDIR_NE
) | (1 << DIAGDIR_SW
): new_ground
= RAIL_GROUND_FENCE_NESW
; break;
2677 case (1 << DIAGDIR_SE
) | (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_SENW
; break;
2678 case (1 << DIAGDIR_NE
) | (1 << DIAGDIR_SE
): new_ground
= RAIL_GROUND_FENCE_VERT1
; break;
2679 case (1 << DIAGDIR_NE
) | (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_HORIZ2
; break;
2680 case (1 << DIAGDIR_SE
) | (1 << DIAGDIR_SW
): new_ground
= RAIL_GROUND_FENCE_HORIZ1
; break;
2681 case (1 << DIAGDIR_SW
) | (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_VERT2
; break;
2682 default: NOT_REACHED();
2687 if (old_ground
!= new_ground
) {
2688 SetRailGroundType(tile
, new_ground
);
2689 MarkTileDirtyByTile(tile
);
2694 static TrackStatus
GetTileTrackStatus_Track(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
2696 /* Case of half tile slope with water. */
2697 if (mode
== TRANSPORT_WATER
&& IsPlainRail(tile
) && GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(GetTileSlope(tile
))) {
2698 TrackBits tb
= GetTrackBits(tile
);
2700 default: NOT_REACHED();
2701 case TRACK_BIT_UPPER
: tb
= TRACK_BIT_LOWER
; break;
2702 case TRACK_BIT_LOWER
: tb
= TRACK_BIT_UPPER
; break;
2703 case TRACK_BIT_LEFT
: tb
= TRACK_BIT_RIGHT
; break;
2704 case TRACK_BIT_RIGHT
: tb
= TRACK_BIT_LEFT
; break;
2706 return CombineTrackStatus(TrackBitsToTrackdirBits(tb
), TRACKDIR_BIT_NONE
);
2709 if (mode
!= TRANSPORT_RAIL
) return 0;
2711 TrackBits trackbits
= TRACK_BIT_NONE
;
2712 TrackdirBits red_signals
= TRACKDIR_BIT_NONE
;
2714 switch (GetRailTileType(tile
)) {
2715 default: NOT_REACHED();
2716 case RAIL_TILE_NORMAL
:
2717 trackbits
= GetTrackBits(tile
);
2720 case RAIL_TILE_SIGNALS
: {
2721 trackbits
= GetTrackBits(tile
);
2722 byte a
= GetPresentSignals(tile
);
2723 uint b
= GetSignalStates(tile
);
2727 /* When signals are not present (in neither direction),
2728 * we pretend them to be green. Otherwise, it depends on
2729 * the signal type. For signals that are only active from
2730 * one side, we set the missing signals explicitly to
2731 * `green'. Otherwise, they implicitly become `red'. */
2732 if (!IsOnewaySignal(tile
, TRACK_UPPER
) || (a
& SignalOnTrack(TRACK_UPPER
)) == 0) b
|= ~a
& SignalOnTrack(TRACK_UPPER
);
2733 if (!IsOnewaySignal(tile
, TRACK_LOWER
) || (a
& SignalOnTrack(TRACK_LOWER
)) == 0) b
|= ~a
& SignalOnTrack(TRACK_LOWER
);
2735 if ((b
& 0x8) == 0) red_signals
|= (TRACKDIR_BIT_LEFT_N
| TRACKDIR_BIT_X_NE
| TRACKDIR_BIT_Y_SE
| TRACKDIR_BIT_UPPER_E
);
2736 if ((b
& 0x4) == 0) red_signals
|= (TRACKDIR_BIT_LEFT_S
| TRACKDIR_BIT_X_SW
| TRACKDIR_BIT_Y_NW
| TRACKDIR_BIT_UPPER_W
);
2737 if ((b
& 0x2) == 0) red_signals
|= (TRACKDIR_BIT_RIGHT_N
| TRACKDIR_BIT_LOWER_E
);
2738 if ((b
& 0x1) == 0) red_signals
|= (TRACKDIR_BIT_RIGHT_S
| TRACKDIR_BIT_LOWER_W
);
2743 case RAIL_TILE_DEPOT
: {
2744 DiagDirection dir
= GetRailDepotDirection(tile
);
2746 if (side
!= INVALID_DIAGDIR
&& side
!= dir
) break;
2748 trackbits
= DiagDirToDiagTrackBits(dir
);
2753 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), red_signals
);
2756 static bool ClickTile_Track(TileIndex tile
)
2758 if (!IsRailDepot(tile
)) return false;
2760 ShowDepotWindow(tile
, VEH_TRAIN
);
2764 static void GetTileDesc_Track(TileIndex tile
, TileDesc
*td
)
2766 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
2767 td
->rail_speed
= rti
->max_speed
;
2768 td
->railtype
= rti
->strings
.name
;
2769 td
->owner
[0] = GetTileOwner(tile
);
2770 switch (GetRailTileType(tile
)) {
2771 case RAIL_TILE_NORMAL
:
2772 td
->str
= STR_LAI_RAIL_DESCRIPTION_TRACK
;
2775 case RAIL_TILE_SIGNALS
: {
2776 static const StringID signal_type
[6][6] = {
2778 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS
,
2779 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS
,
2780 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS
,
2781 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS
,
2782 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS
,
2783 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
2786 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS
,
2787 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS
,
2788 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS
,
2789 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS
,
2790 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS
,
2791 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
2794 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS
,
2795 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS
,
2796 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS
,
2797 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS
,
2798 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS
,
2799 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
2802 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS
,
2803 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS
,
2804 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS
,
2805 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS
,
2806 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS
,
2807 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
2810 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS
,
2811 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS
,
2812 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS
,
2813 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS
,
2814 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS
,
2815 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
2818 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
,
2819 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
,
2820 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
,
2821 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
,
2822 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
,
2823 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS
2827 SignalType primary_signal
;
2828 SignalType secondary_signal
;
2829 if (HasSignalOnTrack(tile
, TRACK_UPPER
)) {
2830 primary_signal
= GetSignalType(tile
, TRACK_UPPER
);
2831 secondary_signal
= HasSignalOnTrack(tile
, TRACK_LOWER
) ? GetSignalType(tile
, TRACK_LOWER
) : primary_signal
;
2833 secondary_signal
= primary_signal
= GetSignalType(tile
, TRACK_LOWER
);
2836 td
->str
= signal_type
[secondary_signal
][primary_signal
];
2840 case RAIL_TILE_DEPOT
:
2841 td
->str
= STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT
;
2842 if (_settings_game
.vehicle
.train_acceleration_model
!= AM_ORIGINAL
) {
2843 if (td
->rail_speed
> 0) {
2844 td
->rail_speed
= std::min
<uint16
>(td
->rail_speed
, 61);
2846 td
->rail_speed
= 61;
2849 td
->build_date
= Depot::GetByTile(tile
)->build_date
;
2857 static void ChangeTileOwner_Track(TileIndex tile
, Owner old_owner
, Owner new_owner
)
2859 if (!IsTileOwner(tile
, old_owner
)) return;
2861 if (new_owner
!= INVALID_OWNER
) {
2862 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2863 uint num_pieces
= 1;
2864 if (IsPlainRail(tile
)) {
2865 TrackBits bits
= GetTrackBits(tile
);
2866 num_pieces
= CountBits(bits
);
2867 if (TracksOverlap(bits
)) num_pieces
*= num_pieces
;
2869 RailType rt
= GetRailType(tile
);
2870 Company::Get(old_owner
)->infrastructure
.rail
[rt
] -= num_pieces
;
2871 Company::Get(new_owner
)->infrastructure
.rail
[rt
] += num_pieces
;
2873 if (HasSignals(tile
)) {
2874 uint num_sigs
= CountBits(GetPresentSignals(tile
));
2875 Company::Get(old_owner
)->infrastructure
.signal
-= num_sigs
;
2876 Company::Get(new_owner
)->infrastructure
.signal
+= num_sigs
;
2879 SetTileOwner(tile
, new_owner
);
2881 Command
<CMD_LANDSCAPE_CLEAR
>::Do(DC_EXEC
| DC_BANKRUPT
, tile
);
2885 static const byte _fractcoords_behind
[4] = { 0x8F, 0x8, 0x80, 0xF8 };
2886 static const byte _fractcoords_enter
[4] = { 0x8A, 0x48, 0x84, 0xA8 };
2887 static const int8 _deltacoord_leaveoffset
[8] = {
2888 -1, 0, 1, 0, /* x */
2894 * Compute number of ticks when next wagon will leave a depot.
2895 * Negative means next wagon should have left depot n ticks before.
2896 * @param v vehicle outside (leaving) the depot
2897 * @return number of ticks when the next wagon will leave
2899 int TicksToLeaveDepot(const Train
*v
)
2901 DiagDirection dir
= GetRailDepotDirection(v
->tile
);
2902 int length
= v
->CalcNextVehicleOffset();
2905 case DIAGDIR_NE
: return ((int)(v
->x_pos
& 0x0F) - ((_fractcoords_enter
[dir
] & 0x0F) - (length
+ 1)));
2906 case DIAGDIR_SE
: return -((int)(v
->y_pos
& 0x0F) - ((_fractcoords_enter
[dir
] >> 4) + (length
+ 1)));
2907 case DIAGDIR_SW
: return -((int)(v
->x_pos
& 0x0F) - ((_fractcoords_enter
[dir
] & 0x0F) + (length
+ 1)));
2908 case DIAGDIR_NW
: return ((int)(v
->y_pos
& 0x0F) - ((_fractcoords_enter
[dir
] >> 4) - (length
+ 1)));
2909 default: NOT_REACHED();
2914 * Tile callback routine when vehicle enters tile
2915 * @see vehicle_enter_tile_proc
2917 static VehicleEnterTileStatus
VehicleEnter_Track(Vehicle
*u
, TileIndex tile
, int x
, int y
)
2919 /* This routine applies only to trains in depot tiles. */
2920 if (u
->type
!= VEH_TRAIN
|| !IsRailDepotTile(tile
)) return VETSB_CONTINUE
;
2922 /* Depot direction. */
2923 DiagDirection dir
= GetRailDepotDirection(tile
);
2925 byte fract_coord
= (x
& 0xF) + ((y
& 0xF) << 4);
2927 /* Make sure a train is not entering the tile from behind. */
2928 if (_fractcoords_behind
[dir
] == fract_coord
) return VETSB_CANNOT_ENTER
;
2930 Train
*v
= Train::From(u
);
2932 /* Leaving depot? */
2933 if (v
->direction
== DiagDirToDir(dir
)) {
2934 /* Calculate the point where the following wagon should be activated. */
2935 int length
= v
->CalcNextVehicleOffset();
2937 byte fract_coord_leave
=
2938 ((_fractcoords_enter
[dir
] & 0x0F) + // x
2939 (length
+ 1) * _deltacoord_leaveoffset
[dir
]) +
2940 (((_fractcoords_enter
[dir
] >> 4) + // y
2941 ((length
+ 1) * _deltacoord_leaveoffset
[dir
+ 4])) << 4);
2943 if (fract_coord_leave
== fract_coord
) {
2944 /* Leave the depot. */
2945 if ((v
= v
->Next()) != nullptr) {
2946 v
->vehstatus
&= ~VS_HIDDEN
;
2947 v
->track
= (DiagDirToAxis(dir
) == AXIS_X
? TRACK_BIT_X
: TRACK_BIT_Y
);
2950 } else if (_fractcoords_enter
[dir
] == fract_coord
) {
2951 /* Entering depot. */
2952 assert(DiagDirToDir(ReverseDiagDir(dir
)) == v
->direction
);
2953 v
->track
= TRACK_BIT_DEPOT
,
2954 v
->vehstatus
|= VS_HIDDEN
;
2955 v
->direction
= ReverseDir(v
->direction
);
2956 if (v
->Next() == nullptr) VehicleEnterDepot(v
->First());
2959 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
2960 return VETSB_ENTERED_WORMHOLE
;
2963 return VETSB_CONTINUE
;
2967 * Tests if autoslope is allowed.
2969 * @param tile The tile.
2970 * @param flags Terraform command flags.
2971 * @param z_old Old TileZ.
2972 * @param tileh_old Old TileSlope.
2973 * @param z_new New TileZ.
2974 * @param tileh_new New TileSlope.
2975 * @param rail_bits Trackbits.
2977 static CommandCost
TestAutoslopeOnRailTile(TileIndex tile
, uint flags
, int z_old
, Slope tileh_old
, int z_new
, Slope tileh_new
, TrackBits rail_bits
)
2979 if (!_settings_game
.construction
.build_on_slopes
|| !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
2981 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
2982 if (CheckRailSlope(tileh_new
, rail_bits
, TRACK_BIT_NONE
, tile
).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
2984 /* Get the slopes on top of the foundations */
2985 z_old
+= ApplyFoundationToSlope(GetRailFoundation(tileh_old
, rail_bits
), &tileh_old
);
2986 z_new
+= ApplyFoundationToSlope(GetRailFoundation(tileh_new
, rail_bits
), &tileh_new
);
2988 Corner track_corner
;
2989 switch (rail_bits
) {
2990 case TRACK_BIT_LEFT
: track_corner
= CORNER_W
; break;
2991 case TRACK_BIT_LOWER
: track_corner
= CORNER_S
; break;
2992 case TRACK_BIT_RIGHT
: track_corner
= CORNER_E
; break;
2993 case TRACK_BIT_UPPER
: track_corner
= CORNER_N
; break;
2995 /* Surface slope must not be changed */
2997 if (z_old
!= z_new
|| tileh_old
!= tileh_new
) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
2998 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3001 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
3002 z_old
+= GetSlopeZInCorner(RemoveHalftileSlope(tileh_old
), track_corner
);
3003 z_new
+= GetSlopeZInCorner(RemoveHalftileSlope(tileh_new
), track_corner
);
3004 if (z_old
!= z_new
) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
3006 CommandCost cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3007 /* Make the ground dirty, if surface slope has changed */
3008 if (tileh_old
!= tileh_new
) {
3009 /* If there is flat water on the lower halftile add the cost for clearing it */
3010 if (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh_old
)) cost
.AddCost(_price
[PR_CLEAR_WATER
]);
3011 if ((flags
& DC_EXEC
) != 0) SetRailGroundType(tile
, RAIL_GROUND_BARREN
);
3017 * Test-procedure for HasVehicleOnPos to check for a ship.
3019 static Vehicle
*EnsureNoShipProc(Vehicle
*v
, void *data
)
3021 return v
->type
== VEH_SHIP
? v
: nullptr;
3024 static CommandCost
TerraformTile_Track(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
3027 Slope tileh_old
= GetTileSlope(tile
, &z_old
);
3028 if (IsPlainRail(tile
)) {
3029 TrackBits rail_bits
= GetTrackBits(tile
);
3030 /* Is there flat water on the lower halftile that must be cleared expensively? */
3031 bool was_water
= (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh_old
));
3033 /* Allow clearing the water only if there is no ship */
3034 if (was_water
&& HasVehicleOnPos(tile
, nullptr, &EnsureNoShipProc
)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY
);
3036 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
3037 CommandCost autoslope_result
= TestAutoslopeOnRailTile(tile
, flags
, z_old
, tileh_old
, z_new
, tileh_new
, rail_bits
);
3039 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
3040 Corner allowed_corner
;
3041 switch (rail_bits
) {
3042 case TRACK_BIT_RIGHT
: allowed_corner
= CORNER_W
; break;
3043 case TRACK_BIT_UPPER
: allowed_corner
= CORNER_S
; break;
3044 case TRACK_BIT_LEFT
: allowed_corner
= CORNER_E
; break;
3045 case TRACK_BIT_LOWER
: allowed_corner
= CORNER_N
; break;
3046 default: return autoslope_result
;
3049 Foundation f_old
= GetRailFoundation(tileh_old
, rail_bits
);
3051 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3052 if (tileh_old
!= SLOPE_NS
&& tileh_old
!= SLOPE_EW
&& IsSpecialRailFoundation(f_old
)) return autoslope_result
;
3054 /* Everything is valid, which only changes allowed_corner */
3055 for (Corner corner
= (Corner
)0; corner
< CORNER_END
; corner
= (Corner
)(corner
+ 1)) {
3056 if (allowed_corner
== corner
) continue;
3057 if (z_old
+ GetSlopeZInCorner(tileh_old
, corner
) != z_new
+ GetSlopeZInCorner(tileh_new
, corner
)) return autoslope_result
;
3060 /* Make the ground dirty */
3061 if ((flags
& DC_EXEC
) != 0) SetRailGroundType(tile
, RAIL_GROUND_BARREN
);
3063 /* allow terraforming */
3064 return CommandCost(EXPENSES_CONSTRUCTION
, was_water
? _price
[PR_CLEAR_WATER
] : (Money
)0);
3065 } else if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled() &&
3066 AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, GetRailDepotDirection(tile
))) {
3067 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3069 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
3073 extern const TileTypeProcs _tile_type_rail_procs
= {
3074 DrawTile_Track
, // draw_tile_proc
3075 GetSlopePixelZ_Track
, // get_slope_z_proc
3076 ClearTile_Track
, // clear_tile_proc
3077 nullptr, // add_accepted_cargo_proc
3078 GetTileDesc_Track
, // get_tile_desc_proc
3079 GetTileTrackStatus_Track
, // get_tile_track_status_proc
3080 ClickTile_Track
, // click_tile_proc
3081 nullptr, // animate_tile_proc
3082 TileLoop_Track
, // tile_loop_proc
3083 ChangeTileOwner_Track
, // change_tile_owner_proc
3084 nullptr, // add_produced_cargo_proc
3085 VehicleEnter_Track
, // vehicle_enter_tile_proc
3086 GetFoundation_Track
, // get_foundation_proc
3087 TerraformTile_Track
, // terraform_tile_proc