Add: INR currency (#8136)
[openttd-github.git] / src / rail_cmd.cpp
blob162fe97799a1084e258b74270fc0c04ecb0b839f
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file rail_cmd.cpp Handling of rail tiles. */
10 #include "stdafx.h"
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"
18 #include "train.h"
19 #include "autoslope.h"
20 #include "water.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"
26 #include "town.h"
27 #include "pbs.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"
35 #include "table/strings.h"
36 #include "table/railtypes.h"
37 #include "table/track_land.h"
39 #include "safeguards.h"
41 /** Helper type for lists/vectors of trains */
42 typedef std::vector<Train *> TrainList;
44 RailtypeInfo _railtypes[RAILTYPE_END];
45 std::vector<RailType> _sorted_railtypes;
46 RailTypes _railtypes_hidden_mask;
48 /** Enum holding the signal offset in the sprite sheet according to the side it is representing. */
49 enum SignalOffsets {
50 SIGNAL_TO_SOUTHWEST,
51 SIGNAL_TO_NORTHEAST,
52 SIGNAL_TO_SOUTHEAST,
53 SIGNAL_TO_NORTHWEST,
54 SIGNAL_TO_EAST,
55 SIGNAL_TO_WEST,
56 SIGNAL_TO_SOUTH,
57 SIGNAL_TO_NORTH,
60 /**
61 * Reset all rail type information to its default values.
63 void ResetRailTypes()
65 assert_compile(lengthof(_original_railtypes) <= lengthof(_railtypes));
67 uint i = 0;
68 for (; i < lengthof(_original_railtypes); i++) _railtypes[i] = _original_railtypes[i];
70 static const RailtypeInfo empty_railtype = {
71 {0,0,0,0,0,0,0,0,0,0,0,0},
72 {0,0,0,0,0,0,0,0,{}},
73 {0,0,0,0,0,0,0,0},
74 {0,0,0,0,0,0},
75 0, RAILTYPES_NONE, RAILTYPES_NONE, 0, 0, 0, RTFB_NONE, 0, 0, 0, 0, 0,
76 RailTypeLabelList(), 0, 0, RAILTYPES_NONE, RAILTYPES_NONE, 0,
77 {}, {} };
78 for (; i < lengthof(_railtypes); i++) _railtypes[i] = empty_railtype;
80 _railtypes_hidden_mask = RAILTYPES_NONE;
83 void ResolveRailTypeGUISprites(RailtypeInfo *rti)
85 SpriteID cursors_base = GetCustomRailSprite(rti, INVALID_TILE, RTSG_CURSORS);
86 if (cursors_base != 0) {
87 rti->gui_sprites.build_ns_rail = cursors_base + 0;
88 rti->gui_sprites.build_x_rail = cursors_base + 1;
89 rti->gui_sprites.build_ew_rail = cursors_base + 2;
90 rti->gui_sprites.build_y_rail = cursors_base + 3;
91 rti->gui_sprites.auto_rail = cursors_base + 4;
92 rti->gui_sprites.build_depot = cursors_base + 5;
93 rti->gui_sprites.build_tunnel = cursors_base + 6;
94 rti->gui_sprites.convert_rail = cursors_base + 7;
95 rti->cursor.rail_ns = cursors_base + 8;
96 rti->cursor.rail_swne = cursors_base + 9;
97 rti->cursor.rail_ew = cursors_base + 10;
98 rti->cursor.rail_nwse = cursors_base + 11;
99 rti->cursor.autorail = cursors_base + 12;
100 rti->cursor.depot = cursors_base + 13;
101 rti->cursor.tunnel = cursors_base + 14;
102 rti->cursor.convert = cursors_base + 15;
105 /* Array of default GUI signal sprite numbers. */
106 const SpriteID _signal_lookup[2][SIGTYPE_END] = {
107 {SPR_IMG_SIGNAL_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_EXIT,
108 SPR_IMG_SIGNAL_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY},
110 {SPR_IMG_SIGNAL_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_EXIT,
111 SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY},
114 for (SignalType type = SIGTYPE_NORMAL; type < SIGTYPE_END; type = (SignalType)(type + 1)) {
115 for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) {
116 SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true);
117 SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true);
118 rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type];
119 rti->gui_sprites.signals[type][var][1] = (green != 0) ? green + SIGNAL_TO_SOUTH : _signal_lookup[var][type] + 1;
125 * Compare railtypes based on their sorting order.
126 * @param first The railtype to compare to.
127 * @param second The railtype to compare.
128 * @return True iff the first should be sorted before the second.
130 static bool CompareRailTypes(const RailType &first, const RailType &second)
132 return GetRailTypeInfo(first)->sorting_order < GetRailTypeInfo(second)->sorting_order;
136 * Resolve sprites of custom rail types
138 void InitRailTypes()
140 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
141 RailtypeInfo *rti = &_railtypes[rt];
142 ResolveRailTypeGUISprites(rti);
143 if (HasBit(rti->flags, RTF_HIDDEN)) SetBit(_railtypes_hidden_mask, rt);
146 _sorted_railtypes.clear();
147 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
148 if (_railtypes[rt].label != 0 && !HasBit(_railtypes_hidden_mask, rt)) {
149 _sorted_railtypes.push_back(rt);
152 std::sort(_sorted_railtypes.begin(), _sorted_railtypes.end(), CompareRailTypes);
156 * Allocate a new rail type label
158 RailType AllocateRailType(RailTypeLabel label)
160 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
161 RailtypeInfo *rti = &_railtypes[rt];
163 if (rti->label == 0) {
164 /* Set up new rail type */
165 *rti = _original_railtypes[RAILTYPE_RAIL];
166 rti->label = label;
167 rti->alternate_labels.clear();
169 /* Make us compatible with ourself. */
170 rti->powered_railtypes = (RailTypes)(1LL << rt);
171 rti->compatible_railtypes = (RailTypes)(1LL << rt);
173 /* We also introduce ourself. */
174 rti->introduces_railtypes = (RailTypes)(1LL << rt);
176 /* Default sort order; order of allocation, but with some
177 * offsets so it's easier for NewGRF to pick a spot without
178 * changing the order of other (original) rail types.
179 * The << is so you can place other railtypes in between the
180 * other railtypes, the 7 is to be able to place something
181 * before the first (default) rail type. */
182 rti->sorting_order = rt << 4 | 7;
183 return rt;
187 return INVALID_RAILTYPE;
190 static const byte _track_sloped_sprites[14] = {
191 14, 15, 22, 13,
192 0, 21, 17, 12,
193 23, 0, 18, 20,
194 19, 16
198 /* 4
199 * ---------
200 * |\ /|
201 * | \ 1/ |
202 * | \ / |
203 * | \ / |
204 * 16| \ |32
205 * | / \2 |
206 * | / \ |
207 * | / \ |
208 * |/ \|
209 * ---------
215 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
216 * MAP3LO byte: abcd???? => Signal Exists?
217 * a and b are for diagonals, upper and left,
218 * one for each direction. (ie a == NE->SW, b ==
219 * SW->NE, or v.v., I don't know. b and c are
220 * similar for lower and right.
221 * MAP2 byte: ????abcd => Type of ground.
222 * MAP3LO byte: ????abcd => Type of rail.
223 * MAP5: 00abcdef => rail
224 * 01abcdef => rail w/ signals
225 * 10uuuuuu => unused
226 * 11uuuudd => rail depot
230 * Tests if a vehicle interacts with the specified track.
231 * All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
233 * @param tile The tile.
234 * @param track The track.
235 * @return Succeeded command (no train found), or a failed command (a train was found).
237 static CommandCost EnsureNoTrainOnTrack(TileIndex tile, Track track)
239 TrackBits rail_bits = TrackToTrackBits(track);
240 return EnsureNoTrainOnTrackBits(tile, rail_bits);
244 * Check that the new track bits may be built.
245 * @param tile %Tile to build on.
246 * @param to_build New track bits.
247 * @param flags Flags of the operation.
248 * @return Succeeded or failed command.
250 static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
252 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
254 /* So, we have a tile with tracks on it (and possibly signals). Let's see
255 * what tracks first */
256 TrackBits current = GetTrackBits(tile); // The current track layout.
257 TrackBits future = current | to_build; // The track layout we want to build.
259 /* Are we really building something new? */
260 if (current == future) {
261 /* Nothing new is being built */
262 return_cmd_error(STR_ERROR_ALREADY_BUILT);
265 /* Let's see if we may build this */
266 if ((flags & DC_NO_RAIL_OVERLAP) || HasSignals(tile)) {
267 /* If we are not allowed to overlap (flag is on for ai companies or we have
268 * signals on the tile), check that */
269 if (future != TRACK_BIT_HORZ && future != TRACK_BIT_VERT) {
270 return_cmd_error((flags & DC_NO_RAIL_OVERLAP) ? STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION : STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
273 /* Normally, we may overlap and any combination is valid */
274 return CommandCost();
278 /** Valid TrackBits on a specific (non-steep)-slope without foundation */
279 static const TrackBits _valid_tracks_without_foundation[15] = {
280 TRACK_BIT_ALL,
281 TRACK_BIT_RIGHT,
282 TRACK_BIT_UPPER,
283 TRACK_BIT_X,
285 TRACK_BIT_LEFT,
286 TRACK_BIT_NONE,
287 TRACK_BIT_Y,
288 TRACK_BIT_LOWER,
290 TRACK_BIT_LOWER,
291 TRACK_BIT_Y,
292 TRACK_BIT_NONE,
293 TRACK_BIT_LEFT,
295 TRACK_BIT_X,
296 TRACK_BIT_UPPER,
297 TRACK_BIT_RIGHT,
300 /** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
301 static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
302 TRACK_BIT_NONE,
303 TRACK_BIT_LEFT,
304 TRACK_BIT_LOWER,
305 TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
307 TRACK_BIT_RIGHT,
308 TRACK_BIT_ALL,
309 TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
310 TRACK_BIT_ALL,
312 TRACK_BIT_UPPER,
313 TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
314 TRACK_BIT_ALL,
315 TRACK_BIT_ALL,
317 TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
318 TRACK_BIT_ALL,
319 TRACK_BIT_ALL
323 * Checks if a track combination is valid on a specific slope and returns the needed foundation.
325 * @param tileh Tile slope.
326 * @param bits Trackbits.
327 * @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
329 Foundation GetRailFoundation(Slope tileh, TrackBits bits)
331 if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
333 if (IsSteepSlope(tileh)) {
334 /* Test for inclined foundations */
335 if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
336 if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
338 /* Get higher track */
339 Corner highest_corner = GetHighestSlopeCorner(tileh);
340 TrackBits higher_track = CornerToTrackBits(highest_corner);
342 /* Only higher track? */
343 if (bits == higher_track) return HalftileFoundation(highest_corner);
345 /* Overlap with higher track? */
346 if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
348 /* either lower track or both higher and lower track */
349 return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
350 } else {
351 if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
353 bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
355 Corner track_corner;
356 switch (bits) {
357 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
358 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
359 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
360 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
362 case TRACK_BIT_HORZ:
363 if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
364 if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
365 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
367 case TRACK_BIT_VERT:
368 if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
369 if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
370 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
372 case TRACK_BIT_X:
373 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
374 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
376 case TRACK_BIT_Y:
377 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
378 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
380 default:
381 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
383 /* Single diagonal track */
385 /* Track must be at least valid on leveled foundation */
386 if (!valid_on_leveled) return FOUNDATION_INVALID;
388 /* If slope has three raised corners, build leveled foundation */
389 if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
391 /* If neighboured corners of track_corner are lowered, build halftile foundation */
392 if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
394 /* else special anti-zig-zag foundation */
395 return SpecialRailFoundation(track_corner);
401 * Tests if a track can be build on a tile.
403 * @param tileh Tile slope.
404 * @param rail_bits Tracks to build.
405 * @param existing Tracks already built.
406 * @param tile Tile (used for water test)
407 * @return Error message or cost for foundation building.
409 static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
411 /* don't allow building on the lower side of a coast */
412 if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
413 if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
416 Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
418 /* check track/slope combination */
419 if ((f_new == FOUNDATION_INVALID) ||
420 ((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
421 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
424 Foundation f_old = GetRailFoundation(tileh, existing);
425 return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
428 /* Validate functions for rail building */
429 static inline bool ValParamTrackOrientation(Track track)
431 return IsValidTrack(track);
435 * Build a single piece of rail
436 * @param tile tile to build on
437 * @param flags operation to perform
438 * @param p1 railtype of being built piece (normal, mono, maglev)
439 * @param p2 rail track to build
440 * @param text unused
441 * @return the cost of this operation or an error
443 CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
445 RailType railtype = Extract<RailType, 0, 6>(p1);
446 Track track = Extract<Track, 0, 3>(p2);
447 CommandCost cost(EXPENSES_CONSTRUCTION);
449 if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
451 Slope tileh = GetTileSlope(tile);
452 TrackBits trackbit = TrackToTrackBits(track);
454 switch (GetTileType(tile)) {
455 case MP_RAILWAY: {
456 CommandCost ret = CheckTileOwnership(tile);
457 if (ret.Failed()) return ret;
459 if (!IsPlainRail(tile)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); // just get appropriate error message
461 if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
463 ret = CheckTrackCombination(tile, trackbit, flags);
464 if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
465 if (ret.Failed()) return ret;
467 ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
468 if (ret.Failed()) return ret;
469 cost.AddCost(ret);
471 /* If the rail types don't match, try to convert only if engines of
472 * the new rail type are not powered on the present rail type and engines of
473 * the present rail type are powered on the new rail type. */
474 if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
475 if (HasPowerOnRail(GetRailType(tile), railtype)) {
476 ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
477 if (ret.Failed()) return ret;
478 cost.AddCost(ret);
479 } else {
480 return CMD_ERROR;
484 if (flags & DC_EXEC) {
485 SetRailGroundType(tile, RAIL_GROUND_BARREN);
486 TrackBits bits = GetTrackBits(tile);
487 SetTrackBits(tile, bits | trackbit);
488 /* Subtract old infrastructure count. */
489 uint pieces = CountBits(bits);
490 if (TracksOverlap(bits)) pieces *= pieces;
491 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
492 /* Add new infrastructure count. */
493 pieces = CountBits(bits | trackbit);
494 if (TracksOverlap(bits | trackbit)) pieces *= pieces;
495 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
496 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
498 break;
501 case MP_ROAD: {
502 /* Level crossings may only be built on these slopes */
503 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
505 CommandCost ret = EnsureNoVehicleOnGround(tile);
506 if (ret.Failed()) return ret;
508 if (IsNormalRoad(tile)) {
509 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
511 if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
513 if (RailNoLevelCrossings(railtype)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_RAIL);
515 RoadType roadtype_road = GetRoadTypeRoad(tile);
516 RoadType roadtype_tram = GetRoadTypeTram(tile);
518 if (roadtype_road != INVALID_ROADTYPE && RoadNoLevelCrossing(roadtype_road)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
519 if (roadtype_tram != INVALID_ROADTYPE && RoadNoLevelCrossing(roadtype_tram)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED_ROAD);
521 RoadBits road = GetRoadBits(tile, RTT_ROAD);
522 RoadBits tram = GetRoadBits(tile, RTT_TRAM);
523 if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
524 (track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
525 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
526 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
527 /* Disallow breaking end-of-line of someone else
528 * so trams can still reverse on this tile. */
529 if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
530 CommandCost ret = CheckOwnership(tram_owner);
531 if (ret.Failed()) return ret;
534 uint num_new_road_pieces = (road != ROAD_NONE) ? 2 - CountBits(road) : 0;
535 if (num_new_road_pieces > 0) {
536 cost.AddCost(num_new_road_pieces * RoadBuildCost(roadtype_road));
539 uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
540 if (num_new_tram_pieces > 0) {
541 cost.AddCost(num_new_tram_pieces * RoadBuildCost(roadtype_tram));
544 if (flags & DC_EXEC) {
545 MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtype_road, roadtype_tram, GetTownIndex(tile));
546 UpdateLevelCrossing(tile, false);
547 Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
548 DirtyCompanyInfrastructureWindows(_current_company);
549 if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
550 Company::Get(road_owner)->infrastructure.road[roadtype_road] += num_new_road_pieces;
551 DirtyCompanyInfrastructureWindows(road_owner);
553 if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
554 Company::Get(tram_owner)->infrastructure.road[roadtype_tram] += num_new_tram_pieces;
555 DirtyCompanyInfrastructureWindows(tram_owner);
558 break;
562 if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
563 return_cmd_error(STR_ERROR_ALREADY_BUILT);
565 FALLTHROUGH;
568 default: {
569 /* Will there be flat water on the lower halftile? */
570 bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
572 CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
573 if (ret.Failed()) return ret;
574 cost.AddCost(ret);
576 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
577 if (ret.Failed()) return ret;
578 cost.AddCost(ret);
580 if (water_ground) {
581 cost.AddCost(-_price[PR_CLEAR_WATER]);
582 cost.AddCost(_price[PR_CLEAR_ROUGH]);
585 if (flags & DC_EXEC) {
586 MakeRailNormal(tile, _current_company, trackbit, railtype);
587 if (water_ground) {
588 SetRailGroundType(tile, RAIL_GROUND_WATER);
589 if (IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
591 Company::Get(_current_company)->infrastructure.rail[railtype]++;
592 DirtyCompanyInfrastructureWindows(_current_company);
594 break;
598 if (flags & DC_EXEC) {
599 MarkTileDirtyByTile(tile);
600 AddTrackToSignalBuffer(tile, track, _current_company);
601 YapfNotifyTrackLayoutChange(tile, track);
604 cost.AddCost(RailBuildCost(railtype));
605 return cost;
609 * Remove a single piece of track
610 * @param tile tile to remove track from
611 * @param flags operation to perform
612 * @param p1 unused
613 * @param p2 rail orientation
614 * @param text unused
615 * @return the cost of this operation or an error
617 CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
619 Track track = Extract<Track, 0, 3>(p2);
620 CommandCost cost(EXPENSES_CONSTRUCTION);
621 bool crossing = false;
623 if (!ValParamTrackOrientation(track)) return CMD_ERROR;
624 TrackBits trackbit = TrackToTrackBits(track);
626 /* Need to read tile owner now because it may change when the rail is removed
627 * Also, in case of floods, _current_company != owner
628 * There may be invalid tiletype even in exec run (when removing long track),
629 * so do not call GetTileOwner(tile) in any case here */
630 Owner owner = INVALID_OWNER;
632 Train *v = nullptr;
634 switch (GetTileType(tile)) {
635 case MP_ROAD: {
636 if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
638 if (_current_company != OWNER_WATER) {
639 CommandCost ret = CheckTileOwnership(tile);
640 if (ret.Failed()) return ret;
643 if (!(flags & DC_BANKRUPT)) {
644 CommandCost ret = EnsureNoVehicleOnGround(tile);
645 if (ret.Failed()) return ret;
648 cost.AddCost(RailClearCost(GetRailType(tile)));
650 if (flags & DC_EXEC) {
651 if (HasReservedTracks(tile, trackbit)) {
652 v = GetTrainForReservation(tile, track);
653 if (v != nullptr) FreeTrainTrackReservation(v);
656 owner = GetTileOwner(tile);
657 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
658 DirtyCompanyInfrastructureWindows(owner);
659 MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypeRoad(tile), GetRoadTypeTram(tile), GetTownIndex(tile), GetRoadOwner(tile, RTT_ROAD), GetRoadOwner(tile, RTT_TRAM));
660 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
662 break;
665 case MP_RAILWAY: {
666 TrackBits present;
667 /* There are no rails present at depots. */
668 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
670 if (_current_company != OWNER_WATER) {
671 CommandCost ret = CheckTileOwnership(tile);
672 if (ret.Failed()) return ret;
675 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
676 if (ret.Failed()) return ret;
678 present = GetTrackBits(tile);
679 if ((present & trackbit) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
680 if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
682 cost.AddCost(RailClearCost(GetRailType(tile)));
684 /* Charge extra to remove signals on the track, if they are there */
685 if (HasSignalOnTrack(tile, track)) {
686 cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
689 if (flags & DC_EXEC) {
690 if (HasReservedTracks(tile, trackbit)) {
691 v = GetTrainForReservation(tile, track);
692 if (v != nullptr) FreeTrainTrackReservation(v);
695 owner = GetTileOwner(tile);
697 /* Subtract old infrastructure count. */
698 uint pieces = CountBits(present);
699 if (TracksOverlap(present)) pieces *= pieces;
700 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
701 /* Add new infrastructure count. */
702 present ^= trackbit;
703 pieces = CountBits(present);
704 if (TracksOverlap(present)) pieces *= pieces;
705 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
706 DirtyCompanyInfrastructureWindows(owner);
708 if (present == 0) {
709 Slope tileh = GetTileSlope(tile);
710 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
711 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
712 bool docking = IsDockingTile(tile);
713 MakeShore(tile);
714 SetDockingTile(tile, docking);
715 } else {
716 DoClearSquare(tile);
718 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
719 } else {
720 SetTrackBits(tile, present);
721 SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
724 break;
727 default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
730 if (flags & DC_EXEC) {
731 /* if we got that far, 'owner' variable is set correctly */
732 assert(Company::IsValidID(owner));
734 MarkTileDirtyByTile(tile);
735 if (crossing) {
736 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
737 * are removing one of these pieces, we'll need to update signals for
738 * both directions explicitly, as after the track is removed it won't
739 * 'connect' with the other piece. */
740 AddTrackToSignalBuffer(tile, TRACK_X, owner);
741 AddTrackToSignalBuffer(tile, TRACK_Y, owner);
742 YapfNotifyTrackLayoutChange(tile, TRACK_X);
743 YapfNotifyTrackLayoutChange(tile, TRACK_Y);
744 } else {
745 AddTrackToSignalBuffer(tile, track, owner);
746 YapfNotifyTrackLayoutChange(tile, track);
749 if (v != nullptr) TryPathReserve(v, true);
752 return cost;
757 * Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
758 * The function floods the lower halftile, if the tile has a halftile foundation.
760 * @param t The tile to flood.
761 * @return true if something was flooded.
763 bool FloodHalftile(TileIndex t)
765 assert(IsPlainRailTile(t));
767 bool flooded = false;
768 if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
770 Slope tileh = GetTileSlope(t);
771 TrackBits rail_bits = GetTrackBits(t);
773 if (IsSlopeWithOneCornerRaised(tileh)) {
774 TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
776 TrackBits to_remove = lower_track & rail_bits;
777 if (to_remove != 0) {
778 Backup<CompanyID> cur_company(_current_company, OWNER_WATER, FILE_LINE);
779 flooded = DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL).Succeeded();
780 cur_company.Restore();
781 if (!flooded) return flooded; // not yet floodable
782 rail_bits = rail_bits & ~to_remove;
783 if (rail_bits == 0) {
784 MakeShore(t);
785 MarkTileDirtyByTile(t);
786 return flooded;
790 if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
791 flooded = true;
792 SetRailGroundType(t, RAIL_GROUND_WATER);
793 MarkTileDirtyByTile(t);
795 } else {
796 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
797 if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
798 if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
799 flooded = true;
800 SetRailGroundType(t, RAIL_GROUND_WATER);
801 MarkTileDirtyByTile(t);
805 return flooded;
808 static const TileIndexDiffC _trackdelta[] = {
809 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
810 { 0, 0 },
811 { 0, 0 },
812 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
813 { 0, 0 },
814 { 0, 0 }
818 static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
820 int x = TileX(start);
821 int y = TileY(start);
822 int ex = TileX(end);
823 int ey = TileY(end);
825 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
827 /* calculate delta x,y from start to end tile */
828 int dx = ex - x;
829 int dy = ey - y;
831 /* calculate delta x,y for the first direction */
832 int trdx = _trackdelta[*trackdir].x;
833 int trdy = _trackdelta[*trackdir].y;
835 if (!IsDiagonalTrackdir(*trackdir)) {
836 trdx += _trackdelta[*trackdir ^ 1].x;
837 trdy += _trackdelta[*trackdir ^ 1].y;
840 /* validate the direction */
841 while ((trdx <= 0 && dx > 0) ||
842 (trdx >= 0 && dx < 0) ||
843 (trdy <= 0 && dy > 0) ||
844 (trdy >= 0 && dy < 0)) {
845 if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
846 SetBit(*trackdir, 3); // reverse the direction
847 trdx = -trdx;
848 trdy = -trdy;
849 } else { // other direction is invalid too, invalid drag
850 return CMD_ERROR;
854 /* (for diagonal tracks, this is already made sure of by above test), but:
855 * for non-diagonal tracks, check if the start and end tile are on 1 line */
856 if (!IsDiagonalTrackdir(*trackdir)) {
857 trdx = _trackdelta[*trackdir].x;
858 trdy = _trackdelta[*trackdir].y;
859 if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CMD_ERROR;
862 return CommandCost();
866 * Build or remove a stretch of railroad tracks.
867 * @param tile start tile of drag
868 * @param flags operation to perform
869 * @param p1 end tile of drag
870 * @param p2 various bitstuffed elements
871 * - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
872 * - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
873 * - p2 = (bit 9) - 0 = build, 1 = remove tracks
874 * - p2 = (bit 10) - 0 = build up to an obstacle, 1 = fail if an obstacle is found (used for AIs).
875 * @param text unused
876 * @return the cost of this operation or an error
878 static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
880 CommandCost total_cost(EXPENSES_CONSTRUCTION);
881 Track track = Extract<Track, 6, 3>(p2);
882 bool remove = HasBit(p2, 9);
883 RailType railtype = Extract<RailType, 0, 6>(p2);
885 if ((!remove && !ValParamRailtype(railtype)) || !ValParamTrackOrientation(track)) return CMD_ERROR;
886 if (p1 >= MapSize()) return CMD_ERROR;
887 TileIndex end_tile = p1;
888 Trackdir trackdir = TrackToTrackdir(track);
890 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
891 if (ret.Failed()) return ret;
893 bool had_success = false;
894 CommandCost last_error = CMD_ERROR;
895 for (;;) {
896 CommandCost ret = DoCommand(tile, remove ? 0 : railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
898 if (ret.Failed()) {
899 last_error = ret;
900 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
901 if (HasBit(p2, 10)) return last_error;
902 break;
905 /* Ownership errors are more important. */
906 if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
907 } else {
908 had_success = true;
909 total_cost.AddCost(ret);
912 if (tile == end_tile) break;
914 tile += ToTileIndexDiff(_trackdelta[trackdir]);
916 /* toggle railbit for the non-diagonal tracks */
917 if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
920 if (had_success) return total_cost;
921 return last_error;
925 * Build rail on a stretch of track.
926 * Stub for the unified rail builder/remover
927 * @param tile start tile of drag
928 * @param flags operation to perform
929 * @param p1 end tile of drag
930 * @param p2 various bitstuffed elements
931 * - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
932 * - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
933 * - p2 = (bit 9) - 0 = build, 1 = remove tracks
934 * @param text unused
935 * @return the cost of this operation or an error
936 * @see CmdRailTrackHelper
938 CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
940 return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 9), text);
944 * Build rail on a stretch of track.
945 * Stub for the unified rail builder/remover
946 * @param tile start tile of drag
947 * @param flags operation to perform
948 * @param p1 end tile of drag
949 * @param p2 various bitstuffed elements
950 * - p2 = (bit 0-5) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
951 * - p2 = (bit 6-8) - track-orientation, valid values: 0-5 (Track enum)
952 * - p2 = (bit 9) - 0 = build, 1 = remove tracks
953 * @param text unused
954 * @return the cost of this operation or an error
955 * @see CmdRailTrackHelper
957 CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
959 return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 9), text);
963 * Build a train depot
964 * @param tile position of the train depot
965 * @param flags operation to perform
966 * @param p1 rail type
967 * @param p2 bit 0..1 entrance direction (DiagDirection)
968 * @param text unused
969 * @return the cost of this operation or an error
971 * @todo When checking for the tile slope,
972 * distinguish between "Flat land required" and "land sloped in wrong direction"
974 CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
976 /* check railtype and valid direction for depot (0 through 3), 4 in total */
977 RailType railtype = Extract<RailType, 0, 6>(p1);
978 if (!ValParamRailtype(railtype)) return CMD_ERROR;
980 Slope tileh = GetTileSlope(tile);
982 DiagDirection dir = Extract<DiagDirection, 0, 2>(p2);
984 CommandCost cost(EXPENSES_CONSTRUCTION);
986 /* Prohibit construction if
987 * The tile is non-flat AND
988 * 1) build-on-slopes is disabled
989 * 2) the tile is steep i.e. spans two height levels
990 * 3) the exit points in the wrong direction
993 if (tileh != SLOPE_FLAT) {
994 if (!_settings_game.construction.build_on_slopes || !CanBuildDepotByTileh(dir, tileh)) {
995 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
997 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
1000 cost.AddCost(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR));
1001 if (cost.Failed()) return cost;
1003 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1005 if (!Depot::CanAllocateItem()) return CMD_ERROR;
1007 if (flags & DC_EXEC) {
1008 Depot *d = new Depot(tile);
1009 d->build_date = _date;
1011 MakeRailDepot(tile, _current_company, d->index, dir, railtype);
1012 MarkTileDirtyByTile(tile);
1013 MakeDefaultName(d);
1015 Company::Get(_current_company)->infrastructure.rail[railtype]++;
1016 DirtyCompanyInfrastructureWindows(_current_company);
1018 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, _current_company);
1019 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1022 cost.AddCost(_price[PR_BUILD_DEPOT_TRAIN]);
1023 cost.AddCost(RailBuildCost(railtype));
1024 return cost;
1028 * Build signals, alternate between double/single, signal/semaphore,
1029 * pre/exit/combo-signals, and what-else not. If the rail piece does not
1030 * have any signals, bit 4 (cycle signal-type) is ignored
1031 * @param tile tile where to build the signals
1032 * @param flags operation to perform
1033 * @param p1 various bitstuffed elements
1034 * - p1 = (bit 0-2) - track-orientation, valid values: 0-5 (Track enum)
1035 * - p1 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal or (for bit 7) toggle variant (CTRL-toggle)
1036 * - p1 = (bit 4) - 0 = signals, 1 = semaphores
1037 * - p1 = (bit 5-7) - type of the signal, for valid values see enum SignalType in rail_map.h
1038 * - p1 = (bit 8) - convert the present signal type and variant
1039 * - p1 = (bit 9-11)- start cycle from this signal type
1040 * - p1 = (bit 12-14)-wrap around after this signal type
1041 * - p1 = (bit 15-16)-cycle the signal direction this many times
1042 * - p1 = (bit 17) - 1 = don't modify an existing signal but don't fail either, 0 = always set new signal type
1043 * @param p2 used for CmdBuildManySignals() to copy direction of first signal
1044 * @param text unused
1045 * @return the cost of this operation or an error
1046 * @todo p2 should be replaced by two bits for "along" and "against" the track.
1048 CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1050 Track track = Extract<Track, 0, 3>(p1);
1051 bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed
1052 SignalVariant sigvar = (ctrl_pressed ^ HasBit(p1, 4)) ? SIG_SEMAPHORE : SIG_ELECTRIC; // the signal variant of the new signal
1053 SignalType sigtype = Extract<SignalType, 5, 3>(p1); // the signal type of the new signal
1054 bool convert_signal = HasBit(p1, 8); // convert button pressed
1055 SignalType cycle_start = Extract<SignalType, 9, 3>(p1);
1056 SignalType cycle_stop = Extract<SignalType, 12, 3>(p1);
1057 uint num_dir_cycle = GB(p1, 15, 2);
1059 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1060 if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CMD_ERROR;
1062 /* You can only build signals on plain rail tiles, and the selected track must exist */
1063 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) ||
1064 !HasTrack(tile, track)) {
1065 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1067 /* Protect against invalid signal copying */
1068 if (p2 != 0 && (p2 & SignalOnTrack(track)) == 0) return CMD_ERROR;
1070 CommandCost ret = CheckTileOwnership(tile);
1071 if (ret.Failed()) return ret;
1073 /* See if this is a valid track combination for signals (no overlap) */
1074 if (TracksOverlap(GetTrackBits(tile))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
1076 /* In case we don't want to change an existing signal, return without error. */
1077 if (HasBit(p1, 17) && HasSignalOnTrack(tile, track)) return CommandCost();
1079 /* you can not convert a signal if no signal is on track */
1080 if (convert_signal && !HasSignalOnTrack(tile, track)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1082 CommandCost cost;
1083 if (!HasSignalOnTrack(tile, track)) {
1084 /* build new signals */
1085 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS]);
1086 } else {
1087 if (p2 != 0 && sigvar != GetSignalVariant(tile, track)) {
1088 /* convert signals <-> semaphores */
1089 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1091 } else if (convert_signal) {
1092 /* convert button pressed */
1093 if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
1094 /* convert electric <-> semaphore */
1095 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1096 } else {
1097 /* it is free to change signal type: normal-pre-exit-combo */
1098 cost = CommandCost();
1101 } else {
1102 /* it is free to change orientation/pre-exit-combo signals */
1103 cost = CommandCost();
1107 if (flags & DC_EXEC) {
1108 Train *v = nullptr;
1109 /* The new/changed signal could block our path. As this can lead to
1110 * stale reservations, we clear the path reservation here and try
1111 * to redo it later on. */
1112 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1113 v = GetTrainForReservation(tile, track);
1114 if (v != nullptr) FreeTrainTrackReservation(v);
1117 if (!HasSignals(tile)) {
1118 /* there are no signals at all on this tile yet */
1119 SetHasSignals(tile, true);
1120 SetSignalStates(tile, 0xF); // all signals are on
1121 SetPresentSignals(tile, 0); // no signals built by default
1122 SetSignalType(tile, track, sigtype);
1123 SetSignalVariant(tile, track, sigvar);
1126 /* Subtract old signal infrastructure count. */
1127 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1129 if (p2 == 0) {
1130 if (!HasSignalOnTrack(tile, track)) {
1131 /* build new signals */
1132 SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
1133 SetSignalType(tile, track, sigtype);
1134 SetSignalVariant(tile, track, sigvar);
1135 while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
1136 } else {
1137 if (convert_signal) {
1138 /* convert signal button pressed */
1139 if (ctrl_pressed) {
1140 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1141 SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1142 /* Query current signal type so the check for PBS signals below works. */
1143 sigtype = GetSignalType(tile, track);
1144 } else {
1145 /* convert the present signal to the chosen type and variant */
1146 SetSignalType(tile, track, sigtype);
1147 SetSignalVariant(tile, track, sigvar);
1148 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1149 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1153 } else if (ctrl_pressed) {
1154 /* cycle between cycle_start and cycle_end */
1155 sigtype = (SignalType)(GetSignalType(tile, track) + 1);
1157 if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
1159 SetSignalType(tile, track, sigtype);
1160 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1161 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1163 } else {
1164 /* cycle the signal side: both -> left -> right -> both -> ... */
1165 CycleSignalSide(tile, track);
1166 /* Query current signal type so the check for PBS signals below works. */
1167 sigtype = GetSignalType(tile, track);
1170 } else {
1171 /* If CmdBuildManySignals is called with copying signals, just copy the
1172 * direction of the first signal given as parameter by CmdBuildManySignals */
1173 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (p2 & SignalOnTrack(track)));
1174 SetSignalVariant(tile, track, sigvar);
1175 SetSignalType(tile, track, sigtype);
1178 /* Add new signal infrastructure count. */
1179 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1180 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1182 if (IsPbsSignal(sigtype)) {
1183 /* PBS signals should show red unless they are on reserved tiles without a train. */
1184 uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
1185 SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetRailReservationTrackBits(tile), track) && EnsureNoVehicleOnGround(tile).Succeeded() ? UINT_MAX : 0) & mask));
1187 MarkTileDirtyByTile(tile);
1188 AddTrackToSignalBuffer(tile, track, _current_company);
1189 YapfNotifyTrackLayoutChange(tile, track);
1190 if (v != nullptr) {
1191 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1192 if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
1193 !IsSafeWaitingPosition(v, v->tile, v->GetVehicleTrackdir(), true, _settings_game.pf.forbid_90_deg)) {
1194 TryPathReserve(v, true);
1199 return cost;
1202 static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal_ctr, bool remove)
1204 tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
1205 if (tile == INVALID_TILE) return false;
1207 /* Check for track bits on the new tile */
1208 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
1210 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
1211 trackdirbits &= TrackdirReachesTrackdirs(trackdir);
1213 /* No track bits, must stop */
1214 if (trackdirbits == TRACKDIR_BIT_NONE) return false;
1216 /* Get the first track dir */
1217 trackdir = RemoveFirstTrackdir(&trackdirbits);
1219 /* Any left? It's a junction so we stop */
1220 if (trackdirbits != TRACKDIR_BIT_NONE) return false;
1222 switch (GetTileType(tile)) {
1223 case MP_RAILWAY:
1224 if (IsRailDepot(tile)) return false;
1225 if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
1226 signal_ctr++;
1227 if (IsDiagonalTrackdir(trackdir)) {
1228 signal_ctr++;
1229 /* Ensure signal_ctr even so X and Y pieces get signals */
1230 ClrBit(signal_ctr, 0);
1232 return true;
1234 case MP_ROAD:
1235 if (!IsLevelCrossing(tile)) return false;
1236 signal_ctr += 2;
1237 return true;
1239 case MP_TUNNELBRIDGE: {
1240 TileIndex orig_tile = tile; // backup old value
1242 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
1243 if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
1245 /* Skip to end of tunnel or bridge
1246 * note that tile is a parameter by reference, so it must be updated */
1247 tile = GetOtherTunnelBridgeEnd(tile);
1249 signal_ctr += (GetTunnelBridgeLength(orig_tile, tile) + 2) * 2;
1250 return true;
1253 default: return false;
1258 * Build many signals by dragging; AutoSignals
1259 * @param tile start tile of drag
1260 * @param flags operation to perform
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(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *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 byte 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 /* for vertical/horizontal tracks, double the given signals density
1294 * since the original amount will be too dense (shorter tracks) */
1295 signal_density *= 2;
1297 Trackdir trackdir = TrackToTrackdir(track);
1298 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
1299 if (ret.Failed()) return ret;
1301 track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
1302 Trackdir start_trackdir = trackdir;
1304 /* Must start on a valid track to be able to avoid loops */
1305 if (!HasTrack(tile, track)) return CMD_ERROR;
1307 SignalType sigtype = (SignalType)GB(p2, 7, 3);
1308 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1310 byte signals;
1311 /* copy the signal-style of the first rail-piece if existing */
1312 if (HasSignalOnTrack(tile, track)) {
1313 signals = GetPresentSignals(tile) & SignalOnTrack(track);
1314 assert(signals != 0);
1316 /* copy signal/semaphores style (independent of CTRL) */
1317 semaphores = GetSignalVariant(tile, track) != SIG_ELECTRIC;
1319 sigtype = GetSignalType(tile, track);
1320 /* Don't but copy entry or exit-signal type */
1321 if (sigtype == SIGTYPE_ENTRY || sigtype == SIGTYPE_EXIT) sigtype = SIGTYPE_NORMAL;
1322 } else { // no signals exist, drag a two-way signal stretch
1323 signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
1326 byte signal_dir = 0;
1327 if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
1328 if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
1330 /* signal_ctr - amount of tiles already processed
1331 * last_used_ctr - amount of tiles before previously placed signal
1332 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1333 * last_suitable_ctr - amount of tiles before last possible signal place
1334 * last_suitable_tile - last tile where it is possible to place a signal
1335 * last_suitable_trackdir - trackdir of the last tile
1336 **********
1337 * trackdir - trackdir to build with autorail
1338 * semaphores - semaphores or signals
1339 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1340 * and convert all others to semaphore/signal
1341 * remove - 1 remove signals, 0 build signals */
1342 int signal_ctr = 0;
1343 int last_used_ctr = INT_MIN; // initially INT_MIN to force building/removing at the first tile
1344 int last_suitable_ctr = 0;
1345 TileIndex last_suitable_tile = INVALID_TILE;
1346 Trackdir last_suitable_trackdir = INVALID_TRACKDIR;
1347 CommandCost last_error = CMD_ERROR;
1348 bool had_success = false;
1349 for (;;) {
1350 /* only build/remove signals with the specified density */
1351 if (remove || minimise_gaps || signal_ctr % signal_density == 0) {
1352 uint32 p1 = GB(TrackdirToTrack(trackdir), 0, 3);
1353 SB(p1, 3, 1, mode);
1354 SB(p1, 4, 1, semaphores);
1355 SB(p1, 5, 3, sigtype);
1356 if (!remove && signal_ctr == 0) SetBit(p1, 17);
1358 /* Pick the correct orientation for the track direction */
1359 signals = 0;
1360 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
1361 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
1363 /* Test tiles in between for suitability as well if minimising gaps. */
1364 bool test_only = !remove && minimise_gaps && signal_ctr < (last_used_ctr + signal_density);
1365 CommandCost ret = DoCommand(tile, p1, signals, test_only ? flags & ~DC_EXEC : flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1367 if (ret.Succeeded()) {
1368 /* Remember last track piece where we can place a signal. */
1369 last_suitable_ctr = signal_ctr;
1370 last_suitable_tile = tile;
1371 last_suitable_trackdir = trackdir;
1372 } else if (!test_only && last_suitable_tile != INVALID_TILE) {
1373 /* If a signal can't be placed, place it at the last possible position. */
1374 SB(p1, 0, 3, TrackdirToTrack(last_suitable_trackdir));
1375 ClrBit(p1, 17);
1377 /* Pick the correct orientation for the track direction. */
1378 signals = 0;
1379 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(last_suitable_trackdir);
1380 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(last_suitable_trackdir);
1382 ret = DoCommand(last_suitable_tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1385 /* Collect cost. */
1386 if (!test_only) {
1387 /* Be user-friendly and try placing signals as much as possible */
1388 if (ret.Succeeded()) {
1389 had_success = true;
1390 total_cost.AddCost(ret);
1391 last_used_ctr = last_suitable_ctr;
1392 last_suitable_tile = INVALID_TILE;
1393 } else {
1394 /* The "No railway" error is the least important one. */
1395 if (ret.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK ||
1396 last_error.GetErrorMessage() == INVALID_STRING_ID) {
1397 last_error = ret;
1403 if (autofill) {
1404 if (!CheckSignalAutoFill(tile, trackdir, signal_ctr, remove)) break;
1406 /* Prevent possible loops */
1407 if (tile == start_tile && trackdir == start_trackdir) break;
1408 } else {
1409 if (tile == end_tile) break;
1411 tile += ToTileIndexDiff(_trackdelta[trackdir]);
1412 signal_ctr++;
1414 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1415 if (IsDiagonalTrackdir(trackdir)) {
1416 signal_ctr++;
1417 } else {
1418 ToggleBit(trackdir, 0);
1423 return had_success ? total_cost : last_error;
1427 * Build signals on a stretch of track.
1428 * Stub for the unified signal builder/remover
1429 * @param tile start tile of drag
1430 * @param flags operation to perform
1431 * @param p1 end tile of drag
1432 * @param p2 various bitstuffed elements
1433 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1434 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1435 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1436 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1437 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1438 * - p2 = (bit 7- 9) - default signal type
1439 * - p2 = (bit 24-31) - user defined signals_density
1440 * @param text unused
1441 * @return the cost of this operation or an error
1442 * @see CmdSignalTrackHelper
1444 CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1446 return CmdSignalTrackHelper(tile, flags, p1, p2, text);
1450 * Remove signals
1451 * @param tile coordinates where signal is being deleted from
1452 * @param flags operation to perform
1453 * @param p1 various bitstuffed elements, only track information is used
1454 * - (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1455 * - (bit 3) - override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1456 * - (bit 4) - 0 = signals, 1 = semaphores
1457 * @param p2 unused
1458 * @param text unused
1459 * @return the cost of this operation or an error
1461 CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1463 Track track = Extract<Track, 0, 3>(p1);
1465 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1466 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1468 if (!HasSignalOnTrack(tile, track)) {
1469 return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1472 /* Only water can remove signals from anyone */
1473 if (_current_company != OWNER_WATER) {
1474 CommandCost ret = CheckTileOwnership(tile);
1475 if (ret.Failed()) return ret;
1478 /* Do it? */
1479 if (flags & DC_EXEC) {
1480 Train *v = nullptr;
1481 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1482 v = GetTrainForReservation(tile, track);
1483 } else if (IsPbsSignal(GetSignalType(tile, track))) {
1484 /* PBS signal, might be the end of a path reservation. */
1485 Trackdir td = TrackToTrackdir(track);
1486 for (int i = 0; v == nullptr && i < 2; i++, td = ReverseTrackdir(td)) {
1487 /* Only test the active signal side. */
1488 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
1489 TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
1490 TrackBits tracks = TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td));
1491 if (HasReservedTracks(next, tracks)) {
1492 v = GetTrainForReservation(next, TrackBitsToTrack(GetReservedTrackbits(next) & tracks));
1496 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1497 SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
1498 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1499 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1501 /* removed last signal from tile? */
1502 if (GetPresentSignals(tile) == 0) {
1503 SetSignalStates(tile, 0);
1504 SetHasSignals(tile, false);
1505 SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
1508 AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
1509 YapfNotifyTrackLayoutChange(tile, track);
1510 if (v != nullptr) TryPathReserve(v, false);
1512 MarkTileDirtyByTile(tile);
1515 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_SIGNALS]);
1519 * Remove signals on a stretch of track.
1520 * Stub for the unified signal builder/remover
1521 * @param tile start tile of drag
1522 * @param flags operation to perform
1523 * @param p1 end tile of drag
1524 * @param p2 various bitstuffed elements
1525 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1526 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1527 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1528 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1529 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1530 * - p2 = (bit 7- 9) - default signal type
1531 * - p2 = (bit 24-31) - user defined signals_density
1532 * @param text unused
1533 * @return the cost of this operation or an error
1534 * @see CmdSignalTrackHelper
1536 CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1538 return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
1541 /** Update power of train under which is the railtype being converted */
1542 static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
1544 if (v->type != VEH_TRAIN) return nullptr;
1546 TrainList *affected_trains = static_cast<TrainList*>(data);
1547 include(*affected_trains, Train::From(v)->First());
1549 return nullptr;
1553 * Convert one rail type to the other. You can convert normal rail to
1554 * monorail/maglev easily or vice-versa.
1555 * @param tile end tile of rail conversion drag
1556 * @param flags operation to perform
1557 * @param p1 start tile of drag
1558 * @param p2 various bitstuffed elements:
1559 * - p2 = (bit 0- 5) new railtype to convert to.
1560 * - p2 = (bit 6) build diagonally or not.
1561 * @param text unused
1562 * @return the cost of this operation or an error
1564 CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1566 RailType totype = Extract<RailType, 0, 6>(p2);
1567 TileIndex area_start = p1;
1568 TileIndex area_end = tile;
1569 bool diagonal = HasBit(p2, 6);
1571 if (!ValParamRailtype(totype)) return CMD_ERROR;
1572 if (area_start >= MapSize()) return CMD_ERROR;
1574 TrainList affected_trains;
1576 CommandCost cost(EXPENSES_CONSTRUCTION);
1577 CommandCost error = CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK); // by default, there is no track to convert.
1578 bool found_convertible_track = false; // whether we actually did convert some track (see bug #7633)
1580 TileIterator *iter = diagonal ? (TileIterator *)new DiagonalTileIterator(area_start, area_end) : new OrthogonalTileIterator(area_start, area_end);
1581 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
1582 TileType tt = GetTileType(tile);
1584 /* Check if there is any track on tile */
1585 switch (tt) {
1586 case MP_RAILWAY:
1587 break;
1588 case MP_STATION:
1589 if (!HasStationRail(tile)) continue;
1590 break;
1591 case MP_ROAD:
1592 if (!IsLevelCrossing(tile)) continue;
1593 if (RailNoLevelCrossings(totype)) {
1594 error.MakeError(STR_ERROR_CROSSING_DISALLOWED_RAIL);
1595 continue;
1597 break;
1598 case MP_TUNNELBRIDGE:
1599 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
1600 break;
1601 default: continue;
1604 /* Original railtype we are converting from */
1605 RailType type = GetRailType(tile);
1607 /* Converting to the same type or converting 'hidden' elrail -> rail */
1608 if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
1610 /* Trying to convert other's rail */
1611 CommandCost ret = CheckTileOwnership(tile);
1612 if (ret.Failed()) {
1613 error = ret;
1614 continue;
1617 std::vector<Train *> vehicles_affected;
1619 /* Vehicle on the tile when not converting Rail <-> ElRail
1620 * Tunnels and bridges have special check later */
1621 if (tt != MP_TUNNELBRIDGE) {
1622 if (!IsCompatibleRail(type, totype)) {
1623 CommandCost ret = IsPlainRailTile(tile) ? EnsureNoTrainOnTrackBits(tile, GetTrackBits(tile)) : EnsureNoVehicleOnGround(tile);
1624 if (ret.Failed()) {
1625 error = ret;
1626 continue;
1629 if (flags & DC_EXEC) { // we can safely convert, too
1630 TrackBits reserved = GetReservedTrackbits(tile);
1631 Track track;
1632 while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
1633 Train *v = GetTrainForReservation(tile, track);
1634 if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
1635 /* No power on new rail type, reroute. */
1636 FreeTrainTrackReservation(v);
1637 vehicles_affected.push_back(v);
1641 /* Update the company infrastructure counters. */
1642 if (!IsRailStationTile(tile) || !IsStationTileBlocked(tile)) {
1643 Company *c = Company::Get(GetTileOwner(tile));
1644 uint num_pieces = IsLevelCrossingTile(tile) ? LEVELCROSSING_TRACKBIT_FACTOR : 1;
1645 if (IsPlainRailTile(tile)) {
1646 TrackBits bits = GetTrackBits(tile);
1647 num_pieces = CountBits(bits);
1648 if (TracksOverlap(bits)) num_pieces *= num_pieces;
1650 c->infrastructure.rail[type] -= num_pieces;
1651 c->infrastructure.rail[totype] += num_pieces;
1652 DirtyCompanyInfrastructureWindows(c->index);
1655 SetRailType(tile, totype);
1656 MarkTileDirtyByTile(tile);
1657 /* update power of train on this tile */
1658 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1662 switch (tt) {
1663 case MP_RAILWAY:
1664 switch (GetRailTileType(tile)) {
1665 case RAIL_TILE_DEPOT:
1666 if (flags & DC_EXEC) {
1667 /* notify YAPF about the track layout change */
1668 YapfNotifyTrackLayoutChange(tile, GetRailDepotTrack(tile));
1670 /* Update build vehicle window related to this depot */
1671 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
1672 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
1674 found_convertible_track = true;
1675 cost.AddCost(RailConvertCost(type, totype));
1676 break;
1678 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1679 if (flags & DC_EXEC) {
1680 /* notify YAPF about the track layout change */
1681 TrackBits tracks = GetTrackBits(tile);
1682 while (tracks != TRACK_BIT_NONE) {
1683 YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(&tracks));
1686 found_convertible_track = true;
1687 cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
1688 break;
1690 break;
1692 case MP_TUNNELBRIDGE: {
1693 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
1695 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1696 * it would cause assert because of different test and exec runs */
1697 if (endtile < tile) {
1698 if (diagonal) {
1699 if (DiagonalTileArea(area_start, area_end).Contains(endtile)) continue;
1700 } else {
1701 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
1705 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1706 if (!IsCompatibleRail(GetRailType(tile), totype)) {
1707 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
1708 if (ret.Failed()) {
1709 error = ret;
1710 continue;
1714 if (flags & DC_EXEC) {
1715 Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
1716 if (HasTunnelBridgeReservation(tile)) {
1717 Train *v = GetTrainForReservation(tile, track);
1718 if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
1719 /* No power on new rail type, reroute. */
1720 FreeTrainTrackReservation(v);
1721 vehicles_affected.push_back(v);
1725 /* Update the company infrastructure counters. */
1726 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1727 Company *c = Company::Get(GetTileOwner(tile));
1728 c->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1729 c->infrastructure.rail[totype] += num_pieces;
1730 DirtyCompanyInfrastructureWindows(c->index);
1732 SetRailType(tile, totype);
1733 SetRailType(endtile, totype);
1735 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1736 FindVehicleOnPos(endtile, &affected_trains, &UpdateTrainPowerProc);
1738 YapfNotifyTrackLayoutChange(tile, track);
1739 YapfNotifyTrackLayoutChange(endtile, track);
1741 if (IsBridge(tile)) {
1742 MarkBridgeDirty(tile);
1743 } else {
1744 MarkTileDirtyByTile(tile);
1745 MarkTileDirtyByTile(endtile);
1749 found_convertible_track = true;
1750 cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
1751 break;
1754 default: // MP_STATION, MP_ROAD
1755 if (flags & DC_EXEC) {
1756 Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
1757 YapfNotifyTrackLayoutChange(tile, track);
1760 found_convertible_track = true;
1761 cost.AddCost(RailConvertCost(type, totype));
1762 break;
1765 for (uint i = 0; i < vehicles_affected.size(); ++i) {
1766 TryPathReserve(vehicles_affected[i], true);
1770 if (flags & DC_EXEC) {
1771 /* Railtype changed, update trains as when entering different track */
1772 for (Train *v : affected_trains) {
1773 v->ConsistChanged(CCF_TRACK);
1777 delete iter;
1778 return found_convertible_track ? cost : error;
1781 static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
1783 if (_current_company != OWNER_WATER) {
1784 CommandCost ret = CheckTileOwnership(tile);
1785 if (ret.Failed()) return ret;
1788 CommandCost ret = EnsureNoVehicleOnGround(tile);
1789 if (ret.Failed()) return ret;
1791 if (flags & DC_EXEC) {
1792 /* read variables before the depot is removed */
1793 DiagDirection dir = GetRailDepotDirection(tile);
1794 Owner owner = GetTileOwner(tile);
1795 Train *v = nullptr;
1797 if (HasDepotReservation(tile)) {
1798 v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
1799 if (v != nullptr) FreeTrainTrackReservation(v);
1802 Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1803 DirtyCompanyInfrastructureWindows(owner);
1805 delete Depot::GetByTile(tile);
1806 DoClearSquare(tile);
1807 AddSideToSignalBuffer(tile, dir, owner);
1808 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1809 if (v != nullptr) TryPathReserve(v, true);
1812 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
1815 static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
1817 CommandCost cost(EXPENSES_CONSTRUCTION);
1819 if (flags & DC_AUTO) {
1820 if (!IsTileOwner(tile, _current_company)) {
1821 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
1824 if (IsPlainRail(tile)) {
1825 return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
1826 } else {
1827 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1831 switch (GetRailTileType(tile)) {
1832 case RAIL_TILE_SIGNALS:
1833 case RAIL_TILE_NORMAL: {
1834 Slope tileh = GetTileSlope(tile);
1835 /* Is there flat water on the lower halftile that gets cleared expensively? */
1836 bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
1838 TrackBits tracks = GetTrackBits(tile);
1839 while (tracks != TRACK_BIT_NONE) {
1840 Track track = RemoveFirstTrack(&tracks);
1841 CommandCost ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
1842 if (ret.Failed()) return ret;
1843 cost.AddCost(ret);
1846 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
1847 * Same holds for non-companies clearing the tile, e.g. disasters. */
1848 if (water_ground && !(flags & DC_BANKRUPT) && Company::IsValidID(_current_company)) {
1849 CommandCost ret = EnsureNoVehicleOnGround(tile);
1850 if (ret.Failed()) return ret;
1852 /* The track was removed, and left a coast tile. Now also clear the water. */
1853 if (flags & DC_EXEC) {
1854 bool remove = IsDockingTile(tile);
1855 DoClearSquare(tile);
1856 if (remove) RemoveDockingTile(tile);
1858 cost.AddCost(_price[PR_CLEAR_WATER]);
1861 return cost;
1864 case RAIL_TILE_DEPOT:
1865 return RemoveTrainDepot(tile, flags);
1867 default:
1868 return CMD_ERROR;
1873 * Get surface height in point (x,y)
1874 * On tiles with halftile foundations move (x,y) to a safe point wrt. track
1876 static uint GetSaveSlopeZ(uint x, uint y, Track track)
1878 switch (track) {
1879 case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
1880 case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
1881 case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
1882 case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
1883 default: break;
1885 return GetSlopePixelZ(x, y);
1888 static void DrawSingleSignal(TileIndex tile, const RailtypeInfo *rti, Track track, SignalState condition, SignalOffsets image, uint pos)
1890 bool side;
1891 switch (_settings_game.construction.train_signal_side) {
1892 case 0: side = false; break; // left
1893 case 2: side = true; break; // right
1894 default: side = _settings_game.vehicle.road_side != 0; break; // driving side
1896 static const Point SignalPositions[2][12] = {
1897 { // Signals on the left side
1898 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1899 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
1900 /* LOWER LOWER X X Y Y */
1901 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1902 }, { // Signals on the right side
1903 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1904 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
1905 /* LOWER LOWER X X Y Y */
1906 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1910 uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
1911 uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
1913 SignalType type = GetSignalType(tile, track);
1914 SignalVariant variant = GetSignalVariant(tile, track);
1916 SpriteID sprite = GetCustomSignalSprite(rti, tile, type, variant, condition);
1917 if (sprite != 0) {
1918 sprite += image;
1919 } else {
1920 /* Normal electric signals are stored in a different sprite block than all other signals. */
1921 sprite = (type == SIGTYPE_NORMAL && variant == SIG_ELECTRIC) ? SPR_ORIGINAL_SIGNALS_BASE : SPR_SIGNALS_BASE - 16;
1922 sprite += type * 16 + variant * 64 + image * 2 + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
1925 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
1928 static uint32 _drawtile_track_palette;
1932 /** Offsets for drawing fences */
1933 struct FenceOffset {
1934 Corner height_ref; //!< Corner to use height offset from.
1935 int x_offs; //!< Bounding box X offset.
1936 int y_offs; //!< Bounding box Y offset.
1937 int x_size; //!< Bounding box X size.
1938 int y_size; //!< Bounding box Y size.
1941 /** Offsets for drawing fences */
1942 static FenceOffset _fence_offsets[] = {
1943 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
1944 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
1945 { CORNER_W, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
1946 { CORNER_N, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
1947 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
1948 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
1949 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
1950 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
1951 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
1952 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
1953 { CORNER_E, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
1954 { CORNER_S, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
1955 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
1956 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
1957 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
1958 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
1962 * Draw a track fence.
1963 * @param ti Tile drawing information.
1964 * @param base_image First fence sprite.
1965 * @param num_sprites Number of fence sprites.
1966 * @param rfo Fence to draw.
1968 static void DrawTrackFence(const TileInfo *ti, SpriteID base_image, uint num_sprites, RailFenceOffset rfo)
1970 int z = ti->z;
1971 if (_fence_offsets[rfo].height_ref != CORNER_INVALID) {
1972 z += GetSlopePixelZInCorner(RemoveHalftileSlope(ti->tileh), _fence_offsets[rfo].height_ref);
1974 AddSortableSpriteToDraw(base_image + (rfo % num_sprites), _drawtile_track_palette,
1975 ti->x + _fence_offsets[rfo].x_offs,
1976 ti->y + _fence_offsets[rfo].y_offs,
1977 _fence_offsets[rfo].x_size,
1978 _fence_offsets[rfo].y_size,
1979 4, z);
1983 * Draw fence at NW border matching the tile slope.
1985 static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1987 RailFenceOffset rfo = RFO_FLAT_X_NW;
1988 if (ti->tileh & SLOPE_NW) rfo = (ti->tileh & SLOPE_W) ? RFO_SLOPE_SW_NW : RFO_SLOPE_NE_NW;
1989 DrawTrackFence(ti, base_image, num_sprites, rfo);
1993 * Draw fence at SE border matching the tile slope.
1995 static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1997 RailFenceOffset rfo = RFO_FLAT_X_SE;
1998 if (ti->tileh & SLOPE_SE) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW_SE : RFO_SLOPE_NE_SE;
1999 DrawTrackFence(ti, base_image, num_sprites, rfo);
2003 * Draw fence at NE border matching the tile slope.
2005 static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2007 RailFenceOffset rfo = RFO_FLAT_Y_NE;
2008 if (ti->tileh & SLOPE_NE) rfo = (ti->tileh & SLOPE_E) ? RFO_SLOPE_SE_NE : RFO_SLOPE_NW_NE;
2009 DrawTrackFence(ti, base_image, num_sprites, rfo);
2013 * Draw fence at SW border matching the tile slope.
2015 static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2017 RailFenceOffset rfo = RFO_FLAT_Y_SW;
2018 if (ti->tileh & SLOPE_SW) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE_SW : RFO_SLOPE_NW_SW;
2019 DrawTrackFence(ti, base_image, num_sprites, rfo);
2023 * Draw track fences.
2024 * @param ti Tile drawing information.
2025 * @param rti Rail type information.
2027 static void DrawTrackDetails(const TileInfo *ti, const RailtypeInfo *rti)
2029 /* Base sprite for track fences.
2030 * Note: Halftile slopes only have fences on the upper part. */
2031 uint num_sprites = 0;
2032 SpriteID base_image = GetCustomRailSprite(rti, ti->tile, RTSG_FENCES, IsHalftileSlope(ti->tileh) ? TCX_UPPER_HALFTILE : TCX_NORMAL, &num_sprites);
2033 if (base_image == 0) {
2034 base_image = SPR_TRACK_FENCE_FLAT_X;
2035 num_sprites = 8;
2038 assert(num_sprites > 0);
2040 switch (GetRailGroundType(ti->tile)) {
2041 case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image, num_sprites); break;
2042 case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image, num_sprites); break;
2043 case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW(ti, base_image, num_sprites);
2044 DrawTrackFence_SE(ti, base_image, num_sprites); break;
2045 case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image, num_sprites); break;
2046 case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image, num_sprites); break;
2047 case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE(ti, base_image, num_sprites);
2048 DrawTrackFence_SW(ti, base_image, num_sprites); break;
2049 case RAIL_GROUND_FENCE_VERT1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2050 case RAIL_GROUND_FENCE_VERT2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2051 case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2052 case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2053 case RAIL_GROUND_WATER: {
2054 Corner track_corner;
2055 if (IsHalftileSlope(ti->tileh)) {
2056 /* Steep slope or one-corner-raised slope with halftile foundation */
2057 track_corner = GetHalftileSlopeCorner(ti->tileh);
2058 } else {
2059 /* Three-corner-raised slope */
2060 track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2062 switch (track_corner) {
2063 case CORNER_W: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2064 case CORNER_S: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2065 case CORNER_E: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2066 case CORNER_N: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2067 default: NOT_REACHED();
2069 break;
2071 default: break;
2075 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2076 static const int INF = 1000; // big number compared to tilesprite size
2077 static const SubSprite _halftile_sub_sprite[4] = {
2078 { -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
2079 { -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
2080 { -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
2081 { -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2084 static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
2086 DrawGroundSprite(sprite, pal, nullptr, 0, (ti->tileh & s) ? -8 : 0);
2089 static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailtypeInfo *rti)
2091 RailGroundType rgt = GetRailGroundType(ti->tile);
2092 Foundation f = GetRailFoundation(ti->tileh, track);
2093 Corner halftile_corner = CORNER_INVALID;
2095 if (IsNonContinuousFoundation(f)) {
2096 /* Save halftile corner */
2097 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2098 /* Draw lower part first */
2099 track &= ~CornerToTrackBits(halftile_corner);
2100 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2103 DrawFoundation(ti, f);
2104 /* DrawFoundation modifies ti */
2106 /* Draw ground */
2107 if (rgt == RAIL_GROUND_WATER) {
2108 if (track != TRACK_BIT_NONE || IsSteepSlope(ti->tileh)) {
2109 /* three-corner-raised slope or steep slope with track on upper part */
2110 DrawShoreTile(ti->tileh);
2111 } else {
2112 /* single-corner-raised slope with track on upper part */
2113 DrawGroundSprite(SPR_FLAT_WATER_TILE, PAL_NONE);
2115 } else {
2116 SpriteID image;
2118 switch (rgt) {
2119 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2120 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2121 default: image = SPR_FLAT_GRASS_TILE; break;
2124 image += SlopeToSpriteOffset(ti->tileh);
2126 DrawGroundSprite(image, PAL_NONE);
2129 bool no_combine = ti->tileh == SLOPE_FLAT && HasBit(rti->flags, RTF_NO_SPRITE_COMBINE);
2130 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2131 SpriteID ground = GetCustomRailSprite(rti, ti->tile, no_combine ? RTSG_GROUND_COMPLETE : RTSG_GROUND);
2132 TrackBits pbs = _settings_client.gui.show_track_reservation ? GetRailReservationTrackBits(ti->tile) : TRACK_BIT_NONE;
2134 if (track == TRACK_BIT_NONE) {
2135 /* Half-tile foundation, no track here? */
2136 } else if (no_combine) {
2137 /* Use trackbits as direct index from ground sprite, subtract 1
2138 * because there is no sprite for no bits. */
2139 DrawGroundSprite(ground + track - 1, PAL_NONE);
2141 /* Draw reserved track bits */
2142 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2143 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2144 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2145 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2146 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2147 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2148 } else if (ti->tileh == SLOPE_NW && track == TRACK_BIT_Y) {
2149 DrawGroundSprite(ground + RTO_SLOPE_NW, PAL_NONE);
2150 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NW, PALETTE_CRASH);
2151 } else if (ti->tileh == SLOPE_NE && track == TRACK_BIT_X) {
2152 DrawGroundSprite(ground + RTO_SLOPE_NE, PAL_NONE);
2153 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NE, PALETTE_CRASH);
2154 } else if (ti->tileh == SLOPE_SE && track == TRACK_BIT_Y) {
2155 DrawGroundSprite(ground + RTO_SLOPE_SE, PAL_NONE);
2156 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SE, PALETTE_CRASH);
2157 } else if (ti->tileh == SLOPE_SW && track == TRACK_BIT_X) {
2158 DrawGroundSprite(ground + RTO_SLOPE_SW, PAL_NONE);
2159 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SW, PALETTE_CRASH);
2160 } else {
2161 switch (track) {
2162 /* Draw single ground sprite when not overlapping. No track overlay
2163 * is necessary for these sprites. */
2164 case TRACK_BIT_X: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2165 case TRACK_BIT_Y: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2166 case TRACK_BIT_UPPER: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N); break;
2167 case TRACK_BIT_LOWER: DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2168 case TRACK_BIT_RIGHT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E); break;
2169 case TRACK_BIT_LEFT: DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2170 case TRACK_BIT_CROSS: DrawGroundSprite(ground + RTO_CROSSING_XY, PAL_NONE); break;
2171 case TRACK_BIT_HORZ: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N);
2172 DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2173 case TRACK_BIT_VERT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E);
2174 DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2176 default:
2177 /* We're drawing a junction tile */
2178 if ((track & TRACK_BIT_3WAY_NE) == 0) {
2179 DrawGroundSprite(ground + RTO_JUNCTION_SW, PAL_NONE);
2180 } else if ((track & TRACK_BIT_3WAY_SW) == 0) {
2181 DrawGroundSprite(ground + RTO_JUNCTION_NE, PAL_NONE);
2182 } else if ((track & TRACK_BIT_3WAY_NW) == 0) {
2183 DrawGroundSprite(ground + RTO_JUNCTION_SE, PAL_NONE);
2184 } else if ((track & TRACK_BIT_3WAY_SE) == 0) {
2185 DrawGroundSprite(ground + RTO_JUNCTION_NW, PAL_NONE);
2186 } else {
2187 DrawGroundSprite(ground + RTO_JUNCTION_NSEW, PAL_NONE);
2190 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2191 track &= ~pbs;
2193 /* Draw regular track bits */
2194 if (track & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PAL_NONE);
2195 if (track & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PAL_NONE);
2196 if (track & TRACK_BIT_UPPER) DrawGroundSprite(overlay + RTO_N, PAL_NONE);
2197 if (track & TRACK_BIT_LOWER) DrawGroundSprite(overlay + RTO_S, PAL_NONE);
2198 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(overlay + RTO_E, PAL_NONE);
2199 if (track & TRACK_BIT_LEFT) DrawGroundSprite(overlay + RTO_W, PAL_NONE);
2202 /* Draw reserved track bits */
2203 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2204 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2205 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2206 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2207 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2208 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2211 if (IsValidCorner(halftile_corner)) {
2212 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2213 overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY, TCX_UPPER_HALFTILE);
2214 ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND, TCX_UPPER_HALFTILE);
2216 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2217 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2219 SpriteID image;
2220 switch (rgt) {
2221 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2222 case RAIL_GROUND_ICE_DESERT:
2223 case RAIL_GROUND_HALF_SNOW: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2224 default: image = SPR_FLAT_GRASS_TILE; break;
2227 image += SlopeToSpriteOffset(fake_slope);
2229 DrawGroundSprite(image, PAL_NONE, &(_halftile_sub_sprite[halftile_corner]));
2231 track = CornerToTrackBits(halftile_corner);
2233 int offset;
2234 switch (track) {
2235 default: NOT_REACHED();
2236 case TRACK_BIT_UPPER: offset = RTO_N; break;
2237 case TRACK_BIT_LOWER: offset = RTO_S; break;
2238 case TRACK_BIT_RIGHT: offset = RTO_E; break;
2239 case TRACK_BIT_LEFT: offset = RTO_W; break;
2242 DrawTrackSprite(ground + offset, PAL_NONE, ti, fake_slope);
2243 if (_settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, track)) {
2244 DrawTrackSprite(overlay + offset, PALETTE_CRASH, ti, fake_slope);
2250 * Draw ground sprite and track bits
2251 * @param ti TileInfo
2252 * @param track TrackBits to draw
2254 static void DrawTrackBits(TileInfo *ti, TrackBits track)
2256 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2258 if (rti->UsesOverlay()) {
2259 DrawTrackBitsOverlay(ti, track, rti);
2260 return;
2263 RailGroundType rgt = GetRailGroundType(ti->tile);
2264 Foundation f = GetRailFoundation(ti->tileh, track);
2265 Corner halftile_corner = CORNER_INVALID;
2267 if (IsNonContinuousFoundation(f)) {
2268 /* Save halftile corner */
2269 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2270 /* Draw lower part first */
2271 track &= ~CornerToTrackBits(halftile_corner);
2272 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2275 DrawFoundation(ti, f);
2276 /* DrawFoundation modifies ti */
2278 SpriteID image;
2279 PaletteID pal = PAL_NONE;
2280 const SubSprite *sub = nullptr;
2281 bool junction = false;
2283 /* Select the sprite to use. */
2284 if (track == 0) {
2285 /* Clear ground (only track on halftile foundation) */
2286 if (rgt == RAIL_GROUND_WATER) {
2287 if (IsSteepSlope(ti->tileh)) {
2288 DrawShoreTile(ti->tileh);
2289 image = 0;
2290 } else {
2291 image = SPR_FLAT_WATER_TILE;
2293 } else {
2294 switch (rgt) {
2295 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2296 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2297 default: image = SPR_FLAT_GRASS_TILE; break;
2299 image += SlopeToSpriteOffset(ti->tileh);
2301 } else {
2302 if (ti->tileh != SLOPE_FLAT) {
2303 /* track on non-flat ground */
2304 image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
2305 } else {
2306 /* track on flat ground */
2307 switch (track) {
2308 /* single track, select combined track + ground sprite*/
2309 case TRACK_BIT_Y: image = rti->base_sprites.track_y; break;
2310 case TRACK_BIT_X: image = rti->base_sprites.track_y + 1; break;
2311 case TRACK_BIT_UPPER: image = rti->base_sprites.track_y + 2; break;
2312 case TRACK_BIT_LOWER: image = rti->base_sprites.track_y + 3; break;
2313 case TRACK_BIT_RIGHT: image = rti->base_sprites.track_y + 4; break;
2314 case TRACK_BIT_LEFT: image = rti->base_sprites.track_y + 5; break;
2315 case TRACK_BIT_CROSS: image = rti->base_sprites.track_y + 6; break;
2317 /* double diagonal track, select combined track + ground sprite*/
2318 case TRACK_BIT_HORZ: image = rti->base_sprites.track_ns; break;
2319 case TRACK_BIT_VERT: image = rti->base_sprites.track_ns + 1; break;
2321 /* junction, select only ground sprite, handle track sprite later */
2322 default:
2323 junction = true;
2324 if ((track & TRACK_BIT_3WAY_NE) == 0) { image = rti->base_sprites.ground; break; }
2325 if ((track & TRACK_BIT_3WAY_SW) == 0) { image = rti->base_sprites.ground + 1; break; }
2326 if ((track & TRACK_BIT_3WAY_NW) == 0) { image = rti->base_sprites.ground + 2; break; }
2327 if ((track & TRACK_BIT_3WAY_SE) == 0) { image = rti->base_sprites.ground + 3; break; }
2328 image = rti->base_sprites.ground + 4;
2329 break;
2333 switch (rgt) {
2334 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2335 case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
2336 case RAIL_GROUND_WATER: {
2337 /* three-corner-raised slope */
2338 DrawShoreTile(ti->tileh);
2339 Corner track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2340 sub = &(_halftile_sub_sprite[track_corner]);
2341 break;
2343 default: break;
2347 if (image != 0) DrawGroundSprite(image, pal, sub);
2349 /* Draw track pieces individually for junction tiles */
2350 if (junction) {
2351 if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
2352 if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
2353 if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
2354 if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
2355 if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
2356 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
2359 /* PBS debugging, draw reserved tracks darker */
2360 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
2361 /* Get reservation, but mask track on halftile slope */
2362 TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
2363 if (pbs & TRACK_BIT_X) {
2364 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2365 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2366 } else {
2367 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2370 if (pbs & TRACK_BIT_Y) {
2371 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2372 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2373 } else {
2374 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2377 if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
2378 if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
2379 if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
2380 if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
2383 if (IsValidCorner(halftile_corner)) {
2384 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2386 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2387 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2388 image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
2389 pal = PAL_NONE;
2390 switch (rgt) {
2391 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2392 case RAIL_GROUND_ICE_DESERT:
2393 case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
2394 default: break;
2396 DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
2398 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
2399 static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
2400 DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, -(int)TILE_HEIGHT);
2405 static void DrawSignals(TileIndex tile, TrackBits rails, const RailtypeInfo *rti)
2407 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2409 if (!(rails & TRACK_BIT_Y)) {
2410 if (!(rails & TRACK_BIT_X)) {
2411 if (rails & TRACK_BIT_LEFT) {
2412 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
2413 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
2415 if (rails & TRACK_BIT_RIGHT) {
2416 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
2417 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
2419 if (rails & TRACK_BIT_UPPER) {
2420 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
2421 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
2423 if (rails & TRACK_BIT_LOWER) {
2424 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
2425 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
2427 } else {
2428 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
2429 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
2431 } else {
2432 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
2433 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
2437 static void DrawTile_Track(TileInfo *ti)
2439 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2441 _drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
2443 if (IsPlainRail(ti->tile)) {
2444 TrackBits rails = GetTrackBits(ti->tile);
2446 DrawTrackBits(ti, rails);
2448 if (HasBit(_display_opt, DO_FULL_DETAIL)) DrawTrackDetails(ti, rti);
2450 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2452 if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails, rti);
2453 } else {
2454 /* draw depot */
2455 const DrawTileSprites *dts;
2456 PaletteID pal = PAL_NONE;
2457 SpriteID relocation;
2459 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
2461 if (IsInvisibilitySet(TO_BUILDINGS)) {
2462 /* Draw rail instead of depot */
2463 dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
2464 } else {
2465 dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
2468 SpriteID image;
2469 if (rti->UsesOverlay()) {
2470 image = SPR_FLAT_GRASS_TILE;
2471 } else {
2472 image = dts->ground.sprite;
2473 if (image != SPR_FLAT_GRASS_TILE) image += rti->GetRailtypeSpriteOffset();
2476 /* Adjust ground tile for desert and snow. */
2477 if (IsSnowRailGround(ti->tile)) {
2478 if (image != SPR_FLAT_GRASS_TILE) {
2479 image += rti->snow_offset; // tile with tracks
2480 } else {
2481 image = SPR_FLAT_SNOW_DESERT_TILE; // flat ground
2485 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
2487 if (rti->UsesOverlay()) {
2488 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2490 switch (GetRailDepotDirection(ti->tile)) {
2491 case DIAGDIR_NE:
2492 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2493 FALLTHROUGH;
2494 case DIAGDIR_SW:
2495 DrawGroundSprite(ground + RTO_X, PAL_NONE);
2496 break;
2497 case DIAGDIR_NW:
2498 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2499 FALLTHROUGH;
2500 case DIAGDIR_SE:
2501 DrawGroundSprite(ground + RTO_Y, PAL_NONE);
2502 break;
2503 default:
2504 break;
2507 if (_settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2508 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2510 switch (GetRailDepotDirection(ti->tile)) {
2511 case DIAGDIR_NE:
2512 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2513 FALLTHROUGH;
2514 case DIAGDIR_SW:
2515 DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2516 break;
2517 case DIAGDIR_NW:
2518 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2519 FALLTHROUGH;
2520 case DIAGDIR_SE:
2521 DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2522 break;
2523 default:
2524 break;
2527 } else {
2528 /* PBS debugging, draw reserved tracks darker */
2529 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2530 switch (GetRailDepotDirection(ti->tile)) {
2531 case DIAGDIR_NE:
2532 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2533 FALLTHROUGH;
2534 case DIAGDIR_SW:
2535 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2536 break;
2537 case DIAGDIR_NW:
2538 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2539 FALLTHROUGH;
2540 case DIAGDIR_SE:
2541 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2542 break;
2543 default:
2544 break;
2548 int depot_sprite = GetCustomRailSprite(rti, ti->tile, RTSG_DEPOT);
2549 relocation = depot_sprite != 0 ? depot_sprite - SPR_RAIL_DEPOT_SE_1 : rti->GetRailtypeSpriteOffset();
2551 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2553 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, _drawtile_track_palette);
2555 DrawBridgeMiddle(ti);
2558 void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
2560 const DrawTileSprites *dts = &_depot_gfx_table[dir];
2561 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
2562 SpriteID image = rti->UsesOverlay() ? SPR_FLAT_GRASS_TILE : dts->ground.sprite;
2563 uint32 offset = rti->GetRailtypeSpriteOffset();
2565 if (image != SPR_FLAT_GRASS_TILE) image += offset;
2566 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
2568 DrawSprite(image, PAL_NONE, x, y);
2570 if (rti->UsesOverlay()) {
2571 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2573 switch (dir) {
2574 case DIAGDIR_SW: DrawSprite(ground + RTO_X, PAL_NONE, x, y); break;
2575 case DIAGDIR_SE: DrawSprite(ground + RTO_Y, PAL_NONE, x, y); break;
2576 default: break;
2579 int depot_sprite = GetCustomRailSprite(rti, INVALID_TILE, RTSG_DEPOT);
2580 if (depot_sprite != 0) offset = depot_sprite - SPR_RAIL_DEPOT_SE_1;
2582 DrawRailTileSeqInGUI(x, y, dts, offset, 0, palette);
2585 static int GetSlopePixelZ_Track(TileIndex tile, uint x, uint y)
2587 if (IsPlainRail(tile)) {
2588 int z;
2589 Slope tileh = GetTilePixelSlope(tile, &z);
2590 if (tileh == SLOPE_FLAT) return z;
2592 z += ApplyPixelFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
2593 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2594 } else {
2595 return GetTileMaxPixelZ(tile);
2599 static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
2601 return IsPlainRail(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
2604 static void TileLoop_Track(TileIndex tile)
2606 RailGroundType old_ground = GetRailGroundType(tile);
2607 RailGroundType new_ground;
2609 if (old_ground == RAIL_GROUND_WATER) {
2610 TileLoop_Water(tile);
2611 return;
2614 switch (_settings_game.game_creation.landscape) {
2615 case LT_ARCTIC: {
2616 int z;
2617 Slope slope = GetTileSlope(tile, &z);
2618 bool half = false;
2620 /* for non-flat track, use lower part of track
2621 * in other cases, use the highest part with track */
2622 if (IsPlainRail(tile)) {
2623 TrackBits track = GetTrackBits(tile);
2624 Foundation f = GetRailFoundation(slope, track);
2626 switch (f) {
2627 case FOUNDATION_NONE:
2628 /* no foundation - is the track on the upper side of three corners raised tile? */
2629 if (IsSlopeWithThreeCornersRaised(slope)) z++;
2630 break;
2632 case FOUNDATION_INCLINED_X:
2633 case FOUNDATION_INCLINED_Y:
2634 /* sloped track - is it on a steep slope? */
2635 if (IsSteepSlope(slope)) z++;
2636 break;
2638 case FOUNDATION_STEEP_LOWER:
2639 /* only lower part of steep slope */
2640 z++;
2641 break;
2643 default:
2644 /* if it is a steep slope, then there is a track on higher part */
2645 if (IsSteepSlope(slope)) z++;
2646 z++;
2647 break;
2650 half = IsInsideMM(f, FOUNDATION_STEEP_BOTH, FOUNDATION_HALFTILE_N + 1);
2651 } else {
2652 /* is the depot on a non-flat tile? */
2653 if (slope != SLOPE_FLAT) z++;
2656 /* 'z' is now the lowest part of the highest track bit -
2657 * for sloped track, it is 'z' of lower part
2658 * for two track bits, it is 'z' of higher track bit
2659 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2660 if (z > GetSnowLine()) {
2661 if (half && z - GetSnowLine() == 1) {
2662 /* track on non-continuous foundation, lower part is not under snow */
2663 new_ground = RAIL_GROUND_HALF_SNOW;
2664 } else {
2665 new_ground = RAIL_GROUND_ICE_DESERT;
2667 goto set_ground;
2669 break;
2672 case LT_TROPIC:
2673 if (GetTropicZone(tile) == TROPICZONE_DESERT) {
2674 new_ground = RAIL_GROUND_ICE_DESERT;
2675 goto set_ground;
2677 break;
2680 new_ground = RAIL_GROUND_GRASS;
2682 if (IsPlainRail(tile) && old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
2683 /* determine direction of fence */
2684 TrackBits rail = GetTrackBits(tile);
2686 Owner owner = GetTileOwner(tile);
2687 byte fences = 0;
2689 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
2690 static const TrackBits dir_to_trackbits[DIAGDIR_END] = {TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW};
2692 /* Track bit on this edge => no fence. */
2693 if ((rail & dir_to_trackbits[d]) != TRACK_BIT_NONE) continue;
2695 TileIndex tile2 = tile + TileOffsByDiagDir(d);
2697 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
2698 if (!IsValidTile(tile2) || IsTileType(tile2, MP_HOUSE) || IsTileType(tile2, MP_INDUSTRY) ||
2699 IsTileType(tile2, MP_ROAD) || (IsTileType(tile2, MP_OBJECT) && !IsObjectType(tile2, OBJECT_OWNED_LAND)) || IsTileType(tile2, MP_TUNNELBRIDGE) || !IsTileOwner(tile2, owner)) {
2700 fences |= 1 << d;
2704 switch (fences) {
2705 case 0: break;
2706 case (1 << DIAGDIR_NE): new_ground = RAIL_GROUND_FENCE_NE; break;
2707 case (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_SE; break;
2708 case (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_SW; break;
2709 case (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_NW; break;
2710 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_NESW; break;
2711 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_SENW; break;
2712 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_VERT1; break;
2713 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
2714 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
2715 case (1 << DIAGDIR_SW) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_VERT2; break;
2716 default: NOT_REACHED();
2720 set_ground:
2721 if (old_ground != new_ground) {
2722 SetRailGroundType(tile, new_ground);
2723 MarkTileDirtyByTile(tile);
2728 static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
2730 /* Case of half tile slope with water. */
2731 if (mode == TRANSPORT_WATER && IsPlainRail(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
2732 TrackBits tb = GetTrackBits(tile);
2733 switch (tb) {
2734 default: NOT_REACHED();
2735 case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
2736 case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
2737 case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
2738 case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
2740 return CombineTrackStatus(TrackBitsToTrackdirBits(tb), TRACKDIR_BIT_NONE);
2743 if (mode != TRANSPORT_RAIL) return 0;
2745 TrackBits trackbits = TRACK_BIT_NONE;
2746 TrackdirBits red_signals = TRACKDIR_BIT_NONE;
2748 switch (GetRailTileType(tile)) {
2749 default: NOT_REACHED();
2750 case RAIL_TILE_NORMAL:
2751 trackbits = GetTrackBits(tile);
2752 break;
2754 case RAIL_TILE_SIGNALS: {
2755 trackbits = GetTrackBits(tile);
2756 byte a = GetPresentSignals(tile);
2757 uint b = GetSignalStates(tile);
2759 b &= a;
2761 /* When signals are not present (in neither direction),
2762 * we pretend them to be green. Otherwise, it depends on
2763 * the signal type. For signals that are only active from
2764 * one side, we set the missing signals explicitly to
2765 * `green'. Otherwise, they implicitly become `red'. */
2766 if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
2767 if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
2769 if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
2770 if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
2771 if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
2772 if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
2774 break;
2777 case RAIL_TILE_DEPOT: {
2778 DiagDirection dir = GetRailDepotDirection(tile);
2780 if (side != INVALID_DIAGDIR && side != dir) break;
2782 trackbits = DiagDirToDiagTrackBits(dir);
2783 break;
2787 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
2790 static bool ClickTile_Track(TileIndex tile)
2792 if (!IsRailDepot(tile)) return false;
2794 ShowDepotWindow(tile, VEH_TRAIN);
2795 return true;
2798 static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
2800 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2801 td->rail_speed = rti->max_speed;
2802 td->railtype = rti->strings.name;
2803 td->owner[0] = GetTileOwner(tile);
2804 switch (GetRailTileType(tile)) {
2805 case RAIL_TILE_NORMAL:
2806 td->str = STR_LAI_RAIL_DESCRIPTION_TRACK;
2807 break;
2809 case RAIL_TILE_SIGNALS: {
2810 static const StringID signal_type[6][6] = {
2812 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS,
2813 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2814 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2815 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2816 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2817 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
2820 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2821 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS,
2822 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2823 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2824 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2825 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
2828 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2829 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2830 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS,
2831 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2832 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2833 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
2836 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2837 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2838 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2839 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS,
2840 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2841 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
2844 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2845 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2846 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2847 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2848 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS,
2849 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
2852 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
2853 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
2854 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
2855 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
2856 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
2857 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS
2861 SignalType primary_signal;
2862 SignalType secondary_signal;
2863 if (HasSignalOnTrack(tile, TRACK_UPPER)) {
2864 primary_signal = GetSignalType(tile, TRACK_UPPER);
2865 secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
2866 } else {
2867 secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
2870 td->str = signal_type[secondary_signal][primary_signal];
2871 break;
2874 case RAIL_TILE_DEPOT:
2875 td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
2876 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
2877 if (td->rail_speed > 0) {
2878 td->rail_speed = min(td->rail_speed, 61);
2879 } else {
2880 td->rail_speed = 61;
2883 td->build_date = Depot::GetByTile(tile)->build_date;
2884 break;
2886 default:
2887 NOT_REACHED();
2891 static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
2893 if (!IsTileOwner(tile, old_owner)) return;
2895 if (new_owner != INVALID_OWNER) {
2896 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2897 uint num_pieces = 1;
2898 if (IsPlainRail(tile)) {
2899 TrackBits bits = GetTrackBits(tile);
2900 num_pieces = CountBits(bits);
2901 if (TracksOverlap(bits)) num_pieces *= num_pieces;
2903 RailType rt = GetRailType(tile);
2904 Company::Get(old_owner)->infrastructure.rail[rt] -= num_pieces;
2905 Company::Get(new_owner)->infrastructure.rail[rt] += num_pieces;
2907 if (HasSignals(tile)) {
2908 uint num_sigs = CountBits(GetPresentSignals(tile));
2909 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2910 Company::Get(new_owner)->infrastructure.signal += num_sigs;
2913 SetTileOwner(tile, new_owner);
2914 } else {
2915 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2919 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
2920 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
2921 static const int8 _deltacoord_leaveoffset[8] = {
2922 -1, 0, 1, 0, /* x */
2923 0, 1, 0, -1 /* y */
2928 * Compute number of ticks when next wagon will leave a depot.
2929 * Negative means next wagon should have left depot n ticks before.
2930 * @param v vehicle outside (leaving) the depot
2931 * @return number of ticks when the next wagon will leave
2933 int TicksToLeaveDepot(const Train *v)
2935 DiagDirection dir = GetRailDepotDirection(v->tile);
2936 int length = v->CalcNextVehicleOffset();
2938 switch (dir) {
2939 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
2940 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
2941 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
2942 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
2943 default: NOT_REACHED();
2948 * Tile callback routine when vehicle enters tile
2949 * @see vehicle_enter_tile_proc
2951 static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int x, int y)
2953 /* This routine applies only to trains in depot tiles. */
2954 if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
2956 /* Depot direction. */
2957 DiagDirection dir = GetRailDepotDirection(tile);
2959 byte fract_coord = (x & 0xF) + ((y & 0xF) << 4);
2961 /* Make sure a train is not entering the tile from behind. */
2962 if (_fractcoords_behind[dir] == fract_coord) return VETSB_CANNOT_ENTER;
2964 Train *v = Train::From(u);
2966 /* Leaving depot? */
2967 if (v->direction == DiagDirToDir(dir)) {
2968 /* Calculate the point where the following wagon should be activated. */
2969 int length = v->CalcNextVehicleOffset();
2971 byte fract_coord_leave =
2972 ((_fractcoords_enter[dir] & 0x0F) + // x
2973 (length + 1) * _deltacoord_leaveoffset[dir]) +
2974 (((_fractcoords_enter[dir] >> 4) + // y
2975 ((length + 1) * _deltacoord_leaveoffset[dir + 4])) << 4);
2977 if (fract_coord_leave == fract_coord) {
2978 /* Leave the depot. */
2979 if ((v = v->Next()) != nullptr) {
2980 v->vehstatus &= ~VS_HIDDEN;
2981 v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
2984 } else if (_fractcoords_enter[dir] == fract_coord) {
2985 /* Entering depot. */
2986 assert(DiagDirToDir(ReverseDiagDir(dir)) == v->direction);
2987 v->track = TRACK_BIT_DEPOT,
2988 v->vehstatus |= VS_HIDDEN;
2989 v->direction = ReverseDir(v->direction);
2990 if (v->Next() == nullptr) VehicleEnterDepot(v->First());
2991 v->tile = tile;
2993 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2994 return VETSB_ENTERED_WORMHOLE;
2997 return VETSB_CONTINUE;
3001 * Tests if autoslope is allowed.
3003 * @param tile The tile.
3004 * @param flags Terraform command flags.
3005 * @param z_old Old TileZ.
3006 * @param tileh_old Old TileSlope.
3007 * @param z_new New TileZ.
3008 * @param tileh_new New TileSlope.
3009 * @param rail_bits Trackbits.
3011 static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old, Slope tileh_old, int z_new, Slope tileh_new, TrackBits rail_bits)
3013 if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3015 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
3016 if (CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3018 /* Get the slopes on top of the foundations */
3019 z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
3020 z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
3022 Corner track_corner;
3023 switch (rail_bits) {
3024 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
3025 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
3026 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
3027 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
3029 /* Surface slope must not be changed */
3030 default:
3031 if (z_old != z_new || tileh_old != tileh_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3032 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3035 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
3036 z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
3037 z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
3038 if (z_old != z_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3040 CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3041 /* Make the ground dirty, if surface slope has changed */
3042 if (tileh_old != tileh_new) {
3043 /* If there is flat water on the lower halftile add the cost for clearing it */
3044 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price[PR_CLEAR_WATER]);
3045 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3047 return cost;
3051 * Test-procedure for HasVehicleOnPos to check for a ship.
3053 static Vehicle *EnsureNoShipProc(Vehicle *v, void *data)
3055 return v->type == VEH_SHIP ? v : nullptr;
3058 static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3060 int z_old;
3061 Slope tileh_old = GetTileSlope(tile, &z_old);
3062 if (IsPlainRail(tile)) {
3063 TrackBits rail_bits = GetTrackBits(tile);
3064 /* Is there flat water on the lower halftile that must be cleared expensively? */
3065 bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
3067 /* Allow clearing the water only if there is no ship */
3068 if (was_water && HasVehicleOnPos(tile, nullptr, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
3070 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
3071 CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
3073 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
3074 Corner allowed_corner;
3075 switch (rail_bits) {
3076 case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
3077 case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
3078 case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
3079 case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
3080 default: return autoslope_result;
3083 Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
3085 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3086 if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
3088 /* Everything is valid, which only changes allowed_corner */
3089 for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
3090 if (allowed_corner == corner) continue;
3091 if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
3094 /* Make the ground dirty */
3095 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3097 /* allow terraforming */
3098 return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0);
3099 } else if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() &&
3100 AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) {
3101 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3103 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3107 extern const TileTypeProcs _tile_type_rail_procs = {
3108 DrawTile_Track, // draw_tile_proc
3109 GetSlopePixelZ_Track, // get_slope_z_proc
3110 ClearTile_Track, // clear_tile_proc
3111 nullptr, // add_accepted_cargo_proc
3112 GetTileDesc_Track, // get_tile_desc_proc
3113 GetTileTrackStatus_Track, // get_tile_track_status_proc
3114 ClickTile_Track, // click_tile_proc
3115 nullptr, // animate_tile_proc
3116 TileLoop_Track, // tile_loop_proc
3117 ChangeTileOwner_Track, // change_tile_owner_proc
3118 nullptr, // add_produced_cargo_proc
3119 VehicleEnter_Track, // vehicle_enter_tile_proc
3120 GetFoundation_Track, // get_foundation_proc
3121 TerraformTile_Track, // terraform_tile_proc