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 "cmd_helper.h"
12 #include "viewport_func.h"
13 #include "command_func.h"
14 #include "depot_base.h"
15 #include "pathfinder/yapf/yapf_cache.h"
16 #include "newgrf_debug.h"
17 #include "newgrf_railtype.h"
19 #include "autoslope.h"
21 #include "tunnelbridge_map.h"
22 #include "vehicle_func.h"
23 #include "sound_func.h"
24 #include "tunnelbridge.h"
25 #include "elrail_func.h"
28 #include "company_base.h"
29 #include "core/backup_type.hpp"
30 #include "date_func.h"
31 #include "strings_func.h"
32 #include "company_gui.h"
33 #include "object_map.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 p1 railtype of being built piece (normal, mono, maglev)
432 * @param p2 various bitstuffed elements
433 * - (bit 0- 2) - track-orientation, valid values: 0-5 (@see Track)
434 * - (bit 3) - 0 = error on signal in the way, 1 = auto remove signals when in the way
436 * @return the cost of this operation or an error
438 CommandCost
CmdBuildSingleRail(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
440 RailType railtype
= Extract
<RailType
, 0, 6>(p1
);
441 Track track
= Extract
<Track
, 0, 3>(p2
);
442 bool auto_remove_signals
= HasBit(p2
, 3);
443 CommandCost
cost(EXPENSES_CONSTRUCTION
);
445 if (!ValParamRailtype(railtype
) || !ValParamTrackOrientation(track
)) return CMD_ERROR
;
447 Slope tileh
= GetTileSlope(tile
);
448 TrackBits trackbit
= TrackToTrackBits(track
);
450 switch (GetTileType(tile
)) {
452 CommandCost ret
= CheckTileOwnership(tile
);
453 if (ret
.Failed()) return ret
;
455 if (!IsPlainRail(tile
)) return DoCommand(flags
, CMD_LANDSCAPE_CLEAR
, tile
, 0, 0); // just get appropriate error message
457 if (!IsCompatibleRail(GetRailType(tile
), railtype
)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION
);
459 ret
= CheckTrackCombination(tile
, trackbit
, flags
);
460 if (ret
.Succeeded()) ret
= EnsureNoTrainOnTrack(tile
, track
);
461 if (ret
.Failed()) return ret
;
463 ret
= CheckRailSlope(tileh
, trackbit
, GetTrackBits(tile
), tile
);
464 if (ret
.Failed()) return ret
;
467 if (HasSignals(tile
) && TracksOverlap(GetTrackBits(tile
) | TrackToTrackBits(track
))) {
468 /* If adding the new track causes any overlap, all signals must be removed first */
469 if (!auto_remove_signals
) return_cmd_error(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST
);
471 for (Track track_it
= TRACK_BEGIN
; track_it
< TRACK_END
; track_it
++) {
472 if (HasTrack(tile
, track_it
) && HasSignalOnTrack(tile
, track_it
)) {
473 CommandCost ret_remove_signals
= DoCommand(flags
, CMD_REMOVE_SIGNALS
, tile
, track_it
, 0);
474 if (ret_remove_signals
.Failed()) return ret_remove_signals
;
475 cost
.AddCost(ret_remove_signals
);
480 /* If the rail types don't match, try to convert only if engines of
481 * the new rail type are not powered on the present rail type and engines of
482 * the present rail type are powered on the new rail type. */
483 if (GetRailType(tile
) != railtype
&& !HasPowerOnRail(railtype
, GetRailType(tile
))) {
484 if (HasPowerOnRail(GetRailType(tile
), railtype
)) {
485 ret
= DoCommand(flags
, CMD_CONVERT_RAIL
, tile
, tile
, railtype
);
486 if (ret
.Failed()) return ret
;
493 if (flags
& DC_EXEC
) {
494 SetRailGroundType(tile
, RAIL_GROUND_BARREN
);
495 TrackBits bits
= GetTrackBits(tile
);
496 SetTrackBits(tile
, bits
| trackbit
);
497 /* Subtract old infrastructure count. */
498 uint pieces
= CountBits(bits
);
499 if (TracksOverlap(bits
)) pieces
*= pieces
;
500 Company::Get(GetTileOwner(tile
))->infrastructure
.rail
[GetRailType(tile
)] -= pieces
;
501 /* Add new infrastructure count. */
502 pieces
= CountBits(bits
| trackbit
);
503 if (TracksOverlap(bits
| trackbit
)) pieces
*= pieces
;
504 Company::Get(GetTileOwner(tile
))->infrastructure
.rail
[GetRailType(tile
)] += pieces
;
505 DirtyCompanyInfrastructureWindows(GetTileOwner(tile
));
511 /* Level crossings may only be built on these slopes */
512 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES
, tileh
)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
514 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
515 if (ret
.Failed()) return ret
;
517 if (IsNormalRoad(tile
)) {
518 if (HasRoadWorks(tile
)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS
);
520 if (GetDisallowedRoadDirections(tile
) != DRD_NONE
) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD
);
522 if (RailNoLevelCrossings(railtype
)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_RAIL
);
524 RoadType roadtype_road
= GetRoadTypeRoad(tile
);
525 RoadType roadtype_tram
= GetRoadTypeTram(tile
);
527 if (roadtype_road
!= INVALID_ROADTYPE
&& RoadNoLevelCrossing(roadtype_road
)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD
);
528 if (roadtype_tram
!= INVALID_ROADTYPE
&& RoadNoLevelCrossing(roadtype_tram
)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD
);
530 RoadBits road
= GetRoadBits(tile
, RTT_ROAD
);
531 RoadBits tram
= GetRoadBits(tile
, RTT_TRAM
);
532 if ((track
== TRACK_X
&& ((road
| tram
) & ROAD_X
) == 0) ||
533 (track
== TRACK_Y
&& ((road
| tram
) & ROAD_Y
) == 0)) {
534 Owner road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
535 Owner tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
536 /* Disallow breaking end-of-line of someone else
537 * so trams can still reverse on this tile. */
538 if (Company::IsValidID(tram_owner
) && HasExactlyOneBit(tram
)) {
539 CommandCost ret
= CheckOwnership(tram_owner
);
540 if (ret
.Failed()) return ret
;
543 uint num_new_road_pieces
= (road
!= ROAD_NONE
) ? 2 - CountBits(road
) : 0;
544 if (num_new_road_pieces
> 0) {
545 cost
.AddCost(num_new_road_pieces
* RoadBuildCost(roadtype_road
));
548 uint num_new_tram_pieces
= (tram
!= ROAD_NONE
) ? 2 - CountBits(tram
) : 0;
549 if (num_new_tram_pieces
> 0) {
550 cost
.AddCost(num_new_tram_pieces
* RoadBuildCost(roadtype_tram
));
553 if (flags
& DC_EXEC
) {
554 MakeRoadCrossing(tile
, road_owner
, tram_owner
, _current_company
, (track
== TRACK_X
? AXIS_Y
: AXIS_X
), railtype
, roadtype_road
, roadtype_tram
, GetTownIndex(tile
));
555 UpdateLevelCrossing(tile
, false);
556 Company::Get(_current_company
)->infrastructure
.rail
[railtype
] += LEVELCROSSING_TRACKBIT_FACTOR
;
557 DirtyCompanyInfrastructureWindows(_current_company
);
558 if (num_new_road_pieces
> 0 && Company::IsValidID(road_owner
)) {
559 Company::Get(road_owner
)->infrastructure
.road
[roadtype_road
] += num_new_road_pieces
;
560 DirtyCompanyInfrastructureWindows(road_owner
);
562 if (num_new_tram_pieces
> 0 && Company::IsValidID(tram_owner
)) {
563 Company::Get(tram_owner
)->infrastructure
.road
[roadtype_tram
] += num_new_tram_pieces
;
564 DirtyCompanyInfrastructureWindows(tram_owner
);
571 if (IsLevelCrossing(tile
) && GetCrossingRailBits(tile
) == trackbit
) {
572 return_cmd_error(STR_ERROR_ALREADY_BUILT
);
578 /* Will there be flat water on the lower halftile? */
579 bool water_ground
= IsTileType(tile
, MP_WATER
) && IsSlopeWithOneCornerRaised(tileh
);
581 CommandCost ret
= CheckRailSlope(tileh
, trackbit
, TRACK_BIT_NONE
, tile
);
582 if (ret
.Failed()) return ret
;
585 ret
= DoCommand(flags
, CMD_LANDSCAPE_CLEAR
, tile
, 0, 0);
586 if (ret
.Failed()) return ret
;
590 cost
.AddCost(-_price
[PR_CLEAR_WATER
]);
591 cost
.AddCost(_price
[PR_CLEAR_ROUGH
]);
594 if (flags
& DC_EXEC
) {
595 MakeRailNormal(tile
, _current_company
, trackbit
, railtype
);
597 SetRailGroundType(tile
, RAIL_GROUND_WATER
);
598 if (IsPossibleDockingTile(tile
)) CheckForDockingTile(tile
);
600 Company::Get(_current_company
)->infrastructure
.rail
[railtype
]++;
601 DirtyCompanyInfrastructureWindows(_current_company
);
607 if (flags
& DC_EXEC
) {
608 MarkTileDirtyByTile(tile
);
609 AddTrackToSignalBuffer(tile
, track
, _current_company
);
610 YapfNotifyTrackLayoutChange(tile
, track
);
613 cost
.AddCost(RailBuildCost(railtype
));
618 * Remove a single piece of track
619 * @param flags operation to perform
620 * @param tile tile to remove track from
622 * @param p2 rail orientation
624 * @return the cost of this operation or an error
626 CommandCost
CmdRemoveSingleRail(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
628 Track track
= Extract
<Track
, 0, 3>(p2
);
629 CommandCost
cost(EXPENSES_CONSTRUCTION
);
630 bool crossing
= false;
632 if (!ValParamTrackOrientation(track
)) return CMD_ERROR
;
633 TrackBits trackbit
= TrackToTrackBits(track
);
635 /* Need to read tile owner now because it may change when the rail is removed
636 * Also, in case of floods, _current_company != owner
637 * There may be invalid tiletype even in exec run (when removing long track),
638 * so do not call GetTileOwner(tile) in any case here */
639 Owner owner
= INVALID_OWNER
;
643 switch (GetTileType(tile
)) {
645 if (!IsLevelCrossing(tile
) || GetCrossingRailBits(tile
) != trackbit
) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
647 if (_current_company
!= OWNER_WATER
) {
648 CommandCost ret
= CheckTileOwnership(tile
);
649 if (ret
.Failed()) return ret
;
652 if (!(flags
& DC_BANKRUPT
)) {
653 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
654 if (ret
.Failed()) return ret
;
657 cost
.AddCost(RailClearCost(GetRailType(tile
)));
659 if (flags
& DC_EXEC
) {
660 if (HasReservedTracks(tile
, trackbit
)) {
661 v
= GetTrainForReservation(tile
, track
);
662 if (v
!= nullptr) FreeTrainTrackReservation(v
);
665 owner
= GetTileOwner(tile
);
666 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] -= LEVELCROSSING_TRACKBIT_FACTOR
;
667 DirtyCompanyInfrastructureWindows(owner
);
668 MakeRoadNormal(tile
, GetCrossingRoadBits(tile
), GetRoadTypeRoad(tile
), GetRoadTypeTram(tile
), GetTownIndex(tile
), GetRoadOwner(tile
, RTT_ROAD
), GetRoadOwner(tile
, RTT_TRAM
));
669 DeleteNewGRFInspectWindow(GSF_RAILTYPES
, tile
);
676 /* There are no rails present at depots. */
677 if (!IsPlainRail(tile
)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
679 if (_current_company
!= OWNER_WATER
) {
680 CommandCost ret
= CheckTileOwnership(tile
);
681 if (ret
.Failed()) return ret
;
684 CommandCost ret
= EnsureNoTrainOnTrack(tile
, track
);
685 if (ret
.Failed()) return ret
;
687 present
= GetTrackBits(tile
);
688 if ((present
& trackbit
) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
689 if (present
== (TRACK_BIT_X
| TRACK_BIT_Y
)) crossing
= true;
691 cost
.AddCost(RailClearCost(GetRailType(tile
)));
693 /* Charge extra to remove signals on the track, if they are there */
694 if (HasSignalOnTrack(tile
, track
)) {
695 cost
.AddCost(DoCommand(flags
, CMD_REMOVE_SIGNALS
, tile
, track
, 0));
698 if (flags
& DC_EXEC
) {
699 if (HasReservedTracks(tile
, trackbit
)) {
700 v
= GetTrainForReservation(tile
, track
);
701 if (v
!= nullptr) FreeTrainTrackReservation(v
);
704 owner
= GetTileOwner(tile
);
706 /* Subtract old infrastructure count. */
707 uint pieces
= CountBits(present
);
708 if (TracksOverlap(present
)) pieces
*= pieces
;
709 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] -= pieces
;
710 /* Add new infrastructure count. */
712 pieces
= CountBits(present
);
713 if (TracksOverlap(present
)) pieces
*= pieces
;
714 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)] += pieces
;
715 DirtyCompanyInfrastructureWindows(owner
);
718 Slope tileh
= GetTileSlope(tile
);
719 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
720 if (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh
)) {
721 bool docking
= IsDockingTile(tile
);
723 SetDockingTile(tile
, docking
);
727 DeleteNewGRFInspectWindow(GSF_RAILTYPES
, tile
);
729 SetTrackBits(tile
, present
);
730 SetTrackReservation(tile
, GetRailReservationTrackBits(tile
) & present
);
736 default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
739 if (flags
& DC_EXEC
) {
740 /* if we got that far, 'owner' variable is set correctly */
741 assert(Company::IsValidID(owner
));
743 MarkTileDirtyByTile(tile
);
745 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
746 * are removing one of these pieces, we'll need to update signals for
747 * both directions explicitly, as after the track is removed it won't
748 * 'connect' with the other piece. */
749 AddTrackToSignalBuffer(tile
, TRACK_X
, owner
);
750 AddTrackToSignalBuffer(tile
, TRACK_Y
, owner
);
751 YapfNotifyTrackLayoutChange(tile
, TRACK_X
);
752 YapfNotifyTrackLayoutChange(tile
, TRACK_Y
);
754 AddTrackToSignalBuffer(tile
, track
, owner
);
755 YapfNotifyTrackLayoutChange(tile
, track
);
758 if (v
!= nullptr) TryPathReserve(v
, true);
766 * Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
767 * The function floods the lower halftile, if the tile has a halftile foundation.
769 * @param t The tile to flood.
770 * @return true if something was flooded.
772 bool FloodHalftile(TileIndex t
)
774 assert(IsPlainRailTile(t
));
776 bool flooded
= false;
777 if (GetRailGroundType(t
) == RAIL_GROUND_WATER
) return flooded
;
779 Slope tileh
= GetTileSlope(t
);
780 TrackBits rail_bits
= GetTrackBits(t
);
782 if (IsSlopeWithOneCornerRaised(tileh
)) {
783 TrackBits lower_track
= CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh
)));
785 TrackBits to_remove
= lower_track
& rail_bits
;
786 if (to_remove
!= 0) {
787 Backup
<CompanyID
> cur_company(_current_company
, OWNER_WATER
, FILE_LINE
);
788 flooded
= DoCommand(DC_EXEC
, CMD_REMOVE_SINGLE_RAIL
, t
, 0, FIND_FIRST_BIT(to_remove
)).Succeeded();
789 cur_company
.Restore();
790 if (!flooded
) return flooded
; // not yet floodable
791 rail_bits
= rail_bits
& ~to_remove
;
792 if (rail_bits
== 0) {
794 MarkTileDirtyByTile(t
);
799 if (IsNonContinuousFoundation(GetRailFoundation(tileh
, rail_bits
))) {
801 SetRailGroundType(t
, RAIL_GROUND_WATER
);
802 MarkTileDirtyByTile(t
);
805 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
806 if (ApplyFoundationToSlope(GetRailFoundation(tileh
, rail_bits
), &tileh
) == 0) {
807 if (IsSteepSlope(tileh
) || IsSlopeWithThreeCornersRaised(tileh
)) {
809 SetRailGroundType(t
, RAIL_GROUND_WATER
);
810 MarkTileDirtyByTile(t
);
817 static const TileIndexDiffC _trackdelta
[] = {
818 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
821 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
827 static CommandCost
ValidateAutoDrag(Trackdir
*trackdir
, TileIndex start
, TileIndex end
)
829 int x
= TileX(start
);
830 int y
= TileY(start
);
834 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir
))) return CMD_ERROR
;
836 /* calculate delta x,y from start to end tile */
840 /* calculate delta x,y for the first direction */
841 int trdx
= _trackdelta
[*trackdir
].x
;
842 int trdy
= _trackdelta
[*trackdir
].y
;
844 if (!IsDiagonalTrackdir(*trackdir
)) {
845 trdx
+= _trackdelta
[*trackdir
^ 1].x
;
846 trdy
+= _trackdelta
[*trackdir
^ 1].y
;
849 /* validate the direction */
850 while ((trdx
<= 0 && dx
> 0) ||
851 (trdx
>= 0 && dx
< 0) ||
852 (trdy
<= 0 && dy
> 0) ||
853 (trdy
>= 0 && dy
< 0)) {
854 if (!HasBit(*trackdir
, 3)) { // first direction is invalid, try the other
855 SetBit(*trackdir
, 3); // reverse the direction
858 } else { // other direction is invalid too, invalid drag
863 /* (for diagonal tracks, this is already made sure of by above test), but:
864 * for non-diagonal tracks, check if the start and end tile are on 1 line */
865 if (!IsDiagonalTrackdir(*trackdir
)) {
866 trdx
= _trackdelta
[*trackdir
].x
;
867 trdy
= _trackdelta
[*trackdir
].y
;
868 if (abs(dx
) != abs(dy
) && abs(dx
) + abs(trdy
) != abs(dy
) + abs(trdx
)) return CMD_ERROR
;
871 return CommandCost();
875 * Build or remove a stretch of railroad tracks.
876 * @param flags operation to perform
877 * @param tile start tile of drag
878 * @param p1 end tile of drag
879 * @param p2 various bitstuffed elements
880 * - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
881 * - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
882 * - p2 = (bit 9) - 0 = build, 1 = remove tracks
883 * - p2 = (bit 10) - 0 = build up to an obstacle, 1 = fail if an obstacle is found (used for AIs).
884 * - p2 = (bit 11) - 0 = error on signal in the way, 1 = auto remove signals when in the way
886 * @return the cost of this operation or an error
888 static CommandCost
CmdRailTrackHelper(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
890 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
891 Track track
= Extract
<Track
, 6, 3>(p2
);
892 bool remove
= HasBit(p2
, 9);
893 bool auto_remove_signals
= HasBit(p2
, 11);
894 RailType railtype
= Extract
<RailType
, 0, 6>(p2
);
896 if ((!remove
&& !ValParamRailtype(railtype
)) || !ValParamTrackOrientation(track
)) return CMD_ERROR
;
897 if (p1
>= MapSize()) return CMD_ERROR
;
898 TileIndex end_tile
= p1
;
899 Trackdir trackdir
= TrackToTrackdir(track
);
901 CommandCost ret
= ValidateAutoDrag(&trackdir
, tile
, end_tile
);
902 if (ret
.Failed()) return ret
;
904 bool had_success
= false;
905 CommandCost last_error
= CMD_ERROR
;
907 CommandCost ret
= DoCommand(flags
, remove
? CMD_REMOVE_SINGLE_RAIL
: CMD_BUILD_SINGLE_RAIL
, tile
, remove
? 0 : railtype
, TrackdirToTrack(trackdir
) | (auto_remove_signals
<< 3));
911 if (last_error
.GetErrorMessage() != STR_ERROR_ALREADY_BUILT
&& !remove
) {
912 if (HasBit(p2
, 10)) return last_error
;
916 /* Ownership errors are more important. */
917 if (last_error
.GetErrorMessage() == STR_ERROR_OWNED_BY
&& remove
) break;
920 total_cost
.AddCost(ret
);
923 if (tile
== end_tile
) break;
925 tile
+= ToTileIndexDiff(_trackdelta
[trackdir
]);
927 /* toggle railbit for the non-diagonal tracks */
928 if (!IsDiagonalTrackdir(trackdir
)) ToggleBit(trackdir
, 0);
931 if (had_success
) return total_cost
;
936 * Build rail on a stretch of track.
937 * Stub for the unified rail builder/remover
938 * @param flags operation to perform
939 * @param tile start tile of drag
940 * @param p1 end tile of drag
941 * @param p2 various bitstuffed elements
942 * - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
943 * - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
944 * - p2 = (bit 9) - 0 = build, 1 = remove tracks
946 * @return the cost of this operation or an error
947 * @see CmdRailTrackHelper
949 CommandCost
CmdBuildRailroadTrack(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
951 return CmdRailTrackHelper(flags
, tile
, p1
, ClrBit(p2
, 9), text
);
955 * Build rail on a stretch of track.
956 * Stub for the unified rail builder/remover
957 * @param flags operation to perform
958 * @param tile start tile of drag
959 * @param p1 end tile of drag
960 * @param p2 various bitstuffed elements
961 * - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
962 * - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
963 * - p2 = (bit 9) - 0 = build, 1 = remove tracks
965 * @return the cost of this operation or an error
966 * @see CmdRailTrackHelper
968 CommandCost
CmdRemoveRailroadTrack(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
970 return CmdRailTrackHelper(flags
, tile
, p1
, SetBit(p2
, 9), text
);
974 * Build a train depot
975 * @param flags operation to perform
976 * @param tile position of the train depot
977 * @param p1 rail type
978 * @param p2 bit 0..1 entrance direction (DiagDirection)
980 * @return the cost of this operation or an error
982 * @todo When checking for the tile slope,
983 * distinguish between "Flat land required" and "land sloped in wrong direction"
985 CommandCost
CmdBuildTrainDepot(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
987 /* check railtype and valid direction for depot (0 through 3), 4 in total */
988 RailType railtype
= Extract
<RailType
, 0, 6>(p1
);
989 if (!ValParamRailtype(railtype
)) return CMD_ERROR
;
991 Slope tileh
= GetTileSlope(tile
);
993 DiagDirection dir
= Extract
<DiagDirection
, 0, 2>(p2
);
995 CommandCost
cost(EXPENSES_CONSTRUCTION
);
997 /* Prohibit construction if
998 * The tile is non-flat AND
999 * 1) build-on-slopes is disabled
1000 * 2) the tile is steep i.e. spans two height levels
1001 * 3) the exit points in the wrong direction
1004 if (tileh
!= SLOPE_FLAT
) {
1005 if (!_settings_game
.construction
.build_on_slopes
|| !CanBuildDepotByTileh(dir
, tileh
)) {
1006 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
1008 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
1011 cost
.AddCost(DoCommand(flags
, CMD_LANDSCAPE_CLEAR
, tile
, 0, 0));
1012 if (cost
.Failed()) return cost
;
1014 if (IsBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
1016 if (!Depot::CanAllocateItem()) return CMD_ERROR
;
1018 if (flags
& DC_EXEC
) {
1019 Depot
*d
= new Depot(tile
);
1020 d
->build_date
= _date
;
1022 MakeRailDepot(tile
, _current_company
, d
->index
, dir
, railtype
);
1023 MarkTileDirtyByTile(tile
);
1026 Company::Get(_current_company
)->infrastructure
.rail
[railtype
]++;
1027 DirtyCompanyInfrastructureWindows(_current_company
);
1029 AddSideToSignalBuffer(tile
, INVALID_DIAGDIR
, _current_company
);
1030 YapfNotifyTrackLayoutChange(tile
, DiagDirToDiagTrack(dir
));
1033 cost
.AddCost(_price
[PR_BUILD_DEPOT_TRAIN
]);
1034 cost
.AddCost(RailBuildCost(railtype
));
1039 * Build signals, alternate between double/single, signal/semaphore,
1040 * pre/exit/combo-signals, and what-else not. If the rail piece does not
1041 * have any signals, bit 4 (cycle signal-type) is ignored
1042 * @param flags operation to perform
1043 * @param tile tile where to build the signals
1044 * @param p1 various bitstuffed elements
1045 * - p1 = (bit 0-2) - track-orientation, valid values: 0-5 (Track enum)
1046 * - p1 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal or (for bit 7) toggle variant (CTRL-toggle)
1047 * - p1 = (bit 4) - 0 = signals, 1 = semaphores
1048 * - p1 = (bit 5-7) - type of the signal, for valid values see enum SignalType in rail_map.h
1049 * - p1 = (bit 8) - convert the present signal type and variant
1050 * - p1 = (bit 9-11)- start cycle from this signal type
1051 * - p1 = (bit 12-14)-wrap around after this signal type
1052 * - p1 = (bit 15-16)-cycle the signal direction this many times
1053 * - p1 = (bit 17) - 1 = don't modify an existing signal but don't fail either, 0 = always set new signal type
1054 * @param p2 used for CmdBuildManySignals() to copy direction of first signal
1055 * @param text unused
1056 * @return the cost of this operation or an error
1057 * @todo p2 should be replaced by two bits for "along" and "against" the track.
1059 CommandCost
CmdBuildSingleSignal(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1061 Track track
= Extract
<Track
, 0, 3>(p1
);
1062 bool ctrl_pressed
= HasBit(p1
, 3); // was the CTRL button pressed
1063 SignalVariant sigvar
= (ctrl_pressed
^ HasBit(p1
, 4)) ? SIG_SEMAPHORE
: SIG_ELECTRIC
; // the signal variant of the new signal
1064 SignalType sigtype
= Extract
<SignalType
, 5, 3>(p1
); // the signal type of the new signal
1065 bool convert_signal
= HasBit(p1
, 8); // convert button pressed
1066 SignalType cycle_start
= Extract
<SignalType
, 9, 3>(p1
);
1067 SignalType cycle_stop
= Extract
<SignalType
, 12, 3>(p1
);
1068 uint num_dir_cycle
= GB(p1
, 15, 2);
1070 if (sigtype
> SIGTYPE_LAST
) return CMD_ERROR
;
1071 if (cycle_start
> cycle_stop
|| cycle_stop
> SIGTYPE_LAST
) return CMD_ERROR
;
1073 /* You can only build signals on plain rail tiles, and the selected track must exist */
1074 if (!ValParamTrackOrientation(track
) || !IsPlainRailTile(tile
) ||
1075 !HasTrack(tile
, track
)) {
1076 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
1078 /* Protect against invalid signal copying */
1079 if (p2
!= 0 && (p2
& SignalOnTrack(track
)) == 0) return CMD_ERROR
;
1081 CommandCost ret
= CheckTileOwnership(tile
);
1082 if (ret
.Failed()) return ret
;
1084 /* See if this is a valid track combination for signals (no overlap) */
1085 if (TracksOverlap(GetTrackBits(tile
))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK
);
1087 /* In case we don't want to change an existing signal, return without error. */
1088 if (HasBit(p1
, 17) && HasSignalOnTrack(tile
, track
)) return CommandCost();
1090 /* you can not convert a signal if no signal is on track */
1091 if (convert_signal
&& !HasSignalOnTrack(tile
, track
)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS
);
1094 if (!HasSignalOnTrack(tile
, track
)) {
1095 /* build new signals */
1096 cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_SIGNALS
]);
1098 if (p2
!= 0 && sigvar
!= GetSignalVariant(tile
, track
)) {
1099 /* convert signals <-> semaphores */
1100 cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_SIGNALS
] + _price
[PR_CLEAR_SIGNALS
]);
1102 } else if (convert_signal
) {
1103 /* convert button pressed */
1104 if (ctrl_pressed
|| GetSignalVariant(tile
, track
) != sigvar
) {
1105 /* convert electric <-> semaphore */
1106 cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_SIGNALS
] + _price
[PR_CLEAR_SIGNALS
]);
1108 /* it is free to change signal type: normal-pre-exit-combo */
1109 cost
= CommandCost();
1113 /* it is free to change orientation/pre-exit-combo signals */
1114 cost
= CommandCost();
1118 if (flags
& DC_EXEC
) {
1120 /* The new/changed signal could block our path. As this can lead to
1121 * stale reservations, we clear the path reservation here and try
1122 * to redo it later on. */
1123 if (HasReservedTracks(tile
, TrackToTrackBits(track
))) {
1124 v
= GetTrainForReservation(tile
, track
);
1125 if (v
!= nullptr) FreeTrainTrackReservation(v
);
1128 if (!HasSignals(tile
)) {
1129 /* there are no signals at all on this tile yet */
1130 SetHasSignals(tile
, true);
1131 SetSignalStates(tile
, 0xF); // all signals are on
1132 SetPresentSignals(tile
, 0); // no signals built by default
1133 SetSignalType(tile
, track
, sigtype
);
1134 SetSignalVariant(tile
, track
, sigvar
);
1137 /* Subtract old signal infrastructure count. */
1138 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
-= CountBits(GetPresentSignals(tile
));
1141 if (!HasSignalOnTrack(tile
, track
)) {
1142 /* build new signals */
1143 SetPresentSignals(tile
, GetPresentSignals(tile
) | (IsPbsSignal(sigtype
) ? KillFirstBit(SignalOnTrack(track
)) : SignalOnTrack(track
)));
1144 SetSignalType(tile
, track
, sigtype
);
1145 SetSignalVariant(tile
, track
, sigvar
);
1146 while (num_dir_cycle
-- > 0) CycleSignalSide(tile
, track
);
1148 if (convert_signal
) {
1149 /* convert signal button pressed */
1151 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1152 SetSignalVariant(tile
, track
, (GetSignalVariant(tile
, track
) == SIG_ELECTRIC
) ? SIG_SEMAPHORE
: SIG_ELECTRIC
);
1153 /* Query current signal type so the check for PBS signals below works. */
1154 sigtype
= GetSignalType(tile
, track
);
1156 /* convert the present signal to the chosen type and variant */
1157 SetSignalType(tile
, track
, sigtype
);
1158 SetSignalVariant(tile
, track
, sigvar
);
1159 if (IsPbsSignal(sigtype
) && (GetPresentSignals(tile
) & SignalOnTrack(track
)) == SignalOnTrack(track
)) {
1160 SetPresentSignals(tile
, (GetPresentSignals(tile
) & ~SignalOnTrack(track
)) | KillFirstBit(SignalOnTrack(track
)));
1164 } else if (ctrl_pressed
) {
1165 /* cycle between cycle_start and cycle_end */
1166 sigtype
= (SignalType
)(GetSignalType(tile
, track
) + 1);
1168 if (sigtype
< cycle_start
|| sigtype
> cycle_stop
) sigtype
= cycle_start
;
1170 SetSignalType(tile
, track
, sigtype
);
1171 if (IsPbsSignal(sigtype
) && (GetPresentSignals(tile
) & SignalOnTrack(track
)) == SignalOnTrack(track
)) {
1172 SetPresentSignals(tile
, (GetPresentSignals(tile
) & ~SignalOnTrack(track
)) | KillFirstBit(SignalOnTrack(track
)));
1175 /* cycle the signal side: both -> left -> right -> both -> ... */
1176 CycleSignalSide(tile
, track
);
1177 /* Query current signal type so the check for PBS signals below works. */
1178 sigtype
= GetSignalType(tile
, track
);
1182 /* If CmdBuildManySignals is called with copying signals, just copy the
1183 * direction of the first signal given as parameter by CmdBuildManySignals */
1184 SetPresentSignals(tile
, (GetPresentSignals(tile
) & ~SignalOnTrack(track
)) | (p2
& SignalOnTrack(track
)));
1185 SetSignalVariant(tile
, track
, sigvar
);
1186 SetSignalType(tile
, track
, sigtype
);
1189 /* Add new signal infrastructure count. */
1190 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
+= CountBits(GetPresentSignals(tile
));
1191 DirtyCompanyInfrastructureWindows(GetTileOwner(tile
));
1193 if (IsPbsSignal(sigtype
)) {
1194 /* PBS signals should show red unless they are on reserved tiles without a train. */
1195 uint mask
= GetPresentSignals(tile
) & SignalOnTrack(track
);
1196 SetSignalStates(tile
, (GetSignalStates(tile
) & ~mask
) | ((HasBit(GetRailReservationTrackBits(tile
), track
) && EnsureNoVehicleOnGround(tile
).Succeeded() ? UINT_MAX
: 0) & mask
));
1198 MarkTileDirtyByTile(tile
);
1199 AddTrackToSignalBuffer(tile
, track
, _current_company
);
1200 YapfNotifyTrackLayoutChange(tile
, track
);
1201 if (v
!= nullptr && v
->track
!= TRACK_BIT_DEPOT
) {
1202 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1203 if (!(((v
->vehstatus
& VS_STOPPED
) && v
->cur_speed
== 0) || v
->current_order
.IsType(OT_LOADING
)) ||
1204 !IsSafeWaitingPosition(v
, v
->tile
, v
->GetVehicleTrackdir(), true, _settings_game
.pf
.forbid_90_deg
)) {
1205 TryPathReserve(v
, true);
1213 static bool AdvanceSignalAutoFill(TileIndex
&tile
, Trackdir
&trackdir
, bool remove
)
1215 /* We only process starting tiles of tunnels or bridges so jump to the other end before moving further. */
1216 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) tile
= GetOtherTunnelBridgeEnd(tile
);
1218 tile
= AddTileIndexDiffCWrap(tile
, _trackdelta
[trackdir
]);
1219 if (tile
== INVALID_TILE
) return false;
1221 /* Check for track bits on the new tile */
1222 TrackdirBits trackdirbits
= TrackStatusToTrackdirBits(GetTileTrackStatus(tile
, TRANSPORT_RAIL
, 0));
1224 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits
))) return false;
1225 trackdirbits
&= TrackdirReachesTrackdirs(trackdir
);
1227 /* No track bits, must stop */
1228 if (trackdirbits
== TRACKDIR_BIT_NONE
) return false;
1230 /* Get the first track dir */
1231 trackdir
= RemoveFirstTrackdir(&trackdirbits
);
1233 /* Any left? It's a junction so we stop */
1234 if (trackdirbits
!= TRACKDIR_BIT_NONE
) return false;
1236 switch (GetTileType(tile
)) {
1238 if (IsRailDepot(tile
)) return false;
1239 if (!remove
&& HasSignalOnTrack(tile
, TrackdirToTrack(trackdir
))) return false;
1243 if (!IsLevelCrossing(tile
)) return false;
1246 case MP_TUNNELBRIDGE
: {
1247 if (GetTunnelBridgeTransportType(tile
) != TRANSPORT_RAIL
) return false;
1248 if (GetTunnelBridgeDirection(tile
) != TrackdirToExitdir(trackdir
)) return false;
1252 default: return false;
1258 * Build many signals by dragging; AutoSignals
1259 * @param flags operation to perform
1260 * @param tile start tile of drag
1261 * @param p1 end tile of drag
1262 * @param p2 various bitstuffed elements
1263 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1264 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1265 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1266 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1267 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1268 * - p2 = (bit 7- 9) - default signal type
1269 * - p2 = (bit 10) - 0 = keep fixed distance, 1 = minimise gaps between signals
1270 * - p2 = (bit 24-31) - user defined signals_density
1271 * @param text unused
1272 * @return the cost of this operation or an error
1274 static CommandCost
CmdSignalTrackHelper(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1276 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1277 TileIndex start_tile
= tile
;
1279 Track track
= Extract
<Track
, 0, 3>(p2
);
1280 bool mode
= HasBit(p2
, 3);
1281 bool semaphores
= HasBit(p2
, 4);
1282 bool remove
= HasBit(p2
, 5);
1283 bool autofill
= HasBit(p2
, 6);
1284 bool minimise_gaps
= HasBit(p2
, 10);
1285 int signal_density
= GB(p2
, 24, 8);
1287 if (p1
>= MapSize() || !ValParamTrackOrientation(track
)) return CMD_ERROR
;
1288 TileIndex end_tile
= p1
;
1289 if (signal_density
== 0 || signal_density
> 20) return CMD_ERROR
;
1291 if (!IsPlainRailTile(tile
)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
1293 /* Interpret signal_density as the logical length of said amount of tiles in X/Y direction. */
1294 signal_density
*= TILE_AXIAL_DISTANCE
;
1296 Trackdir trackdir
= TrackToTrackdir(track
);
1297 CommandCost ret
= ValidateAutoDrag(&trackdir
, tile
, end_tile
);
1298 if (ret
.Failed()) return ret
;
1300 track
= TrackdirToTrack(trackdir
); // trackdir might have changed, keep track in sync
1301 Trackdir start_trackdir
= trackdir
;
1303 /* Must start on a valid track to be able to avoid loops */
1304 if (!HasTrack(tile
, track
)) return CMD_ERROR
;
1306 SignalType sigtype
= (SignalType
)GB(p2
, 7, 3);
1307 if (sigtype
> SIGTYPE_LAST
) return CMD_ERROR
;
1310 /* copy the signal-style of the first rail-piece if existing */
1311 if (HasSignalOnTrack(tile
, track
)) {
1312 signals
= GetPresentSignals(tile
) & SignalOnTrack(track
);
1313 assert(signals
!= 0);
1315 /* copy signal/semaphores style (independent of CTRL) */
1316 semaphores
= GetSignalVariant(tile
, track
) != SIG_ELECTRIC
;
1318 sigtype
= GetSignalType(tile
, track
);
1319 /* Don't but copy entry or exit-signal type */
1320 if (sigtype
== SIGTYPE_ENTRY
|| sigtype
== SIGTYPE_EXIT
) sigtype
= SIGTYPE_NORMAL
;
1321 } else { // no signals exist, drag a two-way signal stretch
1322 signals
= IsPbsSignal(sigtype
) ? SignalAlongTrackdir(trackdir
) : SignalOnTrack(track
);
1325 byte signal_dir
= 0;
1326 if (signals
& SignalAlongTrackdir(trackdir
)) SetBit(signal_dir
, 0);
1327 if (signals
& SignalAgainstTrackdir(trackdir
)) SetBit(signal_dir
, 1);
1329 /* signal_ctr - amount of tiles already processed
1330 * last_used_ctr - amount of tiles before previously placed signal
1331 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1332 * last_suitable_ctr - amount of tiles before last possible signal place
1333 * last_suitable_tile - last tile where it is possible to place a signal
1334 * last_suitable_trackdir - trackdir of the last tile
1336 * trackdir - trackdir to build with autorail
1337 * semaphores - semaphores or signals
1338 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1339 * and convert all others to semaphore/signal
1340 * remove - 1 remove signals, 0 build signals */
1342 int last_used_ctr
= -signal_density
; // to force signal at first tile
1343 int last_suitable_ctr
= 0;
1344 TileIndex last_suitable_tile
= INVALID_TILE
;
1345 Trackdir last_suitable_trackdir
= INVALID_TRACKDIR
;
1346 CommandCost last_error
= CMD_ERROR
;
1347 bool had_success
= false;
1349 SB(param1
, 3, 1, mode
);
1350 SB(param1
, 4, 1, semaphores
);
1351 SB(param1
, 5, 3, sigtype
);
1353 auto build_signal
= [&](TileIndex tile
, Trackdir trackdir
, bool test_only
) {
1354 SB(param1
, 0, 3, TrackdirToTrack(trackdir
));
1355 SB(param1
, 17, 1, (!remove
&& signal_ctr
== 0 ? 1 : 0));
1357 /* Pick the correct orientation for the track direction */
1359 if (HasBit(signal_dir
, 0)) signals
|= SignalAlongTrackdir(trackdir
);
1360 if (HasBit(signal_dir
, 1)) signals
|= SignalAgainstTrackdir(trackdir
);
1362 CommandCost ret
= DoCommand(test_only
? flags
& ~DC_EXEC
: flags
, remove
? CMD_REMOVE_SIGNALS
: CMD_BUILD_SIGNALS
, tile
, param1
, signals
);
1364 if (test_only
) return ret
.Succeeded();
1366 if (ret
.Succeeded()) {
1368 total_cost
.AddCost(ret
);
1370 /* The "No railway" error is the least important one. */
1371 if (ret
.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
||
1372 last_error
.GetErrorMessage() == INVALID_STRING_ID
) {
1376 return ret
.Succeeded();
1381 /* In remove mode last_* stuff doesn't matter, we simply try to clear every tile. */
1382 build_signal(tile
, trackdir
, false);
1383 } else if (minimise_gaps
) {
1384 /* We're trying to minimize gaps wherever possible, so keep track of last suitable
1385 * position and use it if current gap exceeds required signal density. */
1387 if (signal_ctr
> last_used_ctr
+ signal_density
&& last_suitable_tile
!= INVALID_TILE
) {
1388 /* We overshot so build a signal in last good location. */
1389 if (build_signal(last_suitable_tile
, last_suitable_trackdir
, false)) {
1390 last_suitable_tile
= INVALID_TILE
;
1391 last_used_ctr
= last_suitable_ctr
;
1395 if (signal_ctr
== last_used_ctr
+ signal_density
) {
1396 /* Current gap matches the required density, build a signal. */
1397 if (build_signal(tile
, trackdir
, false)) {
1398 last_used_ctr
= signal_ctr
;
1399 last_suitable_tile
= INVALID_TILE
;
1402 /* Test tile for a potential signal spot. */
1403 if (build_signal(tile
, trackdir
, true)) {
1404 last_suitable_tile
= tile
;
1405 last_suitable_ctr
= signal_ctr
;
1406 last_suitable_trackdir
= trackdir
;
1409 } else if(signal_ctr
>= last_used_ctr
+ signal_density
) {
1410 /* We're always keeping regular interval between signals so doesn't matter whether we succeed or not. */
1411 build_signal(tile
, trackdir
, false);
1412 last_used_ctr
= signal_ctr
;
1416 switch (GetTileType(tile
)) {
1418 signal_ctr
+= (IsDiagonalTrackdir(trackdir
) ? TILE_AXIAL_DISTANCE
: TILE_CORNER_DISTANCE
);
1422 signal_ctr
+= TILE_AXIAL_DISTANCE
;
1425 case MP_TUNNELBRIDGE
: {
1426 uint len
= (GetTunnelBridgeLength(tile
, GetOtherTunnelBridgeEnd(tile
)) + 2) * TILE_AXIAL_DISTANCE
;
1427 if (remove
|| minimise_gaps
) {
1430 /* To keep regular interval we need to emulate placing signals on a bridge.
1431 * We start with TILE_AXIAL_DISTANCE as one bridge tile gets processed in the main loop. */
1432 signal_ctr
+= TILE_AXIAL_DISTANCE
;
1433 for(uint i
= TILE_AXIAL_DISTANCE
; i
< len
; i
+= TILE_AXIAL_DISTANCE
) {
1434 if (signal_ctr
>= last_used_ctr
+ signal_density
) last_used_ctr
= signal_ctr
;
1435 signal_ctr
+= TILE_AXIAL_DISTANCE
;
1444 if (!AdvanceSignalAutoFill(tile
, trackdir
, remove
)) break;
1446 /* Prevent possible loops */
1447 if (tile
== start_tile
&& trackdir
== start_trackdir
) break;
1449 if (tile
== end_tile
) break;
1451 signal_ctr
+= (IsDiagonalTrackdir(trackdir
) ? TILE_AXIAL_DISTANCE
: TILE_CORNER_DISTANCE
);
1452 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1454 tile
+= ToTileIndexDiff(_trackdelta
[trackdir
]);
1455 if (!IsDiagonalTrackdir(trackdir
)) ToggleBit(trackdir
, 0);
1459 /* We may end up with the current gap exceeding the signal density so fix that if needed. */
1460 if (!remove
&& minimise_gaps
&& signal_ctr
> last_used_ctr
+ signal_density
&& last_suitable_tile
!= INVALID_TILE
) {
1461 build_signal(last_suitable_tile
, last_suitable_trackdir
, false);
1464 return had_success
? total_cost
: last_error
;
1468 * Build signals on a stretch of track.
1469 * Stub for the unified signal builder/remover
1470 * @param flags operation to perform
1471 * @param tile start tile of drag
1472 * @param p1 end tile of drag
1473 * @param p2 various bitstuffed elements
1474 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1475 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1476 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1477 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1478 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1479 * - p2 = (bit 7- 9) - default signal type
1480 * - p2 = (bit 24-31) - user defined signals_density
1481 * @param text unused
1482 * @return the cost of this operation or an error
1483 * @see CmdSignalTrackHelper
1485 CommandCost
CmdBuildSignalTrack(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1487 return CmdSignalTrackHelper(flags
, tile
, p1
, p2
, text
);
1492 * @param flags operation to perform
1493 * @param tile coordinates where signal is being deleted from
1494 * @param p1 various bitstuffed elements, only track information is used
1495 * - (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1496 * - (bit 3) - override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1497 * - (bit 4) - 0 = signals, 1 = semaphores
1499 * @param text unused
1500 * @return the cost of this operation or an error
1502 CommandCost
CmdRemoveSingleSignal(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1504 Track track
= Extract
<Track
, 0, 3>(p1
);
1506 if (!ValParamTrackOrientation(track
) || !IsPlainRailTile(tile
) || !HasTrack(tile
, track
)) {
1507 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK
);
1509 if (!HasSignalOnTrack(tile
, track
)) {
1510 return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS
);
1513 /* Only water can remove signals from anyone */
1514 if (_current_company
!= OWNER_WATER
) {
1515 CommandCost ret
= CheckTileOwnership(tile
);
1516 if (ret
.Failed()) return ret
;
1520 if (flags
& DC_EXEC
) {
1522 if (HasReservedTracks(tile
, TrackToTrackBits(track
))) {
1523 v
= GetTrainForReservation(tile
, track
);
1524 } else if (IsPbsSignal(GetSignalType(tile
, track
))) {
1525 /* PBS signal, might be the end of a path reservation. */
1526 Trackdir td
= TrackToTrackdir(track
);
1527 for (int i
= 0; v
== nullptr && i
< 2; i
++, td
= ReverseTrackdir(td
)) {
1528 /* Only test the active signal side. */
1529 if (!HasSignalOnTrackdir(tile
, ReverseTrackdir(td
))) continue;
1530 TileIndex next
= TileAddByDiagDir(tile
, TrackdirToExitdir(td
));
1531 TrackBits tracks
= TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td
));
1532 if (HasReservedTracks(next
, tracks
)) {
1533 v
= GetTrainForReservation(next
, TrackBitsToTrack(GetReservedTrackbits(next
) & tracks
));
1537 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
-= CountBits(GetPresentSignals(tile
));
1538 SetPresentSignals(tile
, GetPresentSignals(tile
) & ~SignalOnTrack(track
));
1539 Company::Get(GetTileOwner(tile
))->infrastructure
.signal
+= CountBits(GetPresentSignals(tile
));
1540 DirtyCompanyInfrastructureWindows(GetTileOwner(tile
));
1542 /* removed last signal from tile? */
1543 if (GetPresentSignals(tile
) == 0) {
1544 SetSignalStates(tile
, 0);
1545 SetHasSignals(tile
, false);
1546 SetSignalVariant(tile
, INVALID_TRACK
, SIG_ELECTRIC
); // remove any possible semaphores
1549 AddTrackToSignalBuffer(tile
, track
, GetTileOwner(tile
));
1550 YapfNotifyTrackLayoutChange(tile
, track
);
1551 if (v
!= nullptr) TryPathReserve(v
, false);
1553 MarkTileDirtyByTile(tile
);
1556 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_SIGNALS
]);
1560 * Remove signals on a stretch of track.
1561 * Stub for the unified signal builder/remover
1562 * @param flags operation to perform
1563 * @param tile start tile of drag
1564 * @param p1 end tile of drag
1565 * @param p2 various bitstuffed elements
1566 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1567 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1568 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1569 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1570 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1571 * - p2 = (bit 7- 9) - default signal type
1572 * - p2 = (bit 24-31) - user defined signals_density
1573 * @param text unused
1574 * @return the cost of this operation or an error
1575 * @see CmdSignalTrackHelper
1577 CommandCost
CmdRemoveSignalTrack(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1579 return CmdSignalTrackHelper(flags
, tile
, p1
, SetBit(p2
, 5), text
); // bit 5 is remove bit
1582 /** Update power of train under which is the railtype being converted */
1583 static Vehicle
*UpdateTrainPowerProc(Vehicle
*v
, void *data
)
1585 if (v
->type
!= VEH_TRAIN
) return nullptr;
1587 TrainList
*affected_trains
= static_cast<TrainList
*>(data
);
1588 include(*affected_trains
, Train::From(v
)->First());
1594 * Convert one rail type to the other. You can convert normal rail to
1595 * monorail/maglev easily or vice-versa.
1596 * @param flags operation to perform
1597 * @param tile end tile of rail conversion drag
1598 * @param p1 start tile of drag
1599 * @param p2 various bitstuffed elements:
1600 * - p2 = (bit 0- 5) new railtype to convert to.
1601 * - p2 = (bit 6) build diagonally or not.
1602 * @param text unused
1603 * @return the cost of this operation or an error
1605 CommandCost
CmdConvertRail(DoCommandFlag flags
, TileIndex tile
, uint32 p1
, uint32 p2
, const std::string
&text
)
1607 RailType totype
= Extract
<RailType
, 0, 6>(p2
);
1608 TileIndex area_start
= p1
;
1609 TileIndex area_end
= tile
;
1610 bool diagonal
= HasBit(p2
, 6);
1612 if (!ValParamRailtype(totype
)) return CMD_ERROR
;
1613 if (area_start
>= MapSize()) return CMD_ERROR
;
1615 TrainList affected_trains
;
1617 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1618 CommandCost error
= CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK
); // by default, there is no track to convert.
1619 bool found_convertible_track
= false; // whether we actually did convert some track (see bug #7633)
1621 TileIterator
*iter
= diagonal
? (TileIterator
*)new DiagonalTileIterator(area_start
, area_end
) : new OrthogonalTileIterator(area_start
, area_end
);
1622 for (; (tile
= *iter
) != INVALID_TILE
; ++(*iter
)) {
1623 TileType tt
= GetTileType(tile
);
1625 /* Check if there is any track on tile */
1630 if (!HasStationRail(tile
)) continue;
1633 if (!IsLevelCrossing(tile
)) continue;
1634 if (RailNoLevelCrossings(totype
)) {
1635 error
.MakeError(STR_ERROR_CROSSING_DISALLOWED_RAIL
);
1639 case MP_TUNNELBRIDGE
:
1640 if (GetTunnelBridgeTransportType(tile
) != TRANSPORT_RAIL
) continue;
1645 /* Original railtype we are converting from */
1646 RailType type
= GetRailType(tile
);
1648 /* Converting to the same type or converting 'hidden' elrail -> rail */
1649 if (type
== totype
|| (_settings_game
.vehicle
.disable_elrails
&& totype
== RAILTYPE_RAIL
&& type
== RAILTYPE_ELECTRIC
)) continue;
1651 /* Trying to convert other's rail */
1652 CommandCost ret
= CheckTileOwnership(tile
);
1658 std::vector
<Train
*> vehicles_affected
;
1660 /* Vehicle on the tile when not converting Rail <-> ElRail
1661 * Tunnels and bridges have special check later */
1662 if (tt
!= MP_TUNNELBRIDGE
) {
1663 if (!IsCompatibleRail(type
, totype
)) {
1664 CommandCost ret
= IsPlainRailTile(tile
) ? EnsureNoTrainOnTrackBits(tile
, GetTrackBits(tile
)) : EnsureNoVehicleOnGround(tile
);
1670 if (flags
& DC_EXEC
) { // we can safely convert, too
1671 TrackBits reserved
= GetReservedTrackbits(tile
);
1673 while ((track
= RemoveFirstTrack(&reserved
)) != INVALID_TRACK
) {
1674 Train
*v
= GetTrainForReservation(tile
, track
);
1675 if (v
!= nullptr && !HasPowerOnRail(v
->railtype
, totype
)) {
1676 /* No power on new rail type, reroute. */
1677 FreeTrainTrackReservation(v
);
1678 vehicles_affected
.push_back(v
);
1682 /* Update the company infrastructure counters. */
1683 if (!IsRailStationTile(tile
) || !IsStationTileBlocked(tile
)) {
1684 Company
*c
= Company::Get(GetTileOwner(tile
));
1685 uint num_pieces
= IsLevelCrossingTile(tile
) ? LEVELCROSSING_TRACKBIT_FACTOR
: 1;
1686 if (IsPlainRailTile(tile
)) {
1687 TrackBits bits
= GetTrackBits(tile
);
1688 num_pieces
= CountBits(bits
);
1689 if (TracksOverlap(bits
)) num_pieces
*= num_pieces
;
1691 c
->infrastructure
.rail
[type
] -= num_pieces
;
1692 c
->infrastructure
.rail
[totype
] += num_pieces
;
1693 DirtyCompanyInfrastructureWindows(c
->index
);
1696 SetRailType(tile
, totype
);
1697 MarkTileDirtyByTile(tile
);
1698 /* update power of train on this tile */
1699 FindVehicleOnPos(tile
, &affected_trains
, &UpdateTrainPowerProc
);
1705 switch (GetRailTileType(tile
)) {
1706 case RAIL_TILE_DEPOT
:
1707 if (flags
& DC_EXEC
) {
1708 /* notify YAPF about the track layout change */
1709 YapfNotifyTrackLayoutChange(tile
, GetRailDepotTrack(tile
));
1711 /* Update build vehicle window related to this depot */
1712 InvalidateWindowData(WC_VEHICLE_DEPOT
, tile
);
1713 InvalidateWindowData(WC_BUILD_VEHICLE
, tile
);
1715 found_convertible_track
= true;
1716 cost
.AddCost(RailConvertCost(type
, totype
));
1719 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1720 if (flags
& DC_EXEC
) {
1721 /* notify YAPF about the track layout change */
1722 TrackBits tracks
= GetTrackBits(tile
);
1723 while (tracks
!= TRACK_BIT_NONE
) {
1724 YapfNotifyTrackLayoutChange(tile
, RemoveFirstTrack(&tracks
));
1727 found_convertible_track
= true;
1728 cost
.AddCost(RailConvertCost(type
, totype
) * CountBits(GetTrackBits(tile
)));
1733 case MP_TUNNELBRIDGE
: {
1734 TileIndex endtile
= GetOtherTunnelBridgeEnd(tile
);
1736 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1737 * it would cause assert because of different test and exec runs */
1738 if (endtile
< tile
) {
1740 if (DiagonalTileArea(area_start
, area_end
).Contains(endtile
)) continue;
1742 if (OrthogonalTileArea(area_start
, area_end
).Contains(endtile
)) continue;
1746 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1747 if (!IsCompatibleRail(GetRailType(tile
), totype
)) {
1748 CommandCost ret
= TunnelBridgeIsFree(tile
, endtile
);
1755 if (flags
& DC_EXEC
) {
1756 Track track
= DiagDirToDiagTrack(GetTunnelBridgeDirection(tile
));
1757 if (HasTunnelBridgeReservation(tile
)) {
1758 Train
*v
= GetTrainForReservation(tile
, track
);
1759 if (v
!= nullptr && !HasPowerOnRail(v
->railtype
, totype
)) {
1760 /* No power on new rail type, reroute. */
1761 FreeTrainTrackReservation(v
);
1762 vehicles_affected
.push_back(v
);
1766 /* Update the company infrastructure counters. */
1767 uint num_pieces
= (GetTunnelBridgeLength(tile
, endtile
) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR
;
1768 Company
*c
= Company::Get(GetTileOwner(tile
));
1769 c
->infrastructure
.rail
[GetRailType(tile
)] -= num_pieces
;
1770 c
->infrastructure
.rail
[totype
] += num_pieces
;
1771 DirtyCompanyInfrastructureWindows(c
->index
);
1773 SetRailType(tile
, totype
);
1774 SetRailType(endtile
, totype
);
1776 FindVehicleOnPos(tile
, &affected_trains
, &UpdateTrainPowerProc
);
1777 FindVehicleOnPos(endtile
, &affected_trains
, &UpdateTrainPowerProc
);
1779 YapfNotifyTrackLayoutChange(tile
, track
);
1780 YapfNotifyTrackLayoutChange(endtile
, track
);
1782 if (IsBridge(tile
)) {
1783 MarkBridgeDirty(tile
);
1785 MarkTileDirtyByTile(tile
);
1786 MarkTileDirtyByTile(endtile
);
1790 found_convertible_track
= true;
1791 cost
.AddCost((GetTunnelBridgeLength(tile
, endtile
) + 2) * RailConvertCost(type
, totype
));
1795 default: // MP_STATION, MP_ROAD
1796 if (flags
& DC_EXEC
) {
1797 Track track
= ((tt
== MP_STATION
) ? GetRailStationTrack(tile
) : GetCrossingRailTrack(tile
));
1798 YapfNotifyTrackLayoutChange(tile
, track
);
1801 found_convertible_track
= true;
1802 cost
.AddCost(RailConvertCost(type
, totype
));
1806 for (uint i
= 0; i
< vehicles_affected
.size(); ++i
) {
1807 TryPathReserve(vehicles_affected
[i
], true);
1811 if (flags
& DC_EXEC
) {
1812 /* Railtype changed, update trains as when entering different track */
1813 for (Train
*v
: affected_trains
) {
1814 v
->ConsistChanged(CCF_TRACK
);
1819 return found_convertible_track
? cost
: error
;
1822 static CommandCost
RemoveTrainDepot(TileIndex tile
, DoCommandFlag flags
)
1824 if (_current_company
!= OWNER_WATER
) {
1825 CommandCost ret
= CheckTileOwnership(tile
);
1826 if (ret
.Failed()) return ret
;
1829 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1830 if (ret
.Failed()) return ret
;
1832 if (flags
& DC_EXEC
) {
1833 /* read variables before the depot is removed */
1834 DiagDirection dir
= GetRailDepotDirection(tile
);
1835 Owner owner
= GetTileOwner(tile
);
1838 if (HasDepotReservation(tile
)) {
1839 v
= GetTrainForReservation(tile
, DiagDirToDiagTrack(dir
));
1840 if (v
!= nullptr) FreeTrainTrackReservation(v
);
1843 Company::Get(owner
)->infrastructure
.rail
[GetRailType(tile
)]--;
1844 DirtyCompanyInfrastructureWindows(owner
);
1846 delete Depot::GetByTile(tile
);
1847 DoClearSquare(tile
);
1848 AddSideToSignalBuffer(tile
, dir
, owner
);
1849 YapfNotifyTrackLayoutChange(tile
, DiagDirToDiagTrack(dir
));
1850 if (v
!= nullptr) TryPathReserve(v
, true);
1853 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_DEPOT_TRAIN
]);
1856 static CommandCost
ClearTile_Track(TileIndex tile
, DoCommandFlag flags
)
1858 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1860 if (flags
& DC_AUTO
) {
1861 if (!IsTileOwner(tile
, _current_company
)) {
1862 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER
);
1865 if (IsPlainRail(tile
)) {
1866 return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
1868 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
1872 switch (GetRailTileType(tile
)) {
1873 case RAIL_TILE_SIGNALS
:
1874 case RAIL_TILE_NORMAL
: {
1875 Slope tileh
= GetTileSlope(tile
);
1876 /* Is there flat water on the lower halftile that gets cleared expensively? */
1877 bool water_ground
= (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh
));
1879 TrackBits tracks
= GetTrackBits(tile
);
1880 while (tracks
!= TRACK_BIT_NONE
) {
1881 Track track
= RemoveFirstTrack(&tracks
);
1882 CommandCost ret
= DoCommand(flags
, CMD_REMOVE_SINGLE_RAIL
, tile
, 0, track
);
1883 if (ret
.Failed()) return ret
;
1887 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
1888 * Same holds for non-companies clearing the tile, e.g. disasters. */
1889 if (water_ground
&& !(flags
& DC_BANKRUPT
) && Company::IsValidID(_current_company
)) {
1890 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1891 if (ret
.Failed()) return ret
;
1893 /* The track was removed, and left a coast tile. Now also clear the water. */
1894 if (flags
& DC_EXEC
) {
1895 bool remove
= IsDockingTile(tile
);
1896 DoClearSquare(tile
);
1897 if (remove
) RemoveDockingTile(tile
);
1899 cost
.AddCost(_price
[PR_CLEAR_WATER
]);
1905 case RAIL_TILE_DEPOT
:
1906 return RemoveTrainDepot(tile
, flags
);
1914 * Get surface height in point (x,y)
1915 * On tiles with halftile foundations move (x,y) to a safe point wrt. track
1917 static uint
GetSaveSlopeZ(uint x
, uint y
, Track track
)
1920 case TRACK_UPPER
: x
&= ~0xF; y
&= ~0xF; break;
1921 case TRACK_LOWER
: x
|= 0xF; y
|= 0xF; break;
1922 case TRACK_LEFT
: x
|= 0xF; y
&= ~0xF; break;
1923 case TRACK_RIGHT
: x
&= ~0xF; y
|= 0xF; break;
1926 return GetSlopePixelZ(x
, y
);
1929 static void DrawSingleSignal(TileIndex tile
, const RailtypeInfo
*rti
, Track track
, SignalState condition
, SignalOffsets image
, uint pos
)
1932 switch (_settings_game
.construction
.train_signal_side
) {
1933 case 0: side
= false; break; // left
1934 case 2: side
= true; break; // right
1935 default: side
= _settings_game
.vehicle
.road_side
!= 0; break; // driving side
1937 static const Point SignalPositions
[2][12] = {
1938 { // Signals on the left side
1939 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1940 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
1941 /* LOWER LOWER X X Y Y */
1942 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1943 }, { // Signals on the right side
1944 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1945 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
1946 /* LOWER LOWER X X Y Y */
1947 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1951 uint x
= TileX(tile
) * TILE_SIZE
+ SignalPositions
[side
][pos
].x
;
1952 uint y
= TileY(tile
) * TILE_SIZE
+ SignalPositions
[side
][pos
].y
;
1954 SignalType type
= GetSignalType(tile
, track
);
1955 SignalVariant variant
= GetSignalVariant(tile
, track
);
1957 SpriteID sprite
= GetCustomSignalSprite(rti
, tile
, type
, variant
, condition
);
1961 /* Normal electric signals are stored in a different sprite block than all other signals. */
1962 sprite
= (type
== SIGTYPE_NORMAL
&& variant
== SIG_ELECTRIC
) ? SPR_ORIGINAL_SIGNALS_BASE
: SPR_SIGNALS_BASE
- 16;
1963 sprite
+= type
* 16 + variant
* 64 + image
* 2 + condition
+ (type
> SIGTYPE_LAST_NOPBS
? 64 : 0);
1966 AddSortableSpriteToDraw(sprite
, PAL_NONE
, x
, y
, 1, 1, BB_HEIGHT_UNDER_BRIDGE
, GetSaveSlopeZ(x
, y
, track
));
1969 static uint32 _drawtile_track_palette
;
1973 /** Offsets for drawing fences */
1974 struct FenceOffset
{
1975 Corner height_ref
; //!< Corner to use height offset from.
1976 int x_offs
; //!< Bounding box X offset.
1977 int y_offs
; //!< Bounding box Y offset.
1978 int x_size
; //!< Bounding box X size.
1979 int y_size
; //!< Bounding box Y size.
1982 /** Offsets for drawing fences */
1983 static FenceOffset _fence_offsets
[] = {
1984 { CORNER_INVALID
, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
1985 { CORNER_INVALID
, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
1986 { CORNER_W
, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
1987 { CORNER_N
, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
1988 { CORNER_INVALID
, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
1989 { CORNER_INVALID
, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
1990 { CORNER_INVALID
, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
1991 { CORNER_INVALID
, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
1992 { CORNER_INVALID
, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
1993 { CORNER_INVALID
, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
1994 { CORNER_E
, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
1995 { CORNER_S
, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
1996 { CORNER_INVALID
, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
1997 { CORNER_INVALID
, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
1998 { CORNER_INVALID
, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
1999 { CORNER_INVALID
, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
2003 * Draw a track fence.
2004 * @param ti Tile drawing information.
2005 * @param base_image First fence sprite.
2006 * @param num_sprites Number of fence sprites.
2007 * @param rfo Fence to draw.
2009 static void DrawTrackFence(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
, RailFenceOffset rfo
)
2012 if (_fence_offsets
[rfo
].height_ref
!= CORNER_INVALID
) {
2013 z
+= GetSlopePixelZInCorner(RemoveHalftileSlope(ti
->tileh
), _fence_offsets
[rfo
].height_ref
);
2015 AddSortableSpriteToDraw(base_image
+ (rfo
% num_sprites
), _drawtile_track_palette
,
2016 ti
->x
+ _fence_offsets
[rfo
].x_offs
,
2017 ti
->y
+ _fence_offsets
[rfo
].y_offs
,
2018 _fence_offsets
[rfo
].x_size
,
2019 _fence_offsets
[rfo
].y_size
,
2024 * Draw fence at NW border matching the tile slope.
2026 static void DrawTrackFence_NW(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
2028 RailFenceOffset rfo
= RFO_FLAT_X_NW
;
2029 if (ti
->tileh
& SLOPE_NW
) rfo
= (ti
->tileh
& SLOPE_W
) ? RFO_SLOPE_SW_NW
: RFO_SLOPE_NE_NW
;
2030 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
2034 * Draw fence at SE border matching the tile slope.
2036 static void DrawTrackFence_SE(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
2038 RailFenceOffset rfo
= RFO_FLAT_X_SE
;
2039 if (ti
->tileh
& SLOPE_SE
) rfo
= (ti
->tileh
& SLOPE_S
) ? RFO_SLOPE_SW_SE
: RFO_SLOPE_NE_SE
;
2040 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
2044 * Draw fence at NE border matching the tile slope.
2046 static void DrawTrackFence_NE(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
2048 RailFenceOffset rfo
= RFO_FLAT_Y_NE
;
2049 if (ti
->tileh
& SLOPE_NE
) rfo
= (ti
->tileh
& SLOPE_E
) ? RFO_SLOPE_SE_NE
: RFO_SLOPE_NW_NE
;
2050 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
2054 * Draw fence at SW border matching the tile slope.
2056 static void DrawTrackFence_SW(const TileInfo
*ti
, SpriteID base_image
, uint num_sprites
)
2058 RailFenceOffset rfo
= RFO_FLAT_Y_SW
;
2059 if (ti
->tileh
& SLOPE_SW
) rfo
= (ti
->tileh
& SLOPE_S
) ? RFO_SLOPE_SE_SW
: RFO_SLOPE_NW_SW
;
2060 DrawTrackFence(ti
, base_image
, num_sprites
, rfo
);
2064 * Draw track fences.
2065 * @param ti Tile drawing information.
2066 * @param rti Rail type information.
2068 static void DrawTrackDetails(const TileInfo
*ti
, const RailtypeInfo
*rti
)
2070 /* Base sprite for track fences.
2071 * Note: Halftile slopes only have fences on the upper part. */
2072 uint num_sprites
= 0;
2073 SpriteID base_image
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_FENCES
, IsHalftileSlope(ti
->tileh
) ? TCX_UPPER_HALFTILE
: TCX_NORMAL
, &num_sprites
);
2074 if (base_image
== 0) {
2075 base_image
= SPR_TRACK_FENCE_FLAT_X
;
2079 assert(num_sprites
> 0);
2081 switch (GetRailGroundType(ti
->tile
)) {
2082 case RAIL_GROUND_FENCE_NW
: DrawTrackFence_NW(ti
, base_image
, num_sprites
); break;
2083 case RAIL_GROUND_FENCE_SE
: DrawTrackFence_SE(ti
, base_image
, num_sprites
); break;
2084 case RAIL_GROUND_FENCE_SENW
: DrawTrackFence_NW(ti
, base_image
, num_sprites
);
2085 DrawTrackFence_SE(ti
, base_image
, num_sprites
); break;
2086 case RAIL_GROUND_FENCE_NE
: DrawTrackFence_NE(ti
, base_image
, num_sprites
); break;
2087 case RAIL_GROUND_FENCE_SW
: DrawTrackFence_SW(ti
, base_image
, num_sprites
); break;
2088 case RAIL_GROUND_FENCE_NESW
: DrawTrackFence_NE(ti
, base_image
, num_sprites
);
2089 DrawTrackFence_SW(ti
, base_image
, num_sprites
); break;
2090 case RAIL_GROUND_FENCE_VERT1
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LEFT
); break;
2091 case RAIL_GROUND_FENCE_VERT2
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_RIGHT
); break;
2092 case RAIL_GROUND_FENCE_HORIZ1
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_UPPER
); break;
2093 case RAIL_GROUND_FENCE_HORIZ2
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LOWER
); break;
2094 case RAIL_GROUND_WATER
: {
2095 Corner track_corner
;
2096 if (IsHalftileSlope(ti
->tileh
)) {
2097 /* Steep slope or one-corner-raised slope with halftile foundation */
2098 track_corner
= GetHalftileSlopeCorner(ti
->tileh
);
2100 /* Three-corner-raised slope */
2101 track_corner
= OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti
->tileh
)));
2103 switch (track_corner
) {
2104 case CORNER_W
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LEFT
); break;
2105 case CORNER_S
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_LOWER
); break;
2106 case CORNER_E
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_RIGHT
); break;
2107 case CORNER_N
: DrawTrackFence(ti
, base_image
, num_sprites
, RFO_FLAT_UPPER
); break;
2108 default: NOT_REACHED();
2116 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2117 static const int INF
= 1000; // big number compared to tilesprite size
2118 static const SubSprite _halftile_sub_sprite
[4] = {
2119 { -INF
, -INF
, 32 - 33, INF
}, // CORNER_W, clip 33 pixels from right
2120 { -INF
, 0 + 7, INF
, INF
}, // CORNER_S, clip 7 pixels from top
2121 { -31 + 33, -INF
, INF
, INF
}, // CORNER_E, clip 33 pixels from left
2122 { -INF
, -INF
, INF
, 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2125 static inline void DrawTrackSprite(SpriteID sprite
, PaletteID pal
, const TileInfo
*ti
, Slope s
)
2127 DrawGroundSprite(sprite
, pal
, nullptr, 0, (ti
->tileh
& s
) ? -8 : 0);
2130 static void DrawTrackBitsOverlay(TileInfo
*ti
, TrackBits track
, const RailtypeInfo
*rti
)
2132 RailGroundType rgt
= GetRailGroundType(ti
->tile
);
2133 Foundation f
= GetRailFoundation(ti
->tileh
, track
);
2134 Corner halftile_corner
= CORNER_INVALID
;
2136 if (IsNonContinuousFoundation(f
)) {
2137 /* Save halftile corner */
2138 halftile_corner
= (f
== FOUNDATION_STEEP_BOTH
? GetHighestSlopeCorner(ti
->tileh
) : GetHalftileFoundationCorner(f
));
2139 /* Draw lower part first */
2140 track
&= ~CornerToTrackBits(halftile_corner
);
2141 f
= (f
== FOUNDATION_STEEP_BOTH
? FOUNDATION_STEEP_LOWER
: FOUNDATION_NONE
);
2144 DrawFoundation(ti
, f
);
2145 /* DrawFoundation modifies ti */
2148 if (rgt
== RAIL_GROUND_WATER
) {
2149 if (track
!= TRACK_BIT_NONE
|| IsSteepSlope(ti
->tileh
)) {
2150 /* three-corner-raised slope or steep slope with track on upper part */
2151 DrawShoreTile(ti
->tileh
);
2153 /* single-corner-raised slope with track on upper part */
2154 DrawGroundSprite(SPR_FLAT_WATER_TILE
, PAL_NONE
);
2160 case RAIL_GROUND_BARREN
: image
= SPR_FLAT_BARE_LAND
; break;
2161 case RAIL_GROUND_ICE_DESERT
: image
= SPR_FLAT_SNOW_DESERT_TILE
; break;
2162 default: image
= SPR_FLAT_GRASS_TILE
; break;
2165 image
+= SlopeToSpriteOffset(ti
->tileh
);
2167 DrawGroundSprite(image
, PAL_NONE
);
2170 bool no_combine
= ti
->tileh
== SLOPE_FLAT
&& HasBit(rti
->flags
, RTF_NO_SPRITE_COMBINE
);
2171 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
2172 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, no_combine
? RTSG_GROUND_COMPLETE
: RTSG_GROUND
);
2173 TrackBits pbs
= _settings_client
.gui
.show_track_reservation
? GetRailReservationTrackBits(ti
->tile
) : TRACK_BIT_NONE
;
2175 if (track
== TRACK_BIT_NONE
) {
2176 /* Half-tile foundation, no track here? */
2177 } else if (no_combine
) {
2178 /* Use trackbits as direct index from ground sprite, subtract 1
2179 * because there is no sprite for no bits. */
2180 DrawGroundSprite(ground
+ track
- 1, PAL_NONE
);
2182 /* Draw reserved track bits */
2183 if (pbs
& TRACK_BIT_X
) DrawGroundSprite(overlay
+ RTO_X
, PALETTE_CRASH
);
2184 if (pbs
& TRACK_BIT_Y
) DrawGroundSprite(overlay
+ RTO_Y
, PALETTE_CRASH
);
2185 if (pbs
& TRACK_BIT_UPPER
) DrawTrackSprite(overlay
+ RTO_N
, PALETTE_CRASH
, ti
, SLOPE_N
);
2186 if (pbs
& TRACK_BIT_LOWER
) DrawTrackSprite(overlay
+ RTO_S
, PALETTE_CRASH
, ti
, SLOPE_S
);
2187 if (pbs
& TRACK_BIT_RIGHT
) DrawTrackSprite(overlay
+ RTO_E
, PALETTE_CRASH
, ti
, SLOPE_E
);
2188 if (pbs
& TRACK_BIT_LEFT
) DrawTrackSprite(overlay
+ RTO_W
, PALETTE_CRASH
, ti
, SLOPE_W
);
2189 } else if (ti
->tileh
== SLOPE_NW
&& track
== TRACK_BIT_Y
) {
2190 DrawGroundSprite(ground
+ RTO_SLOPE_NW
, PAL_NONE
);
2191 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_NW
, PALETTE_CRASH
);
2192 } else if (ti
->tileh
== SLOPE_NE
&& track
== TRACK_BIT_X
) {
2193 DrawGroundSprite(ground
+ RTO_SLOPE_NE
, PAL_NONE
);
2194 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_NE
, PALETTE_CRASH
);
2195 } else if (ti
->tileh
== SLOPE_SE
&& track
== TRACK_BIT_Y
) {
2196 DrawGroundSprite(ground
+ RTO_SLOPE_SE
, PAL_NONE
);
2197 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_SE
, PALETTE_CRASH
);
2198 } else if (ti
->tileh
== SLOPE_SW
&& track
== TRACK_BIT_X
) {
2199 DrawGroundSprite(ground
+ RTO_SLOPE_SW
, PAL_NONE
);
2200 if (pbs
!= TRACK_BIT_NONE
) DrawGroundSprite(overlay
+ RTO_SLOPE_SW
, PALETTE_CRASH
);
2203 /* Draw single ground sprite when not overlapping. No track overlay
2204 * is necessary for these sprites. */
2205 case TRACK_BIT_X
: DrawGroundSprite(ground
+ RTO_X
, PAL_NONE
); break;
2206 case TRACK_BIT_Y
: DrawGroundSprite(ground
+ RTO_Y
, PAL_NONE
); break;
2207 case TRACK_BIT_UPPER
: DrawTrackSprite(ground
+ RTO_N
, PAL_NONE
, ti
, SLOPE_N
); break;
2208 case TRACK_BIT_LOWER
: DrawTrackSprite(ground
+ RTO_S
, PAL_NONE
, ti
, SLOPE_S
); break;
2209 case TRACK_BIT_RIGHT
: DrawTrackSprite(ground
+ RTO_E
, PAL_NONE
, ti
, SLOPE_E
); break;
2210 case TRACK_BIT_LEFT
: DrawTrackSprite(ground
+ RTO_W
, PAL_NONE
, ti
, SLOPE_W
); break;
2211 case TRACK_BIT_CROSS
: DrawGroundSprite(ground
+ RTO_CROSSING_XY
, PAL_NONE
); break;
2212 case TRACK_BIT_HORZ
: DrawTrackSprite(ground
+ RTO_N
, PAL_NONE
, ti
, SLOPE_N
);
2213 DrawTrackSprite(ground
+ RTO_S
, PAL_NONE
, ti
, SLOPE_S
); break;
2214 case TRACK_BIT_VERT
: DrawTrackSprite(ground
+ RTO_E
, PAL_NONE
, ti
, SLOPE_E
);
2215 DrawTrackSprite(ground
+ RTO_W
, PAL_NONE
, ti
, SLOPE_W
); break;
2218 /* We're drawing a junction tile */
2219 if ((track
& TRACK_BIT_3WAY_NE
) == 0) {
2220 DrawGroundSprite(ground
+ RTO_JUNCTION_SW
, PAL_NONE
);
2221 } else if ((track
& TRACK_BIT_3WAY_SW
) == 0) {
2222 DrawGroundSprite(ground
+ RTO_JUNCTION_NE
, PAL_NONE
);
2223 } else if ((track
& TRACK_BIT_3WAY_NW
) == 0) {
2224 DrawGroundSprite(ground
+ RTO_JUNCTION_SE
, PAL_NONE
);
2225 } else if ((track
& TRACK_BIT_3WAY_SE
) == 0) {
2226 DrawGroundSprite(ground
+ RTO_JUNCTION_NW
, PAL_NONE
);
2228 DrawGroundSprite(ground
+ RTO_JUNCTION_NSEW
, PAL_NONE
);
2231 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2234 /* Draw regular track bits */
2235 if (track
& TRACK_BIT_X
) DrawGroundSprite(overlay
+ RTO_X
, PAL_NONE
);
2236 if (track
& TRACK_BIT_Y
) DrawGroundSprite(overlay
+ RTO_Y
, PAL_NONE
);
2237 if (track
& TRACK_BIT_UPPER
) DrawGroundSprite(overlay
+ RTO_N
, PAL_NONE
);
2238 if (track
& TRACK_BIT_LOWER
) DrawGroundSprite(overlay
+ RTO_S
, PAL_NONE
);
2239 if (track
& TRACK_BIT_RIGHT
) DrawGroundSprite(overlay
+ RTO_E
, PAL_NONE
);
2240 if (track
& TRACK_BIT_LEFT
) DrawGroundSprite(overlay
+ RTO_W
, PAL_NONE
);
2243 /* Draw reserved track bits */
2244 if (pbs
& TRACK_BIT_X
) DrawGroundSprite(overlay
+ RTO_X
, PALETTE_CRASH
);
2245 if (pbs
& TRACK_BIT_Y
) DrawGroundSprite(overlay
+ RTO_Y
, PALETTE_CRASH
);
2246 if (pbs
& TRACK_BIT_UPPER
) DrawTrackSprite(overlay
+ RTO_N
, PALETTE_CRASH
, ti
, SLOPE_N
);
2247 if (pbs
& TRACK_BIT_LOWER
) DrawTrackSprite(overlay
+ RTO_S
, PALETTE_CRASH
, ti
, SLOPE_S
);
2248 if (pbs
& TRACK_BIT_RIGHT
) DrawTrackSprite(overlay
+ RTO_E
, PALETTE_CRASH
, ti
, SLOPE_E
);
2249 if (pbs
& TRACK_BIT_LEFT
) DrawTrackSprite(overlay
+ RTO_W
, PALETTE_CRASH
, ti
, SLOPE_W
);
2252 if (IsValidCorner(halftile_corner
)) {
2253 DrawFoundation(ti
, HalftileFoundation(halftile_corner
));
2254 overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
, TCX_UPPER_HALFTILE
);
2255 ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
, TCX_UPPER_HALFTILE
);
2257 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2258 Slope fake_slope
= SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner
));
2262 case RAIL_GROUND_BARREN
: image
= SPR_FLAT_BARE_LAND
; break;
2263 case RAIL_GROUND_ICE_DESERT
:
2264 case RAIL_GROUND_HALF_SNOW
: image
= SPR_FLAT_SNOW_DESERT_TILE
; break;
2265 default: image
= SPR_FLAT_GRASS_TILE
; break;
2268 image
+= SlopeToSpriteOffset(fake_slope
);
2270 DrawGroundSprite(image
, PAL_NONE
, &(_halftile_sub_sprite
[halftile_corner
]));
2272 track
= CornerToTrackBits(halftile_corner
);
2276 default: NOT_REACHED();
2277 case TRACK_BIT_UPPER
: offset
= RTO_N
; break;
2278 case TRACK_BIT_LOWER
: offset
= RTO_S
; break;
2279 case TRACK_BIT_RIGHT
: offset
= RTO_E
; break;
2280 case TRACK_BIT_LEFT
: offset
= RTO_W
; break;
2283 DrawTrackSprite(ground
+ offset
, PAL_NONE
, ti
, fake_slope
);
2284 if (_settings_client
.gui
.show_track_reservation
&& HasReservedTracks(ti
->tile
, track
)) {
2285 DrawTrackSprite(overlay
+ offset
, PALETTE_CRASH
, ti
, fake_slope
);
2291 * Draw ground sprite and track bits
2292 * @param ti TileInfo
2293 * @param track TrackBits to draw
2295 static void DrawTrackBits(TileInfo
*ti
, TrackBits track
)
2297 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2299 if (rti
->UsesOverlay()) {
2300 DrawTrackBitsOverlay(ti
, track
, rti
);
2304 RailGroundType rgt
= GetRailGroundType(ti
->tile
);
2305 Foundation f
= GetRailFoundation(ti
->tileh
, track
);
2306 Corner halftile_corner
= CORNER_INVALID
;
2308 if (IsNonContinuousFoundation(f
)) {
2309 /* Save halftile corner */
2310 halftile_corner
= (f
== FOUNDATION_STEEP_BOTH
? GetHighestSlopeCorner(ti
->tileh
) : GetHalftileFoundationCorner(f
));
2311 /* Draw lower part first */
2312 track
&= ~CornerToTrackBits(halftile_corner
);
2313 f
= (f
== FOUNDATION_STEEP_BOTH
? FOUNDATION_STEEP_LOWER
: FOUNDATION_NONE
);
2316 DrawFoundation(ti
, f
);
2317 /* DrawFoundation modifies ti */
2320 PaletteID pal
= PAL_NONE
;
2321 const SubSprite
*sub
= nullptr;
2322 bool junction
= false;
2324 /* Select the sprite to use. */
2326 /* Clear ground (only track on halftile foundation) */
2327 if (rgt
== RAIL_GROUND_WATER
) {
2328 if (IsSteepSlope(ti
->tileh
)) {
2329 DrawShoreTile(ti
->tileh
);
2332 image
= SPR_FLAT_WATER_TILE
;
2336 case RAIL_GROUND_BARREN
: image
= SPR_FLAT_BARE_LAND
; break;
2337 case RAIL_GROUND_ICE_DESERT
: image
= SPR_FLAT_SNOW_DESERT_TILE
; break;
2338 default: image
= SPR_FLAT_GRASS_TILE
; break;
2340 image
+= SlopeToSpriteOffset(ti
->tileh
);
2343 if (ti
->tileh
!= SLOPE_FLAT
) {
2344 /* track on non-flat ground */
2345 image
= _track_sloped_sprites
[ti
->tileh
- 1] + rti
->base_sprites
.track_y
;
2347 /* track on flat ground */
2349 /* single track, select combined track + ground sprite*/
2350 case TRACK_BIT_Y
: image
= rti
->base_sprites
.track_y
; break;
2351 case TRACK_BIT_X
: image
= rti
->base_sprites
.track_y
+ 1; break;
2352 case TRACK_BIT_UPPER
: image
= rti
->base_sprites
.track_y
+ 2; break;
2353 case TRACK_BIT_LOWER
: image
= rti
->base_sprites
.track_y
+ 3; break;
2354 case TRACK_BIT_RIGHT
: image
= rti
->base_sprites
.track_y
+ 4; break;
2355 case TRACK_BIT_LEFT
: image
= rti
->base_sprites
.track_y
+ 5; break;
2356 case TRACK_BIT_CROSS
: image
= rti
->base_sprites
.track_y
+ 6; break;
2358 /* double diagonal track, select combined track + ground sprite*/
2359 case TRACK_BIT_HORZ
: image
= rti
->base_sprites
.track_ns
; break;
2360 case TRACK_BIT_VERT
: image
= rti
->base_sprites
.track_ns
+ 1; break;
2362 /* junction, select only ground sprite, handle track sprite later */
2365 if ((track
& TRACK_BIT_3WAY_NE
) == 0) { image
= rti
->base_sprites
.ground
; break; }
2366 if ((track
& TRACK_BIT_3WAY_SW
) == 0) { image
= rti
->base_sprites
.ground
+ 1; break; }
2367 if ((track
& TRACK_BIT_3WAY_NW
) == 0) { image
= rti
->base_sprites
.ground
+ 2; break; }
2368 if ((track
& TRACK_BIT_3WAY_SE
) == 0) { image
= rti
->base_sprites
.ground
+ 3; break; }
2369 image
= rti
->base_sprites
.ground
+ 4;
2375 case RAIL_GROUND_BARREN
: pal
= PALETTE_TO_BARE_LAND
; break;
2376 case RAIL_GROUND_ICE_DESERT
: image
+= rti
->snow_offset
; break;
2377 case RAIL_GROUND_WATER
: {
2378 /* three-corner-raised slope */
2379 DrawShoreTile(ti
->tileh
);
2380 Corner track_corner
= OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti
->tileh
)));
2381 sub
= &(_halftile_sub_sprite
[track_corner
]);
2388 if (image
!= 0) DrawGroundSprite(image
, pal
, sub
);
2390 /* Draw track pieces individually for junction tiles */
2392 if (track
& TRACK_BIT_X
) DrawGroundSprite(rti
->base_sprites
.single_x
, PAL_NONE
);
2393 if (track
& TRACK_BIT_Y
) DrawGroundSprite(rti
->base_sprites
.single_y
, PAL_NONE
);
2394 if (track
& TRACK_BIT_UPPER
) DrawGroundSprite(rti
->base_sprites
.single_n
, PAL_NONE
);
2395 if (track
& TRACK_BIT_LOWER
) DrawGroundSprite(rti
->base_sprites
.single_s
, PAL_NONE
);
2396 if (track
& TRACK_BIT_LEFT
) DrawGroundSprite(rti
->base_sprites
.single_w
, PAL_NONE
);
2397 if (track
& TRACK_BIT_RIGHT
) DrawGroundSprite(rti
->base_sprites
.single_e
, PAL_NONE
);
2400 /* PBS debugging, draw reserved tracks darker */
2401 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
) {
2402 /* Get reservation, but mask track on halftile slope */
2403 TrackBits pbs
= GetRailReservationTrackBits(ti
->tile
) & track
;
2404 if (pbs
& TRACK_BIT_X
) {
2405 if (ti
->tileh
== SLOPE_FLAT
|| ti
->tileh
== SLOPE_ELEVATED
) {
2406 DrawGroundSprite(rti
->base_sprites
.single_x
, PALETTE_CRASH
);
2408 DrawGroundSprite(_track_sloped_sprites
[ti
->tileh
- 1] + rti
->base_sprites
.single_sloped
- 20, PALETTE_CRASH
);
2411 if (pbs
& TRACK_BIT_Y
) {
2412 if (ti
->tileh
== SLOPE_FLAT
|| ti
->tileh
== SLOPE_ELEVATED
) {
2413 DrawGroundSprite(rti
->base_sprites
.single_y
, PALETTE_CRASH
);
2415 DrawGroundSprite(_track_sloped_sprites
[ti
->tileh
- 1] + rti
->base_sprites
.single_sloped
- 20, PALETTE_CRASH
);
2418 if (pbs
& TRACK_BIT_UPPER
) DrawGroundSprite(rti
->base_sprites
.single_n
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_N
? -(int)TILE_HEIGHT
: 0);
2419 if (pbs
& TRACK_BIT_LOWER
) DrawGroundSprite(rti
->base_sprites
.single_s
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_S
? -(int)TILE_HEIGHT
: 0);
2420 if (pbs
& TRACK_BIT_LEFT
) DrawGroundSprite(rti
->base_sprites
.single_w
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_W
? -(int)TILE_HEIGHT
: 0);
2421 if (pbs
& TRACK_BIT_RIGHT
) DrawGroundSprite(rti
->base_sprites
.single_e
, PALETTE_CRASH
, nullptr, 0, ti
->tileh
& SLOPE_E
? -(int)TILE_HEIGHT
: 0);
2424 if (IsValidCorner(halftile_corner
)) {
2425 DrawFoundation(ti
, HalftileFoundation(halftile_corner
));
2427 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2428 Slope fake_slope
= SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner
));
2429 image
= _track_sloped_sprites
[fake_slope
- 1] + rti
->base_sprites
.track_y
;
2432 case RAIL_GROUND_BARREN
: pal
= PALETTE_TO_BARE_LAND
; break;
2433 case RAIL_GROUND_ICE_DESERT
:
2434 case RAIL_GROUND_HALF_SNOW
: image
+= rti
->snow_offset
; break; // higher part has snow in this case too
2437 DrawGroundSprite(image
, pal
, &(_halftile_sub_sprite
[halftile_corner
]));
2439 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasReservedTracks(ti
->tile
, CornerToTrackBits(halftile_corner
))) {
2440 static const byte _corner_to_track_sprite
[] = {3, 1, 2, 0};
2441 DrawGroundSprite(_corner_to_track_sprite
[halftile_corner
] + rti
->base_sprites
.single_n
, PALETTE_CRASH
, nullptr, 0, -(int)TILE_HEIGHT
);
2446 static void DrawSignals(TileIndex tile
, TrackBits rails
, const RailtypeInfo
*rti
)
2448 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2450 if (!(rails
& TRACK_BIT_Y
)) {
2451 if (!(rails
& TRACK_BIT_X
)) {
2452 if (rails
& TRACK_BIT_LEFT
) {
2453 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH
, 0, TRACK_LEFT
);
2454 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH
, 1, TRACK_LEFT
);
2456 if (rails
& TRACK_BIT_RIGHT
) {
2457 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH
, 2, TRACK_RIGHT
);
2458 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH
, 3, TRACK_RIGHT
);
2460 if (rails
& TRACK_BIT_UPPER
) {
2461 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST
, 4, TRACK_UPPER
);
2462 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST
, 5, TRACK_UPPER
);
2464 if (rails
& TRACK_BIT_LOWER
) {
2465 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST
, 6, TRACK_LOWER
);
2466 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST
, 7, TRACK_LOWER
);
2469 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST
, 8, TRACK_X
);
2470 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST
, 9, TRACK_X
);
2473 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST
, 10, TRACK_Y
);
2474 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST
, 11, TRACK_Y
);
2478 static void DrawTile_Track(TileInfo
*ti
)
2480 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2482 _drawtile_track_palette
= COMPANY_SPRITE_COLOUR(GetTileOwner(ti
->tile
));
2484 if (IsPlainRail(ti
->tile
)) {
2485 TrackBits rails
= GetTrackBits(ti
->tile
);
2487 DrawTrackBits(ti
, rails
);
2489 if (HasBit(_display_opt
, DO_FULL_DETAIL
)) DrawTrackDetails(ti
, rti
);
2491 if (HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
2493 if (HasSignals(ti
->tile
)) DrawSignals(ti
->tile
, rails
, rti
);
2496 const DrawTileSprites
*dts
;
2497 PaletteID pal
= PAL_NONE
;
2498 SpriteID relocation
;
2500 if (ti
->tileh
!= SLOPE_FLAT
) DrawFoundation(ti
, FOUNDATION_LEVELED
);
2502 if (IsInvisibilitySet(TO_BUILDINGS
)) {
2503 /* Draw rail instead of depot */
2504 dts
= &_depot_invisible_gfx_table
[GetRailDepotDirection(ti
->tile
)];
2506 dts
= &_depot_gfx_table
[GetRailDepotDirection(ti
->tile
)];
2510 if (rti
->UsesOverlay()) {
2511 image
= SPR_FLAT_GRASS_TILE
;
2513 image
= dts
->ground
.sprite
;
2514 if (image
!= SPR_FLAT_GRASS_TILE
) image
+= rti
->GetRailtypeSpriteOffset();
2517 /* Adjust ground tile for desert and snow. */
2518 if (IsSnowRailGround(ti
->tile
)) {
2519 if (image
!= SPR_FLAT_GRASS_TILE
) {
2520 image
+= rti
->snow_offset
; // tile with tracks
2522 image
= SPR_FLAT_SNOW_DESERT_TILE
; // flat ground
2526 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, _drawtile_track_palette
));
2528 if (rti
->UsesOverlay()) {
2529 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
2531 switch (GetRailDepotDirection(ti
->tile
)) {
2533 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2536 DrawGroundSprite(ground
+ RTO_X
, PAL_NONE
);
2539 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2542 DrawGroundSprite(ground
+ RTO_Y
, PAL_NONE
);
2548 if (_settings_client
.gui
.show_track_reservation
&& HasDepotReservation(ti
->tile
)) {
2549 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
2551 switch (GetRailDepotDirection(ti
->tile
)) {
2553 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2556 DrawGroundSprite(overlay
+ RTO_X
, PALETTE_CRASH
);
2559 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2562 DrawGroundSprite(overlay
+ RTO_Y
, PALETTE_CRASH
);
2569 /* PBS debugging, draw reserved tracks darker */
2570 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasDepotReservation(ti
->tile
)) {
2571 switch (GetRailDepotDirection(ti
->tile
)) {
2573 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2576 DrawGroundSprite(rti
->base_sprites
.single_x
, PALETTE_CRASH
);
2579 if (!IsInvisibilitySet(TO_BUILDINGS
)) break;
2582 DrawGroundSprite(rti
->base_sprites
.single_y
, PALETTE_CRASH
);
2589 int depot_sprite
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_DEPOT
);
2590 relocation
= depot_sprite
!= 0 ? depot_sprite
- SPR_RAIL_DEPOT_SE_1
: rti
->GetRailtypeSpriteOffset();
2592 if (HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
2594 DrawRailTileSeq(ti
, dts
, TO_BUILDINGS
, relocation
, 0, _drawtile_track_palette
);
2596 DrawBridgeMiddle(ti
);
2599 void DrawTrainDepotSprite(int x
, int y
, int dir
, RailType railtype
)
2601 const DrawTileSprites
*dts
= &_depot_gfx_table
[dir
];
2602 const RailtypeInfo
*rti
= GetRailTypeInfo(railtype
);
2603 SpriteID image
= rti
->UsesOverlay() ? SPR_FLAT_GRASS_TILE
: dts
->ground
.sprite
;
2604 uint32 offset
= rti
->GetRailtypeSpriteOffset();
2606 if (image
!= SPR_FLAT_GRASS_TILE
) image
+= offset
;
2607 PaletteID palette
= COMPANY_SPRITE_COLOUR(_local_company
);
2609 DrawSprite(image
, PAL_NONE
, x
, y
);
2611 if (rti
->UsesOverlay()) {
2612 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
2615 case DIAGDIR_SW
: DrawSprite(ground
+ RTO_X
, PAL_NONE
, x
, y
); break;
2616 case DIAGDIR_SE
: DrawSprite(ground
+ RTO_Y
, PAL_NONE
, x
, y
); break;
2620 int depot_sprite
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_DEPOT
);
2621 if (depot_sprite
!= 0) offset
= depot_sprite
- SPR_RAIL_DEPOT_SE_1
;
2623 DrawRailTileSeqInGUI(x
, y
, dts
, offset
, 0, palette
);
2626 static int GetSlopePixelZ_Track(TileIndex tile
, uint x
, uint y
)
2628 if (IsPlainRail(tile
)) {
2630 Slope tileh
= GetTilePixelSlope(tile
, &z
);
2631 if (tileh
== SLOPE_FLAT
) return z
;
2633 z
+= ApplyPixelFoundationToSlope(GetRailFoundation(tileh
, GetTrackBits(tile
)), &tileh
);
2634 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
2636 return GetTileMaxPixelZ(tile
);
2640 static Foundation
GetFoundation_Track(TileIndex tile
, Slope tileh
)
2642 return IsPlainRail(tile
) ? GetRailFoundation(tileh
, GetTrackBits(tile
)) : FlatteningFoundation(tileh
);
2645 static void TileLoop_Track(TileIndex tile
)
2647 RailGroundType old_ground
= GetRailGroundType(tile
);
2648 RailGroundType new_ground
;
2650 if (old_ground
== RAIL_GROUND_WATER
) {
2651 TileLoop_Water(tile
);
2655 switch (_settings_game
.game_creation
.landscape
) {
2658 Slope slope
= GetTileSlope(tile
, &z
);
2661 /* for non-flat track, use lower part of track
2662 * in other cases, use the highest part with track */
2663 if (IsPlainRail(tile
)) {
2664 TrackBits track
= GetTrackBits(tile
);
2665 Foundation f
= GetRailFoundation(slope
, track
);
2668 case FOUNDATION_NONE
:
2669 /* no foundation - is the track on the upper side of three corners raised tile? */
2670 if (IsSlopeWithThreeCornersRaised(slope
)) z
++;
2673 case FOUNDATION_INCLINED_X
:
2674 case FOUNDATION_INCLINED_Y
:
2675 /* sloped track - is it on a steep slope? */
2676 if (IsSteepSlope(slope
)) z
++;
2679 case FOUNDATION_STEEP_LOWER
:
2680 /* only lower part of steep slope */
2685 /* if it is a steep slope, then there is a track on higher part */
2686 if (IsSteepSlope(slope
)) z
++;
2691 half
= IsInsideMM(f
, FOUNDATION_STEEP_BOTH
, FOUNDATION_HALFTILE_N
+ 1);
2693 /* is the depot on a non-flat tile? */
2694 if (slope
!= SLOPE_FLAT
) z
++;
2697 /* 'z' is now the lowest part of the highest track bit -
2698 * for sloped track, it is 'z' of lower part
2699 * for two track bits, it is 'z' of higher track bit
2700 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2701 if (z
> GetSnowLine()) {
2702 if (half
&& z
- GetSnowLine() == 1) {
2703 /* track on non-continuous foundation, lower part is not under snow */
2704 new_ground
= RAIL_GROUND_HALF_SNOW
;
2706 new_ground
= RAIL_GROUND_ICE_DESERT
;
2714 if (GetTropicZone(tile
) == TROPICZONE_DESERT
) {
2715 new_ground
= RAIL_GROUND_ICE_DESERT
;
2721 new_ground
= RAIL_GROUND_GRASS
;
2723 if (IsPlainRail(tile
) && old_ground
!= RAIL_GROUND_BARREN
) { // wait until bottom is green
2724 /* determine direction of fence */
2725 TrackBits rail
= GetTrackBits(tile
);
2727 Owner owner
= GetTileOwner(tile
);
2730 for (DiagDirection d
= DIAGDIR_BEGIN
; d
< DIAGDIR_END
; d
++) {
2731 static const TrackBits dir_to_trackbits
[DIAGDIR_END
] = {TRACK_BIT_3WAY_NE
, TRACK_BIT_3WAY_SE
, TRACK_BIT_3WAY_SW
, TRACK_BIT_3WAY_NW
};
2733 /* Track bit on this edge => no fence. */
2734 if ((rail
& dir_to_trackbits
[d
]) != TRACK_BIT_NONE
) continue;
2736 TileIndex tile2
= tile
+ TileOffsByDiagDir(d
);
2738 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
2739 if (!IsValidTile(tile2
) || IsTileType(tile2
, MP_HOUSE
) || IsTileType(tile2
, MP_INDUSTRY
) ||
2740 IsTileType(tile2
, MP_ROAD
) || (IsTileType(tile2
, MP_OBJECT
) && !IsObjectType(tile2
, OBJECT_OWNED_LAND
)) || IsTileType(tile2
, MP_TUNNELBRIDGE
) || !IsTileOwner(tile2
, owner
)) {
2747 case (1 << DIAGDIR_NE
): new_ground
= RAIL_GROUND_FENCE_NE
; break;
2748 case (1 << DIAGDIR_SE
): new_ground
= RAIL_GROUND_FENCE_SE
; break;
2749 case (1 << DIAGDIR_SW
): new_ground
= RAIL_GROUND_FENCE_SW
; break;
2750 case (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_NW
; break;
2751 case (1 << DIAGDIR_NE
) | (1 << DIAGDIR_SW
): new_ground
= RAIL_GROUND_FENCE_NESW
; break;
2752 case (1 << DIAGDIR_SE
) | (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_SENW
; break;
2753 case (1 << DIAGDIR_NE
) | (1 << DIAGDIR_SE
): new_ground
= RAIL_GROUND_FENCE_VERT1
; break;
2754 case (1 << DIAGDIR_NE
) | (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_HORIZ2
; break;
2755 case (1 << DIAGDIR_SE
) | (1 << DIAGDIR_SW
): new_ground
= RAIL_GROUND_FENCE_HORIZ1
; break;
2756 case (1 << DIAGDIR_SW
) | (1 << DIAGDIR_NW
): new_ground
= RAIL_GROUND_FENCE_VERT2
; break;
2757 default: NOT_REACHED();
2762 if (old_ground
!= new_ground
) {
2763 SetRailGroundType(tile
, new_ground
);
2764 MarkTileDirtyByTile(tile
);
2769 static TrackStatus
GetTileTrackStatus_Track(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
2771 /* Case of half tile slope with water. */
2772 if (mode
== TRANSPORT_WATER
&& IsPlainRail(tile
) && GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(GetTileSlope(tile
))) {
2773 TrackBits tb
= GetTrackBits(tile
);
2775 default: NOT_REACHED();
2776 case TRACK_BIT_UPPER
: tb
= TRACK_BIT_LOWER
; break;
2777 case TRACK_BIT_LOWER
: tb
= TRACK_BIT_UPPER
; break;
2778 case TRACK_BIT_LEFT
: tb
= TRACK_BIT_RIGHT
; break;
2779 case TRACK_BIT_RIGHT
: tb
= TRACK_BIT_LEFT
; break;
2781 return CombineTrackStatus(TrackBitsToTrackdirBits(tb
), TRACKDIR_BIT_NONE
);
2784 if (mode
!= TRANSPORT_RAIL
) return 0;
2786 TrackBits trackbits
= TRACK_BIT_NONE
;
2787 TrackdirBits red_signals
= TRACKDIR_BIT_NONE
;
2789 switch (GetRailTileType(tile
)) {
2790 default: NOT_REACHED();
2791 case RAIL_TILE_NORMAL
:
2792 trackbits
= GetTrackBits(tile
);
2795 case RAIL_TILE_SIGNALS
: {
2796 trackbits
= GetTrackBits(tile
);
2797 byte a
= GetPresentSignals(tile
);
2798 uint b
= GetSignalStates(tile
);
2802 /* When signals are not present (in neither direction),
2803 * we pretend them to be green. Otherwise, it depends on
2804 * the signal type. For signals that are only active from
2805 * one side, we set the missing signals explicitly to
2806 * `green'. Otherwise, they implicitly become `red'. */
2807 if (!IsOnewaySignal(tile
, TRACK_UPPER
) || (a
& SignalOnTrack(TRACK_UPPER
)) == 0) b
|= ~a
& SignalOnTrack(TRACK_UPPER
);
2808 if (!IsOnewaySignal(tile
, TRACK_LOWER
) || (a
& SignalOnTrack(TRACK_LOWER
)) == 0) b
|= ~a
& SignalOnTrack(TRACK_LOWER
);
2810 if ((b
& 0x8) == 0) red_signals
|= (TRACKDIR_BIT_LEFT_N
| TRACKDIR_BIT_X_NE
| TRACKDIR_BIT_Y_SE
| TRACKDIR_BIT_UPPER_E
);
2811 if ((b
& 0x4) == 0) red_signals
|= (TRACKDIR_BIT_LEFT_S
| TRACKDIR_BIT_X_SW
| TRACKDIR_BIT_Y_NW
| TRACKDIR_BIT_UPPER_W
);
2812 if ((b
& 0x2) == 0) red_signals
|= (TRACKDIR_BIT_RIGHT_N
| TRACKDIR_BIT_LOWER_E
);
2813 if ((b
& 0x1) == 0) red_signals
|= (TRACKDIR_BIT_RIGHT_S
| TRACKDIR_BIT_LOWER_W
);
2818 case RAIL_TILE_DEPOT
: {
2819 DiagDirection dir
= GetRailDepotDirection(tile
);
2821 if (side
!= INVALID_DIAGDIR
&& side
!= dir
) break;
2823 trackbits
= DiagDirToDiagTrackBits(dir
);
2828 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), red_signals
);
2831 static bool ClickTile_Track(TileIndex tile
)
2833 if (!IsRailDepot(tile
)) return false;
2835 ShowDepotWindow(tile
, VEH_TRAIN
);
2839 static void GetTileDesc_Track(TileIndex tile
, TileDesc
*td
)
2841 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
2842 td
->rail_speed
= rti
->max_speed
;
2843 td
->railtype
= rti
->strings
.name
;
2844 td
->owner
[0] = GetTileOwner(tile
);
2845 switch (GetRailTileType(tile
)) {
2846 case RAIL_TILE_NORMAL
:
2847 td
->str
= STR_LAI_RAIL_DESCRIPTION_TRACK
;
2850 case RAIL_TILE_SIGNALS
: {
2851 static const StringID signal_type
[6][6] = {
2853 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS
,
2854 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS
,
2855 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS
,
2856 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS
,
2857 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS
,
2858 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
2861 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS
,
2862 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS
,
2863 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS
,
2864 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS
,
2865 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS
,
2866 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
2869 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS
,
2870 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS
,
2871 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS
,
2872 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS
,
2873 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS
,
2874 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
2877 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS
,
2878 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS
,
2879 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS
,
2880 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS
,
2881 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS
,
2882 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
2885 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS
,
2886 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS
,
2887 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS
,
2888 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS
,
2889 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS
,
2890 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
2893 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
,
2894 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
,
2895 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
,
2896 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
,
2897 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
,
2898 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS
2902 SignalType primary_signal
;
2903 SignalType secondary_signal
;
2904 if (HasSignalOnTrack(tile
, TRACK_UPPER
)) {
2905 primary_signal
= GetSignalType(tile
, TRACK_UPPER
);
2906 secondary_signal
= HasSignalOnTrack(tile
, TRACK_LOWER
) ? GetSignalType(tile
, TRACK_LOWER
) : primary_signal
;
2908 secondary_signal
= primary_signal
= GetSignalType(tile
, TRACK_LOWER
);
2911 td
->str
= signal_type
[secondary_signal
][primary_signal
];
2915 case RAIL_TILE_DEPOT
:
2916 td
->str
= STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT
;
2917 if (_settings_game
.vehicle
.train_acceleration_model
!= AM_ORIGINAL
) {
2918 if (td
->rail_speed
> 0) {
2919 td
->rail_speed
= std::min
<uint16
>(td
->rail_speed
, 61);
2921 td
->rail_speed
= 61;
2924 td
->build_date
= Depot::GetByTile(tile
)->build_date
;
2932 static void ChangeTileOwner_Track(TileIndex tile
, Owner old_owner
, Owner new_owner
)
2934 if (!IsTileOwner(tile
, old_owner
)) return;
2936 if (new_owner
!= INVALID_OWNER
) {
2937 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2938 uint num_pieces
= 1;
2939 if (IsPlainRail(tile
)) {
2940 TrackBits bits
= GetTrackBits(tile
);
2941 num_pieces
= CountBits(bits
);
2942 if (TracksOverlap(bits
)) num_pieces
*= num_pieces
;
2944 RailType rt
= GetRailType(tile
);
2945 Company::Get(old_owner
)->infrastructure
.rail
[rt
] -= num_pieces
;
2946 Company::Get(new_owner
)->infrastructure
.rail
[rt
] += num_pieces
;
2948 if (HasSignals(tile
)) {
2949 uint num_sigs
= CountBits(GetPresentSignals(tile
));
2950 Company::Get(old_owner
)->infrastructure
.signal
-= num_sigs
;
2951 Company::Get(new_owner
)->infrastructure
.signal
+= num_sigs
;
2954 SetTileOwner(tile
, new_owner
);
2956 DoCommand(DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
, tile
, 0, 0);
2960 static const byte _fractcoords_behind
[4] = { 0x8F, 0x8, 0x80, 0xF8 };
2961 static const byte _fractcoords_enter
[4] = { 0x8A, 0x48, 0x84, 0xA8 };
2962 static const int8 _deltacoord_leaveoffset
[8] = {
2963 -1, 0, 1, 0, /* x */
2969 * Compute number of ticks when next wagon will leave a depot.
2970 * Negative means next wagon should have left depot n ticks before.
2971 * @param v vehicle outside (leaving) the depot
2972 * @return number of ticks when the next wagon will leave
2974 int TicksToLeaveDepot(const Train
*v
)
2976 DiagDirection dir
= GetRailDepotDirection(v
->tile
);
2977 int length
= v
->CalcNextVehicleOffset();
2980 case DIAGDIR_NE
: return ((int)(v
->x_pos
& 0x0F) - ((_fractcoords_enter
[dir
] & 0x0F) - (length
+ 1)));
2981 case DIAGDIR_SE
: return -((int)(v
->y_pos
& 0x0F) - ((_fractcoords_enter
[dir
] >> 4) + (length
+ 1)));
2982 case DIAGDIR_SW
: return -((int)(v
->x_pos
& 0x0F) - ((_fractcoords_enter
[dir
] & 0x0F) + (length
+ 1)));
2983 case DIAGDIR_NW
: return ((int)(v
->y_pos
& 0x0F) - ((_fractcoords_enter
[dir
] >> 4) - (length
+ 1)));
2984 default: NOT_REACHED();
2989 * Tile callback routine when vehicle enters tile
2990 * @see vehicle_enter_tile_proc
2992 static VehicleEnterTileStatus
VehicleEnter_Track(Vehicle
*u
, TileIndex tile
, int x
, int y
)
2994 /* This routine applies only to trains in depot tiles. */
2995 if (u
->type
!= VEH_TRAIN
|| !IsRailDepotTile(tile
)) return VETSB_CONTINUE
;
2997 /* Depot direction. */
2998 DiagDirection dir
= GetRailDepotDirection(tile
);
3000 byte fract_coord
= (x
& 0xF) + ((y
& 0xF) << 4);
3002 /* Make sure a train is not entering the tile from behind. */
3003 if (_fractcoords_behind
[dir
] == fract_coord
) return VETSB_CANNOT_ENTER
;
3005 Train
*v
= Train::From(u
);
3007 /* Leaving depot? */
3008 if (v
->direction
== DiagDirToDir(dir
)) {
3009 /* Calculate the point where the following wagon should be activated. */
3010 int length
= v
->CalcNextVehicleOffset();
3012 byte fract_coord_leave
=
3013 ((_fractcoords_enter
[dir
] & 0x0F) + // x
3014 (length
+ 1) * _deltacoord_leaveoffset
[dir
]) +
3015 (((_fractcoords_enter
[dir
] >> 4) + // y
3016 ((length
+ 1) * _deltacoord_leaveoffset
[dir
+ 4])) << 4);
3018 if (fract_coord_leave
== fract_coord
) {
3019 /* Leave the depot. */
3020 if ((v
= v
->Next()) != nullptr) {
3021 v
->vehstatus
&= ~VS_HIDDEN
;
3022 v
->track
= (DiagDirToAxis(dir
) == AXIS_X
? TRACK_BIT_X
: TRACK_BIT_Y
);
3025 } else if (_fractcoords_enter
[dir
] == fract_coord
) {
3026 /* Entering depot. */
3027 assert(DiagDirToDir(ReverseDiagDir(dir
)) == v
->direction
);
3028 v
->track
= TRACK_BIT_DEPOT
,
3029 v
->vehstatus
|= VS_HIDDEN
;
3030 v
->direction
= ReverseDir(v
->direction
);
3031 if (v
->Next() == nullptr) VehicleEnterDepot(v
->First());
3034 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
3035 return VETSB_ENTERED_WORMHOLE
;
3038 return VETSB_CONTINUE
;
3042 * Tests if autoslope is allowed.
3044 * @param tile The tile.
3045 * @param flags Terraform command flags.
3046 * @param z_old Old TileZ.
3047 * @param tileh_old Old TileSlope.
3048 * @param z_new New TileZ.
3049 * @param tileh_new New TileSlope.
3050 * @param rail_bits Trackbits.
3052 static CommandCost
TestAutoslopeOnRailTile(TileIndex tile
, uint flags
, int z_old
, Slope tileh_old
, int z_new
, Slope tileh_new
, TrackBits rail_bits
)
3054 if (!_settings_game
.construction
.build_on_slopes
|| !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
3056 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
3057 if (CheckRailSlope(tileh_new
, rail_bits
, TRACK_BIT_NONE
, tile
).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
3059 /* Get the slopes on top of the foundations */
3060 z_old
+= ApplyFoundationToSlope(GetRailFoundation(tileh_old
, rail_bits
), &tileh_old
);
3061 z_new
+= ApplyFoundationToSlope(GetRailFoundation(tileh_new
, rail_bits
), &tileh_new
);
3063 Corner track_corner
;
3064 switch (rail_bits
) {
3065 case TRACK_BIT_LEFT
: track_corner
= CORNER_W
; break;
3066 case TRACK_BIT_LOWER
: track_corner
= CORNER_S
; break;
3067 case TRACK_BIT_RIGHT
: track_corner
= CORNER_E
; break;
3068 case TRACK_BIT_UPPER
: track_corner
= CORNER_N
; break;
3070 /* Surface slope must not be changed */
3072 if (z_old
!= z_new
|| tileh_old
!= tileh_new
) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
3073 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3076 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
3077 z_old
+= GetSlopeZInCorner(RemoveHalftileSlope(tileh_old
), track_corner
);
3078 z_new
+= GetSlopeZInCorner(RemoveHalftileSlope(tileh_new
), track_corner
);
3079 if (z_old
!= z_new
) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK
);
3081 CommandCost cost
= CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3082 /* Make the ground dirty, if surface slope has changed */
3083 if (tileh_old
!= tileh_new
) {
3084 /* If there is flat water on the lower halftile add the cost for clearing it */
3085 if (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh_old
)) cost
.AddCost(_price
[PR_CLEAR_WATER
]);
3086 if ((flags
& DC_EXEC
) != 0) SetRailGroundType(tile
, RAIL_GROUND_BARREN
);
3092 * Test-procedure for HasVehicleOnPos to check for a ship.
3094 static Vehicle
*EnsureNoShipProc(Vehicle
*v
, void *data
)
3096 return v
->type
== VEH_SHIP
? v
: nullptr;
3099 static CommandCost
TerraformTile_Track(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
3102 Slope tileh_old
= GetTileSlope(tile
, &z_old
);
3103 if (IsPlainRail(tile
)) {
3104 TrackBits rail_bits
= GetTrackBits(tile
);
3105 /* Is there flat water on the lower halftile that must be cleared expensively? */
3106 bool was_water
= (GetRailGroundType(tile
) == RAIL_GROUND_WATER
&& IsSlopeWithOneCornerRaised(tileh_old
));
3108 /* Allow clearing the water only if there is no ship */
3109 if (was_water
&& HasVehicleOnPos(tile
, nullptr, &EnsureNoShipProc
)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY
);
3111 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
3112 CommandCost autoslope_result
= TestAutoslopeOnRailTile(tile
, flags
, z_old
, tileh_old
, z_new
, tileh_new
, rail_bits
);
3114 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
3115 Corner allowed_corner
;
3116 switch (rail_bits
) {
3117 case TRACK_BIT_RIGHT
: allowed_corner
= CORNER_W
; break;
3118 case TRACK_BIT_UPPER
: allowed_corner
= CORNER_S
; break;
3119 case TRACK_BIT_LEFT
: allowed_corner
= CORNER_E
; break;
3120 case TRACK_BIT_LOWER
: allowed_corner
= CORNER_N
; break;
3121 default: return autoslope_result
;
3124 Foundation f_old
= GetRailFoundation(tileh_old
, rail_bits
);
3126 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3127 if (tileh_old
!= SLOPE_NS
&& tileh_old
!= SLOPE_EW
&& IsSpecialRailFoundation(f_old
)) return autoslope_result
;
3129 /* Everything is valid, which only changes allowed_corner */
3130 for (Corner corner
= (Corner
)0; corner
< CORNER_END
; corner
= (Corner
)(corner
+ 1)) {
3131 if (allowed_corner
== corner
) continue;
3132 if (z_old
+ GetSlopeZInCorner(tileh_old
, corner
) != z_new
+ GetSlopeZInCorner(tileh_new
, corner
)) return autoslope_result
;
3135 /* Make the ground dirty */
3136 if ((flags
& DC_EXEC
) != 0) SetRailGroundType(tile
, RAIL_GROUND_BARREN
);
3138 /* allow terraforming */
3139 return CommandCost(EXPENSES_CONSTRUCTION
, was_water
? _price
[PR_CLEAR_WATER
] : (Money
)0);
3140 } else if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled() &&
3141 AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, GetRailDepotDirection(tile
))) {
3142 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
3144 return DoCommand(flags
, CMD_LANDSCAPE_CLEAR
, tile
, 0, 0);
3148 extern const TileTypeProcs _tile_type_rail_procs
= {
3149 DrawTile_Track
, // draw_tile_proc
3150 GetSlopePixelZ_Track
, // get_slope_z_proc
3151 ClearTile_Track
, // clear_tile_proc
3152 nullptr, // add_accepted_cargo_proc
3153 GetTileDesc_Track
, // get_tile_desc_proc
3154 GetTileTrackStatus_Track
, // get_tile_track_status_proc
3155 ClickTile_Track
, // click_tile_proc
3156 nullptr, // animate_tile_proc
3157 TileLoop_Track
, // tile_loop_proc
3158 ChangeTileOwner_Track
, // change_tile_owner_proc
3159 nullptr, // add_produced_cargo_proc
3160 VehicleEnter_Track
, // vehicle_enter_tile_proc
3161 GetFoundation_Track
, // get_foundation_proc
3162 TerraformTile_Track
, // terraform_tile_proc