Add templated versions of CeilDiv and Ceil maths functions
[openttd-joker.git] / src / rail_cmd.cpp
blob61d62defa39f52fbc54d20d2b4a348e4228977ba
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file rail_cmd.cpp Handling of rail tiles. */
12 #include "stdafx.h"
13 #include "cmd_helper.h"
14 #include "viewport_func.h"
15 #include "command_func.h"
16 #include "depot_base.h"
17 #include "pathfinder/yapf/yapf_cache.h"
18 #include "newgrf_debug.h"
19 #include "newgrf_railtype.h"
20 #include "train.h"
21 #include "autoslope.h"
22 #include "water.h"
23 #include "tunnelbridge_map.h"
24 #include "bridge_signal_map.h"
25 #include "vehicle_func.h"
26 #include "sound_func.h"
27 #include "tunnelbridge.h"
28 #include "elrail_func.h"
29 #include "town.h"
30 #include "pbs.h"
31 #include "company_base.h"
32 #include "core/backup_type.hpp"
33 #include "date_func.h"
34 #include "strings_func.h"
35 #include "company_gui.h"
36 #include "object_map.h"
37 #include "tracerestrict.h"
38 #include "logic_signals.h"
39 #include "core/container_func.hpp"
41 #include "table/strings.h"
42 #include "table/railtypes.h"
43 #include "table/track_land.h"
45 #include "safeguards.h"
47 /** Helper type for lists/vectors of trains */
48 typedef SmallVector<Train *, 16> TrainList;
50 RailtypeInfo _railtypes[RAILTYPE_END];
51 TileIndex _rail_track_endtile; ///< The end of a rail track; as hidden return from the rail build/remove command for GUI purposes.
52 RailType _sorted_railtypes[RAILTYPE_END];
53 uint8 _sorted_railtypes_size;
55 /** Enum holding the signal offset in the sprite sheet according to the side it is representing. */
56 enum SignalOffsets {
57 SIGNAL_TO_SOUTHWEST,
58 SIGNAL_TO_NORTHEAST,
59 SIGNAL_TO_SOUTHEAST,
60 SIGNAL_TO_NORTHWEST,
61 SIGNAL_TO_EAST,
62 SIGNAL_TO_WEST,
63 SIGNAL_TO_SOUTH,
64 SIGNAL_TO_NORTH,
67 /**
68 * Reset all rail type information to its default values.
70 void ResetRailTypes()
72 assert_compile(lengthof(_original_railtypes) <= lengthof(_railtypes));
74 uint i = 0;
75 for (; i < lengthof(_original_railtypes); i++) _railtypes[i] = _original_railtypes[i];
77 static const RailtypeInfo empty_railtype = {
78 {0,0,0,0,0,0,0,0,0,0,0,0},
79 {0,0,0,0,0,0,0,0,{}},
80 {0,0,0,0,0,0,0,0},
81 {0,0,0,0,0,0},
82 0, RAILTYPES_NONE, RAILTYPES_NONE, 0, 0, 0, RTFB_NONE, 0, 0, 0, 0, 0,
83 RailTypeLabelList(), 0, 0, RAILTYPES_NONE, RAILTYPES_NONE, 0,
84 {}, {} };
85 for (; i < lengthof(_railtypes); i++) _railtypes[i] = empty_railtype;
88 void ResolveRailTypeGUISprites(RailtypeInfo *rti)
90 SpriteID cursors_base = GetCustomRailSprite(rti, INVALID_TILE, RTSG_CURSORS);
91 if (cursors_base != 0) {
92 rti->gui_sprites.build_ns_rail = cursors_base + 0;
93 rti->gui_sprites.build_x_rail = cursors_base + 1;
94 rti->gui_sprites.build_ew_rail = cursors_base + 2;
95 rti->gui_sprites.build_y_rail = cursors_base + 3;
96 rti->gui_sprites.auto_rail = cursors_base + 4;
97 rti->gui_sprites.build_depot = cursors_base + 5;
98 rti->gui_sprites.build_tunnel = cursors_base + 6;
99 rti->gui_sprites.convert_rail = cursors_base + 7;
100 rti->cursor.rail_ns = cursors_base + 8;
101 rti->cursor.rail_swne = cursors_base + 9;
102 rti->cursor.rail_ew = cursors_base + 10;
103 rti->cursor.rail_nwse = cursors_base + 11;
104 rti->cursor.autorail = cursors_base + 12;
105 rti->cursor.depot = cursors_base + 13;
106 rti->cursor.tunnel = cursors_base + 14;
107 rti->cursor.convert = cursors_base + 15;
110 /* Array of default GUI signal sprite numbers. */
111 /* Logic signals don't have their own sprites yet, lets use one-way pbs sprites for now */
112 const SpriteID _signal_lookup[2][SIGTYPE_END] = {
113 {SPR_IMG_SIGNAL_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_EXIT,
114 SPR_IMG_SIGNAL_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY,
115 SPR_IMG_SIGNAL_ELECTRIC_LOGIC},
117 {SPR_IMG_SIGNAL_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_EXIT,
118 SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY,
119 SPR_IMG_SIGNAL_SEMAPHORE_LOGIC},
122 for (SignalType type = SIGTYPE_NORMAL; type < SIGTYPE_END; type = (SignalType)(type + 1)) {
123 for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) {
124 SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true);
125 SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true);
126 rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type];
127 rti->gui_sprites.signals[type][var][1] = (green != 0) ? green + SIGNAL_TO_SOUTH : _signal_lookup[var][type] + 1;
133 * Compare railtypes based on their sorting order.
134 * @param first The railtype to compare to.
135 * @param second The railtype to compare.
136 * @return True iff the first should be sorted before the second.
138 static int CDECL CompareRailTypes(const RailType *first, const RailType *second)
140 return GetRailTypeInfo(*first)->sorting_order - GetRailTypeInfo(*second)->sorting_order;
144 * Resolve sprites of custom rail types
146 void InitRailTypes()
148 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
149 RailtypeInfo *rti = &_railtypes[rt];
150 ResolveRailTypeGUISprites(rti);
153 _sorted_railtypes_size = 0;
154 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
155 if (_railtypes[rt].label != 0) {
156 _sorted_railtypes[_sorted_railtypes_size++] = rt;
159 QSortT(_sorted_railtypes, _sorted_railtypes_size, CompareRailTypes);
163 * Allocate a new rail type label
165 RailType AllocateRailType(RailTypeLabel label)
167 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
168 RailtypeInfo *rti = &_railtypes[rt];
170 if (rti->label == 0) {
171 /* Set up new rail type */
172 *rti = _original_railtypes[RAILTYPE_RAIL];
173 rti->label = label;
174 rti->alternate_labels.Clear();
176 /* Make us compatible with ourself. */
177 rti->powered_railtypes = (RailTypes)(1 << rt);
178 rti->compatible_railtypes = (RailTypes)(1 << rt);
180 /* We also introduce ourself. */
181 rti->introduces_railtypes = (RailTypes)(1 << rt);
183 /* Default sort order; order of allocation, but with some
184 * offsets so it's easier for NewGRF to pick a spot without
185 * changing the order of other (original) rail types.
186 * The << is so you can place other railtypes in between the
187 * other railtypes, the 7 is to be able to place something
188 * before the first (default) rail type. */
189 rti->sorting_order = rt << 4 | 7;
190 return rt;
194 return INVALID_RAILTYPE;
197 static const byte _track_sloped_sprites[14] = {
198 14, 15, 22, 13,
199 0, 21, 17, 12,
200 23, 0, 18, 20,
201 19, 16
205 /* 4
206 * ---------
207 * |\ /|
208 * | \ 1/ |
209 * | \ / |
210 * | \ / |
211 * 16| \ |32
212 * | / \2 |
213 * | / \ |
214 * | / \ |
215 * |/ \|
216 * ---------
222 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
223 * MAP3LO byte: abcd???? => Signal Exists?
224 * a and b are for diagonals, upper and left,
225 * one for each direction. (ie a == NE->SW, b ==
226 * SW->NE, or v.v., I don't know. b and c are
227 * similar for lower and right.
228 * MAP2 byte: ????abcd => Type of ground.
229 * MAP3LO byte: ????abcd => Type of rail.
230 * MAP5: 00abcdef => rail
231 * 01abcdef => rail w/ signals
232 * 10uuuuuu => unused
233 * 11uuuudd => rail depot
237 * Tests if a vehicle interacts with the specified track.
238 * All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
240 * @param tile The tile.
241 * @param track The track.
242 * @return Succeeded command (no train found), or a failed command (a train was found).
244 static CommandCost EnsureNoTrainOnTrack(TileIndex tile, Track track)
246 TrackBits rail_bits = TrackToTrackBits(track);
247 return EnsureNoTrainOnTrackBits(tile, rail_bits);
251 * Check that the new track bits may be built.
252 * @param tile %Tile to build on.
253 * @param to_build New track bits.
254 * @param flags Flags of the operation.
255 * @return Succeeded or failed command.
257 static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
259 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
261 /* So, we have a tile with tracks on it (and possibly signals). Let's see
262 * what tracks first */
263 TrackBits current = GetTrackBits(tile); // The current track layout.
264 TrackBits future = current | to_build; // The track layout we want to build.
266 /* Are we really building something new? */
267 if (current == future) {
268 /* Nothing new is being built */
269 return_cmd_error(STR_ERROR_ALREADY_BUILT);
272 /* Let's see if we may build this */
273 if ((flags & DC_NO_RAIL_OVERLAP) || HasSignals(tile)) {
274 /* If we are not allowed to overlap (flag is on for ai companies or we have
275 * signals on the tile), check that */
276 if (future != TRACK_BIT_HORZ && future != TRACK_BIT_VERT) {
277 return_cmd_error((flags & DC_NO_RAIL_OVERLAP) ? STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION : STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
280 /* Normally, we may overlap and any combination is valid */
281 return CommandCost();
285 /** Valid TrackBits on a specific (non-steep)-slope without foundation */
286 static const TrackBits _valid_tracks_without_foundation[15] = {
287 TRACK_BIT_ALL,
288 TRACK_BIT_RIGHT,
289 TRACK_BIT_UPPER,
290 TRACK_BIT_X,
292 TRACK_BIT_LEFT,
293 TRACK_BIT_NONE,
294 TRACK_BIT_Y,
295 TRACK_BIT_LOWER,
297 TRACK_BIT_LOWER,
298 TRACK_BIT_Y,
299 TRACK_BIT_NONE,
300 TRACK_BIT_LEFT,
302 TRACK_BIT_X,
303 TRACK_BIT_UPPER,
304 TRACK_BIT_RIGHT,
307 /** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
308 static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
309 TRACK_BIT_NONE,
310 TRACK_BIT_LEFT,
311 TRACK_BIT_LOWER,
312 TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
314 TRACK_BIT_RIGHT,
315 TRACK_BIT_ALL,
316 TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
317 TRACK_BIT_ALL,
319 TRACK_BIT_UPPER,
320 TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
321 TRACK_BIT_ALL,
322 TRACK_BIT_ALL,
324 TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
325 TRACK_BIT_ALL,
326 TRACK_BIT_ALL
330 * Checks if a track combination is valid on a specific slope and returns the needed foundation.
332 * @param tileh Tile slope.
333 * @param bits Trackbits.
334 * @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
336 Foundation GetRailFoundation(Slope tileh, TrackBits bits)
338 if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
340 if (IsSteepSlope(tileh)) {
341 /* Test for inclined foundations */
342 if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
343 if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
345 /* Get higher track */
346 Corner highest_corner = GetHighestSlopeCorner(tileh);
347 TrackBits higher_track = CornerToTrackBits(highest_corner);
349 /* Only higher track? */
350 if (bits == higher_track) return HalftileFoundation(highest_corner);
352 /* Overlap with higher track? */
353 if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
355 /* either lower track or both higher and lower track */
356 return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
357 } else {
358 if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
360 bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
362 Corner track_corner;
363 switch (bits) {
364 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
365 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
366 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
367 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
369 case TRACK_BIT_HORZ:
370 if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
371 if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
372 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
374 case TRACK_BIT_VERT:
375 if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
376 if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
377 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
379 case TRACK_BIT_X:
380 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
381 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
383 case TRACK_BIT_Y:
384 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
385 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
387 default:
388 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
390 /* Single diagonal track */
392 /* Track must be at least valid on leveled foundation */
393 if (!valid_on_leveled) return FOUNDATION_INVALID;
395 /* If slope has three raised corners, build leveled foundation */
396 if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
398 /* If neighboured corners of track_corner are lowered, build halftile foundation */
399 if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
401 /* else special anti-zig-zag foundation */
402 return SpecialRailFoundation(track_corner);
408 * Tests if a track can be build on a tile.
410 * @param tileh Tile slope.
411 * @param rail_bits Tracks to build.
412 * @param existing Tracks already built.
413 * @param tile Tile (used for water test)
414 * @return Error message or cost for foundation building.
416 static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
418 /* don't allow building on the lower side of a coast */
419 if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
420 if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
423 Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
425 /* check track/slope combination */
426 if ((f_new == FOUNDATION_INVALID) ||
427 ((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
428 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
431 Foundation f_old = GetRailFoundation(tileh, existing);
432 return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
435 /* Validate functions for rail building */
436 static inline bool ValParamTrackOrientation(Track track)
438 return IsValidTrack(track);
442 * Build a single piece of rail
443 * @param tile tile to build on
444 * @param flags operation to perform
445 * @param p1 railtype of being built piece (normal, mono, maglev)
446 * @param p2 rail track to build
447 * @param text unused
448 * @return the cost of this operation or an error
450 CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
452 RailType railtype = Extract<RailType, 0, 5>(p1);
453 Track track = Extract<Track, 0, 3>(p2);
454 CommandCost cost(EXPENSES_CONSTRUCTION);
456 _rail_track_endtile = INVALID_TILE;
458 if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
460 Slope tileh = GetTileSlope(tile);
461 TrackBits trackbit = TrackToTrackBits(track);
463 switch (GetTileType(tile)) {
464 case MP_RAILWAY: {
465 CommandCost ret = CheckTileOwnership(tile);
466 if (ret.Failed()) return ret;
468 if (!IsPlainRail(tile)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); // just get appropriate error message
470 if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
472 ret = CheckTrackCombination(tile, trackbit, flags);
473 if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
474 if (ret.Failed()) {
475 if (ret.GetErrorMessage() == STR_ERROR_ALREADY_BUILT) _rail_track_endtile = tile;
476 return ret;
479 ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
480 if (ret.Failed()) return ret;
481 cost.AddCost(ret);
483 /* If the rail types don't match, try to convert only if engines of
484 * the new rail type are not powered on the present rail type and engines of
485 * the present rail type are powered on the new rail type. */
486 if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
487 if (HasPowerOnRail(GetRailType(tile), railtype)) {
488 ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
489 if (ret.Failed()) return ret;
490 cost.AddCost(ret);
491 } else {
492 return CMD_ERROR;
496 if (flags & DC_EXEC) {
497 SetRailGroundType(tile, RAIL_GROUND_BARREN);
498 TrackBits bits = GetTrackBits(tile);
499 SetTrackBits(tile, bits | trackbit);
500 ResetRailAge(tile);
501 /* Subtract old infrastructure count. */
502 uint pieces = CountBits(bits);
503 if (TracksOverlap(bits)) pieces *= pieces;
504 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
505 /* Add new infrastructure count. */
506 pieces = CountBits(bits | trackbit);
507 if (TracksOverlap(bits | trackbit)) pieces *= pieces;
508 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
509 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
511 break;
514 case MP_ROAD: {
515 /* Level crossings may only be built on these slopes */
516 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
518 CommandCost ret = EnsureNoVehicleOnGround(tile);
519 if (ret.Failed()) return ret;
521 if (IsNormalRoad(tile)) {
522 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
524 if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
526 if (RailNoLevelCrossings(railtype)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
528 RoadTypes roadtypes = GetRoadTypes(tile);
529 RoadBits road = GetRoadBits(tile, ROADTYPE_ROAD);
530 RoadBits tram = GetRoadBits(tile, ROADTYPE_TRAM);
531 if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
532 (track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
533 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
534 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
535 /* Disallow breaking end-of-line of someone else
536 * so trams can still reverse on this tile. */
537 if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
538 CommandCost ret = CheckOwnership(tram_owner);
539 if (ret.Failed()) return ret;
541 /* Crossings must always have a road... */
542 uint num_new_road_pieces = 2 - CountBits(road);
543 if (road == ROAD_NONE) road_owner = _current_company;
544 roadtypes |= ROADTYPES_ROAD;
545 /* ...but tram is not required. */
546 uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
548 cost.AddCost((num_new_road_pieces + num_new_tram_pieces) * _price[PR_BUILD_ROAD]);
550 if (flags & DC_EXEC) {
551 MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtypes, GetTownIndex(tile));
552 UpdateLevelCrossing(tile, false);
553 Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
554 DirtyCompanyInfrastructureWindows(_current_company);
555 if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
556 Company::Get(road_owner)->infrastructure.road[ROADTYPE_ROAD] += num_new_road_pieces;
557 DirtyCompanyInfrastructureWindows(road_owner);
559 if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
560 Company::Get(tram_owner)->infrastructure.road[ROADTYPE_TRAM] += num_new_tram_pieces;
561 DirtyCompanyInfrastructureWindows(tram_owner);
564 break;
568 if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
569 _rail_track_endtile = tile;
570 return_cmd_error(STR_ERROR_ALREADY_BUILT);
573 FALLTHROUGH;
575 default: {
576 /* Will there be flat water on the lower halftile? */
577 bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
579 CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
580 if (ret.Failed()) return ret;
581 cost.AddCost(ret);
583 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
584 if (ret.Failed()) return ret;
585 cost.AddCost(ret);
587 if (water_ground) {
588 cost.AddCost(-_price[PR_CLEAR_WATER]);
589 cost.AddCost(_price[PR_CLEAR_ROUGH]);
592 if (flags & DC_EXEC) {
593 MakeRailNormal(tile, _current_company, trackbit, railtype);
594 if (water_ground) SetRailGroundType(tile, RAIL_GROUND_WATER);
595 Company::Get(_current_company)->infrastructure.rail[railtype]++;
596 DirtyCompanyInfrastructureWindows(_current_company);
598 break;
602 if (flags & DC_EXEC) {
603 MarkTileDirtyByTile(tile);
604 AddTrackToSignalBuffer(tile, track, _current_company);
605 YapfNotifyTrackLayoutChange(tile, track);
608 cost.AddCost(RailBuildCost(railtype));
609 _rail_track_endtile = tile;
610 return cost;
614 * Remove a single piece of track
615 * @param tile tile to remove track from
616 * @param flags operation to perform
617 * @param p1 unused
618 * @param p2 rail orientation
619 * @param text unused
620 * @return the cost of this operation or an error
622 CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
624 Track track = Extract<Track, 0, 3>(p2);
625 CommandCost cost(EXPENSES_CONSTRUCTION);
626 bool crossing = false;
628 _rail_track_endtile = INVALID_TILE;
630 if (!ValParamTrackOrientation(track)) return CMD_ERROR;
631 TrackBits trackbit = TrackToTrackBits(track);
633 /* Need to read tile owner now because it may change when the rail is removed
634 * Also, in case of floods, _current_company != owner
635 * There may be invalid tiletype even in exec run (when removing long track),
636 * so do not call GetTileOwner(tile) in any case here */
637 Owner owner = INVALID_OWNER;
639 Train *v = NULL;
641 switch (GetTileType(tile)) {
642 case MP_ROAD: {
643 if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
645 if (_current_company != OWNER_WATER) {
646 CommandCost ret = CheckTileOwnership(tile);
647 if (ret.Failed()) return ret;
650 if (!(flags & DC_BANKRUPT)) {
651 CommandCost ret = EnsureNoVehicleOnGround(tile);
652 if (ret.Failed()) return ret;
655 cost.AddCost(RailClearCost(GetRailType(tile)));
657 if (flags & DC_EXEC) {
658 if (HasReservedTracks(tile, trackbit)) {
659 v = GetTrainForReservation(tile, track);
660 if (v != NULL) FreeTrainTrackReservation(v);
662 owner = GetTileOwner(tile);
663 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
664 DirtyCompanyInfrastructureWindows(owner);
665 MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypes(tile), GetTownIndex(tile), GetRoadOwner(tile, ROADTYPE_ROAD), GetRoadOwner(tile, ROADTYPE_TRAM));
666 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
668 break;
671 case MP_RAILWAY: {
672 TrackBits present;
673 /* There are no rails present at depots. */
674 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
676 if (_current_company != OWNER_WATER) {
677 CommandCost ret = CheckTileOwnership(tile);
678 if (ret.Failed()) return ret;
681 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
682 if (ret.Failed()) return ret;
684 present = GetTrackBits(tile);
685 if ((present & trackbit) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
686 if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
688 cost.AddCost(RailClearCost(GetRailType(tile)));
690 /* Charge extra to remove signals on the track, if they are there */
691 if (HasSignalOnTrack(tile, track)) {
692 cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
695 if (flags & DC_EXEC) {
696 if (HasReservedTracks(tile, trackbit)) {
697 v = GetTrainForReservation(tile, track);
698 if (v != NULL) FreeTrainTrackReservation(v);
701 owner = GetTileOwner(tile);
703 /* Subtract old infrastructure count. */
704 uint pieces = CountBits(present);
705 if (TracksOverlap(present)) pieces *= pieces;
706 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
707 /* Add new infrastructure count. */
708 present ^= trackbit;
709 pieces = CountBits(present);
710 if (TracksOverlap(present)) pieces *= pieces;
711 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
712 DirtyCompanyInfrastructureWindows(owner);
714 if (present == 0) {
715 Slope tileh = GetTileSlope(tile);
716 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
717 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
718 MakeShore(tile);
719 } else {
720 DoClearSquare(tile);
722 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
723 } else {
724 SetTrackBits(tile, present);
725 SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
728 break;
731 default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
734 if (flags & DC_EXEC) {
735 /* if we got that far, 'owner' variable is set correctly */
736 assert(Company::IsValidID(owner));
738 MarkTileDirtyByTile(tile);
739 if (crossing) {
740 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
741 * are removing one of these pieces, we'll need to update signals for
742 * both directions explicitly, as after the track is removed it won't
743 * 'connect' with the other piece. */
744 AddTrackToSignalBuffer(tile, TRACK_X, owner);
745 AddTrackToSignalBuffer(tile, TRACK_Y, owner);
746 YapfNotifyTrackLayoutChange(tile, TRACK_X);
747 YapfNotifyTrackLayoutChange(tile, TRACK_Y);
748 } else {
749 AddTrackToSignalBuffer(tile, track, owner);
750 YapfNotifyTrackLayoutChange(tile, track);
753 if (v != NULL) TryPathReserve(v, true);
756 _rail_track_endtile = tile;
757 return cost;
762 * Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
763 * The function floods the lower halftile, if the tile has a halftile foundation.
765 * @param t The tile to flood.
766 * @return true if something was flooded.
768 bool FloodHalftile(TileIndex t)
770 assert(IsPlainRailTile(t));
772 bool flooded = false;
773 if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
775 Slope tileh = GetTileSlope(t);
776 TrackBits rail_bits = GetTrackBits(t);
778 if (IsSlopeWithOneCornerRaised(tileh)) {
779 TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
781 TrackBits to_remove = lower_track & rail_bits;
782 if (to_remove != 0) {
783 Backup<CompanyByte> cur_company(_current_company, OWNER_WATER, FILE_LINE);
784 flooded = DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL).Succeeded();
785 cur_company.Restore();
786 if (!flooded) return flooded; // not yet floodable
787 rail_bits = rail_bits & ~to_remove;
788 if (rail_bits == 0) {
789 MakeShore(t);
790 MarkTileDirtyByTile(t);
791 return flooded;
795 if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
796 flooded = true;
797 SetRailGroundType(t, RAIL_GROUND_WATER);
798 MarkTileDirtyByTile(t);
800 } else {
801 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
802 if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
803 if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
804 flooded = true;
805 SetRailGroundType(t, RAIL_GROUND_WATER);
806 MarkTileDirtyByTile(t);
810 return flooded;
813 static const TileIndexDiffC _trackdelta[] = {
814 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
815 { 0, 0 },
816 { 0, 0 },
817 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
818 { 0, 0 },
819 { 0, 0 }
823 static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
825 int x = TileX(start);
826 int y = TileY(start);
827 int ex = TileX(end);
828 int ey = TileY(end);
830 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
832 /* calculate delta x,y from start to end tile */
833 int dx = ex - x;
834 int dy = ey - y;
836 /* calculate delta x,y for the first direction */
837 int trdx = _trackdelta[*trackdir].x;
838 int trdy = _trackdelta[*trackdir].y;
840 if (!IsDiagonalTrackdir(*trackdir)) {
841 trdx += _trackdelta[*trackdir ^ 1].x;
842 trdy += _trackdelta[*trackdir ^ 1].y;
845 /* validate the direction */
846 while ((trdx <= 0 && dx > 0) ||
847 (trdx >= 0 && dx < 0) ||
848 (trdy <= 0 && dy > 0) ||
849 (trdy >= 0 && dy < 0)) {
850 if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
851 SetBit(*trackdir, 3); // reverse the direction
852 trdx = -trdx;
853 trdy = -trdy;
854 } else { // other direction is invalid too, invalid drag
855 return CMD_ERROR;
859 /* (for diagonal tracks, this is already made sure of by above test), but:
860 * for non-diagonal tracks, check if the start and end tile are on 1 line */
861 if (!IsDiagonalTrackdir(*trackdir)) {
862 trdx = _trackdelta[*trackdir].x;
863 trdy = _trackdelta[*trackdir].y;
864 if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CMD_ERROR;
867 return CommandCost();
871 * Build or remove a stretch of railroad tracks.
872 * @param tile start tile of drag
873 * @param flags operation to perform
874 * @param p1 end tile of drag
875 * @param p2 various bitstuffed elements
876 * - p2 = (bit 0-4) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
877 * - p2 = (bit 5-7) - track-orientation, valid values: 0-5 (Track enum)
878 * - p2 = (bit 8) - 0 = build, 1 = remove tracks
879 * - p2 = (bit 9) - 0 = build up to an obstacle, 1 = fail if an obstacle is found (used for AIs).
880 * @param text unused
881 * @return the cost of this operation or an error
883 static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
885 CommandCost total_cost(EXPENSES_CONSTRUCTION);
886 RailType railtype = Extract<RailType, 0, 5>(p2);
887 Track track = Extract<Track, 5, 3>(p2);
888 bool remove = HasBit(p2, 8);
889 bool fail_if_obstacle = HasBit(p2, 9);
891 _rail_track_endtile = INVALID_TILE;
893 if ((!remove && !ValParamRailtype(railtype)) || !ValParamTrackOrientation(track)) return CMD_ERROR;
894 if (p1 >= MapSize()) return CMD_ERROR;
895 TileIndex end_tile = p1;
896 Trackdir trackdir = TrackToTrackdir(track);
898 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
899 if (ret.Failed()) return ret;
901 bool had_success = false;
902 CommandCost last_error = CMD_ERROR;
903 for (;;) {
904 TileIndex last_endtile = _rail_track_endtile;
905 CommandCost ret = DoCommand(tile, remove ? 0 : railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
907 if (ret.Failed()) {
908 last_error = ret;
909 if (_rail_track_endtile == INVALID_TILE) _rail_track_endtile = last_endtile;
910 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
911 if (fail_if_obstacle) return last_error;
912 break;
915 /* Ownership errors are more important. */
916 if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
917 } else {
918 had_success = true;
919 total_cost.AddCost(ret);
922 if (tile == end_tile) break;
924 tile += ToTileIndexDiff(_trackdelta[trackdir]);
926 /* toggle railbit for the non-diagonal tracks */
927 if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
930 if (had_success) return total_cost;
931 return last_error;
935 * Build rail on a stretch of track.
936 * Stub for the unified rail builder/remover
937 * @param tile start tile of drag
938 * @param flags operation to perform
939 * @param p1 end tile of drag
940 * @param p2 various bitstuffed elements
941 * - p2 = (bit 0-4) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
942 * - p2 = (bit 5-7) - track-orientation, valid values: 0-5 (Track enum)
943 * - p2 = (bit 8) - 0 = build, 1 = remove tracks
944 * @param text unused
945 * @return the cost of this operation or an error
946 * @see CmdRailTrackHelper
948 CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
950 return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 8), text);
954 * Build rail on a stretch of track.
955 * Stub for the unified rail builder/remover
956 * @param tile start tile of drag
957 * @param flags operation to perform
958 * @param p1 end tile of drag
959 * @param p2 various bitstuffed elements
960 * - p2 = (bit 0-4) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
961 * - p2 = (bit 5-7) - track-orientation, valid values: 0-5 (Track enum)
962 * - p2 = (bit 8) - 0 = build, 1 = remove tracks
963 * @param text unused
964 * @return the cost of this operation or an error
965 * @see CmdRailTrackHelper
967 CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
969 return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 8), text);
973 * Build a train depot
974 * @param tile position of the train depot
975 * @param flags operation to perform
976 * @param p1 rail type
977 * @param p2 bit 0..1 entrance direction (DiagDirection)
978 * @param text unused
979 * @return the cost of this operation or an error
981 * @todo When checking for the tile slope,
982 * distinguish between "Flat land required" and "land sloped in wrong direction"
984 CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
986 /* check railtype and valid direction for depot (0 through 3), 4 in total */
987 RailType railtype = Extract<RailType, 0, 5>(p1);
988 if (!ValParamRailtype(railtype)) return CMD_ERROR;
990 Slope tileh = GetTileSlope(tile);
992 DiagDirection dir = Extract<DiagDirection, 0, 2>(p2);
994 /* Prohibit construction if
995 * The tile is non-flat AND
996 * 1) build-on-slopes is disabled
997 * 2) the tile is steep i.e. spans two height levels
998 * 3) the exit points in the wrong direction
1001 if (tileh != SLOPE_FLAT && (
1002 !_settings_game.construction.build_on_slopes ||
1003 !CanBuildDepotByTileh(dir, tileh)
1004 )) {
1005 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
1008 CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1009 if (cost.Failed()) return cost;
1011 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1013 if (!Depot::CanAllocateItem()) return CMD_ERROR;
1015 if (flags & DC_EXEC) {
1016 Depot *d = new Depot(tile);
1017 d->build_date = _date;
1019 MakeRailDepot(tile, _current_company, d->index, dir, railtype);
1020 MarkTileDirtyByTile(tile);
1021 MakeDefaultName(d);
1023 Company::Get(_current_company)->infrastructure.rail[railtype]++;
1024 DirtyCompanyInfrastructureWindows(_current_company);
1026 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, _current_company);
1027 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1030 cost.AddCost(_price[PR_BUILD_DEPOT_TRAIN]);
1031 cost.AddCost(RailBuildCost(railtype));
1032 return cost;
1035 static void ClearBridgeTunnelSignalSimulation(TileIndex entrance, TileIndex exit)
1037 if (IsBridge(entrance)) ClearBridgeEntranceSimulatedSignals(entrance);
1038 ClrTunnelBridgeSignalSimulationEntrance(entrance);
1039 ClrTunnelBridgeSignalSimulationExit(exit);
1042 static void SetupBridgeTunnelSignalSimulation(TileIndex entrance, TileIndex exit)
1044 SetTunnelBridgeSignalSimulationEntrance(entrance);
1045 SetTunnelBridgeSignalState(entrance, SIGNAL_STATE_GREEN);
1046 SetTunnelBridgeSignalSimulationExit(exit);
1050 * Build signals, alternate between double/single, signal/semaphore,
1051 * pre/exit/combo-signals, and what-else not. If the rail piece does not
1052 * have any signals, bit 4 (cycle signal-type) is ignored
1053 * @param tile tile where to build the signals
1054 * @param flags operation to perform
1055 * @param p1 various bitstuffed elements
1056 * - p1 = (bit 0-2) - track-orientation, valid values: 0-5 (Track enum)
1057 * - p1 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal or (for bit 7) toggle variant (CTRL-toggle)
1058 * - p1 = (bit 4) - 0 = signals, 1 = semaphores
1059 * - p1 = (bit 5-7) - type of the signal, for valid values see enum SignalType in rail_map.h
1060 * - p1 = (bit 8) - convert the present signal type and variant
1061 * - p1 = (bit 9-11)- start cycle from this signal type
1062 * - p1 = (bit 12-14)-wrap around after this signal type
1063 * - p1 = (bit 15-16)-cycle the signal direction this many times
1064 * - p1 = (bit 17) - 1 = don't modify an existing signal but don't fail either, 0 = always set new signal type
1065 * @param p2 used for CmdBuildManySignals() to copy direction of first signal
1066 * @param text unused
1067 * @return the cost of this operation or an error
1068 * @todo p2 should be replaced by two bits for "along" and "against" the track.
1070 CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1072 Track track = Extract<Track, 0, 3>(p1);
1073 bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed
1074 SignalVariant sigvar = (ctrl_pressed ^ HasBit(p1, 4)) ? SIG_SEMAPHORE : SIG_ELECTRIC; // the signal variant of the new signal
1075 SignalType sigtype = Extract<SignalType, 5, 3>(p1); // the signal type of the new signal
1076 bool convert_signal = HasBit(p1, 8); // convert button pressed
1077 SignalType cycle_start = Extract<SignalType, 9, 3>(p1);
1078 SignalType cycle_stop = Extract<SignalType, 12, 3>(p1);
1079 uint num_dir_cycle = GB(p1, 15, 2);
1081 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1082 if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CMD_ERROR;
1084 /* You can only build signals on plain rail tiles or tunnel/bridges, and the selected track must exist */
1085 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1086 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return CMD_ERROR;
1087 CommandCost ret = EnsureNoTrainOnTrack(GetOtherTunnelBridgeEnd(tile), track);
1088 if (ret.Failed()) return ret;
1089 ret = EnsureNoTrainOnTrack(tile, track);
1090 if (ret.Failed()) return ret;
1091 } else if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1092 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1094 /* Protect against invalid signal copying */
1095 if (p2 != 0 && (p2 & SignalOnTrack(track)) == 0) return CMD_ERROR;
1097 CommandCost ret = CheckTileOwnership(tile);
1098 if (ret.Failed()) return ret;
1100 CommandCost cost;
1101 /* handle signals simulation on tunnel/bridge. */
1102 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1103 TileIndex tile_exit = GetOtherTunnelBridgeEnd(tile);
1104 cost = CommandCost();
1105 bool flip_variant = false;
1106 bool is_pbs = (sigtype == SIGTYPE_PBS) || (sigtype == SIGTYPE_PBS_ONEWAY);
1107 if (!IsTunnelBridgeWithSignalSimulation(tile)) { // toggle signal zero costs.
1108 if (convert_signal) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1109 if (p2 != 12) cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] * ((GetTunnelBridgeLength(tile, tile_exit) + 4) >> 2)); // minimal 1
1110 } else {
1111 if (HasBit(p1, 17)) return CommandCost();
1112 if ((p2 != 0 && (sigvar == SIG_SEMAPHORE) != IsTunnelBridgeSemaphore(tile)) ||
1113 (convert_signal && (ctrl_pressed || (sigvar == SIG_SEMAPHORE) != IsTunnelBridgeSemaphore(tile)))) {
1114 flip_variant = true;
1115 cost = CommandCost(EXPENSES_CONSTRUCTION, (_price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]) *
1116 ((GetTunnelBridgeLength(tile, tile_exit) + 4) >> 2)); // minimal 1
1119 if (flags & DC_EXEC) {
1120 Company * const c = Company::Get(GetTileOwner(tile));
1121 if (IsTunnelBridgeWithSignalSimulation(tile)) c->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, tile_exit);
1122 if (p2 == 0 && IsTunnelBridgeWithSignalSimulation(tile)) { // Toggle signal if already signals present.
1123 if (convert_signal) {
1124 if (flip_variant) {
1125 SetTunnelBridgeSemaphore(tile, !IsTunnelBridgeSemaphore(tile));
1126 SetTunnelBridgeSemaphore(tile_exit, IsTunnelBridgeSemaphore(tile));
1128 if (!ctrl_pressed) {
1129 SetTunnelBridgePBS(tile, is_pbs);
1130 SetTunnelBridgePBS(tile_exit, is_pbs);
1132 } else if (ctrl_pressed) {
1133 SetTunnelBridgePBS(tile, !IsTunnelBridgePBS(tile));
1134 SetTunnelBridgePBS(tile_exit, IsTunnelBridgePBS(tile));
1135 } else {
1136 if (IsTunnelBridgeSignalSimulationEntrance(tile)) {
1137 ClearBridgeTunnelSignalSimulation(tile, tile_exit);
1138 SetupBridgeTunnelSignalSimulation(tile_exit, tile);
1139 } else {
1140 ClearBridgeTunnelSignalSimulation(tile_exit, tile);
1141 SetupBridgeTunnelSignalSimulation(tile, tile_exit);
1144 } else {
1145 /* Create one direction tunnel/bridge if required. */
1146 if (p2 == 0) {
1147 SetupBridgeTunnelSignalSimulation(tile, tile_exit);
1148 } else if (p2 == 4 || p2 == 8) {
1149 DiagDirection tbdir = GetTunnelBridgeDirection(tile);
1150 /* If signal only on one side build accordingly one-way tunnel/bridge. */
1151 if ((p2 == 8 && (tbdir == DIAGDIR_NE || tbdir == DIAGDIR_SE)) ||
1152 (p2 == 4 && (tbdir == DIAGDIR_SW || tbdir == DIAGDIR_NW))) {
1153 ClearBridgeTunnelSignalSimulation(tile_exit, tile);
1154 SetupBridgeTunnelSignalSimulation(tile, tile_exit);
1155 } else {
1156 ClearBridgeTunnelSignalSimulation(tile, tile_exit);
1157 SetupBridgeTunnelSignalSimulation(tile_exit, tile);
1161 if (p2 == 0 || p2 == 4 || p2 == 8) {
1162 SetTunnelBridgeSemaphore(tile, sigvar == SIG_SEMAPHORE);
1163 SetTunnelBridgeSemaphore(tile_exit, sigvar == SIG_SEMAPHORE);
1164 SetTunnelBridgePBS(tile, is_pbs);
1165 SetTunnelBridgePBS(tile_exit, is_pbs);
1169 if (IsTunnelBridgeSignalSimulationExit(tile) && IsTunnelBridgePBS(tile) && !HasTunnelBridgeReservation(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_RED);
1170 if (IsTunnelBridgeSignalSimulationExit(tile_exit) && IsTunnelBridgePBS(tile_exit) && !HasTunnelBridgeReservation(tile_exit)) SetTunnelBridgeSignalState(tile_exit, SIGNAL_STATE_RED);
1172 MarkBridgeOrTunnelDirty(tile);
1173 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, GetTileOwner(tile));
1174 AddSideToSignalBuffer(tile_exit, INVALID_DIAGDIR, GetTileOwner(tile));
1175 YapfNotifyTrackLayoutChange(tile, track);
1176 YapfNotifyTrackLayoutChange(tile_exit, track);
1177 if (IsTunnelBridgeWithSignalSimulation(tile)) c->infrastructure.signal += GetTunnelBridgeSignalSimulationSignalCount(tile, tile_exit);
1178 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1180 return cost;
1183 /* See if this is a valid track combination for signals (no overlap) */
1184 if (TracksOverlap(GetTrackBits(tile))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
1186 /* In case we don't want to change an existing signal, return without error. */
1187 if (HasBit(p1, 17) && HasSignalOnTrack(tile, track)) return CommandCost();
1189 /* you can not convert a signal if no signal is on track */
1190 if (convert_signal && !HasSignalOnTrack(tile, track)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1192 if (!HasSignalOnTrack(tile, track)) {
1193 /* build new signals */
1194 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS]);
1195 } else {
1196 if (p2 != 0 && sigvar != GetSignalVariant(tile, track)) {
1197 /* convert signals <-> semaphores */
1198 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1200 } else if (convert_signal) {
1201 /* convert button pressed */
1202 if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
1203 /* convert electric <-> semaphore */
1204 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1205 } else {
1206 /* it is free to change signal type: normal-pre-exit-combo */
1207 cost = CommandCost();
1210 } else {
1211 /* it is free to change orientation/pre-exit-combo signals */
1212 cost = CommandCost();
1216 if (flags & DC_EXEC) {
1217 Train *v = NULL;
1218 /* The new/changed signal could block our path. As this can lead to
1219 * stale reservations, we clear the path reservation here and try
1220 * to redo it later on. */
1221 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1222 v = GetTrainForReservation(tile, track);
1223 if (v != NULL) FreeTrainTrackReservation(v);
1226 if (!HasSignals(tile)) {
1227 /* there are no signals at all on this tile yet */
1228 SetHasSignals(tile, true);
1229 SetSignalStates(tile, 0xF); // all signals are on
1230 SetPresentSignals(tile, 0); // no signals built by default
1231 SetSignalType(tile, track, sigtype);
1232 SetSignalVariant(tile, track, sigvar);
1235 /* Subtract old signal infrastructure count. */
1236 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1238 if (p2 == 0) {
1239 if (!HasSignalOnTrack(tile, track)) {
1240 /* build new signals */
1241 SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsOrLogicSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
1242 SetSignalType(tile, track, sigtype);
1243 SetSignalVariant(tile, track, sigvar);
1245 /* logic signals: create a new signal program */
1246 if (sigtype == SIGTYPE_LOGIC) {
1247 CreateSignalProgram(tile, track);
1250 while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
1251 } else {
1252 if (convert_signal) {
1253 /* convert signal button pressed */
1254 if (ctrl_pressed) {
1255 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1256 SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1257 /* Query current signal type so the check for PBS signals below works. */
1258 sigtype = GetSignalType(tile, track);
1259 } else {
1260 /* convert the present signal to the chosen type and variant */
1262 /* logic signals: create or delete signal program as necessary */
1263 SignalTypeChanged(tile, track, GetSignalType(tile, track), sigtype);
1265 SetSignalType(tile, track, sigtype);
1266 SetSignalVariant(tile, track, sigvar);
1267 if (IsPbsOrLogicSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1268 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1272 } else if (ctrl_pressed) {
1273 /* cycle between cycle_start and cycle_end */
1274 sigtype = (SignalType)(GetSignalType(tile, track) + 1);
1275 if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
1277 /* logic signals: create or delete signal program as necessary */
1278 SignalTypeChanged(tile, track, GetSignalType(tile, track), sigtype);
1280 SetSignalType(tile, track, sigtype);
1281 if (IsPbsOrLogicSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1282 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1284 } else {
1285 /* cycle the signal side: both -> left -> right -> both -> ... */
1286 CycleSignalSide(tile, track);
1287 /* Query current signal type so the check for PBS signals below works. */
1288 sigtype = GetSignalType(tile, track);
1291 } else {
1292 /* If CmdBuildManySignals is called with copying signals, just copy the
1293 * direction of the first signal given as parameter by CmdBuildManySignals */
1294 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (p2 & SignalOnTrack(track)));
1295 SetSignalVariant(tile, track, sigvar);
1296 SetSignalType(tile, track, sigtype);
1298 /* logic signals: create a new signal program */
1299 if (sigtype == SIGTYPE_LOGIC) {
1300 CreateSignalProgram(tile, track);
1304 /* Add new signal infrastructure count. */
1305 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1306 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1308 if (IsPbsSignal(sigtype)) {
1309 /* PBS signals should show red unless they are on reserved tiles without a train. */
1310 uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
1311 SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetRailReservationTrackBits(tile), track) && EnsureNoVehicleOnGround(tile).Succeeded() ? UINT_MAX : 0) & mask));
1313 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1314 AddTrackToSignalBuffer(tile, track, _current_company);
1315 YapfNotifyTrackLayoutChange(tile, track);
1316 if (v != NULL) {
1317 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1318 if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
1319 !IsSafeWaitingPosition(v, v->tile, v->GetVehicleTrackdir(), true, _settings_game.pf.forbid_90_deg)) {
1320 TryPathReserve(v, true);
1325 return cost;
1328 static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal_ctr, bool remove)
1330 tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
1331 if (tile == INVALID_TILE) return false;
1333 /* Check for track bits on the new tile */
1334 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
1336 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
1337 trackdirbits &= TrackdirReachesTrackdirs(trackdir);
1339 /* No track bits, must stop */
1340 if (trackdirbits == TRACKDIR_BIT_NONE) return false;
1342 /* Get the first track dir */
1343 trackdir = RemoveFirstTrackdir(&trackdirbits);
1345 /* Any left? It's a junction so we stop */
1346 if (trackdirbits != TRACKDIR_BIT_NONE) return false;
1348 switch (GetTileType(tile)) {
1349 case MP_RAILWAY:
1350 if (IsRailDepot(tile)) return false;
1351 if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
1352 signal_ctr++;
1353 if (IsDiagonalTrackdir(trackdir)) {
1354 signal_ctr++;
1355 /* Ensure signal_ctr even so X and Y pieces get signals */
1356 ClrBit(signal_ctr, 0);
1358 return true;
1360 case MP_ROAD:
1361 if (!IsLevelCrossing(tile)) return false;
1362 signal_ctr += 2;
1363 return true;
1365 case MP_TUNNELBRIDGE: {
1366 if (!remove && IsTunnelBridgeWithSignalSimulation(tile)) return false;
1367 TileIndex orig_tile = tile; // backup old value
1369 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
1370 if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
1372 /* Skip to end of tunnel or bridge
1373 * note that tile is a parameter by reference, so it must be updated */
1374 tile = GetOtherTunnelBridgeEnd(tile);
1376 signal_ctr += (GetTunnelBridgeLength(orig_tile, tile) + 2) * 2;
1377 return true;
1380 default: return false;
1385 * Build many signals by dragging; AutoSignals
1386 * @param tile start tile of drag
1387 * @param flags operation to perform
1388 * @param p1 end tile of drag
1389 * @param p2 various bitstuffed elements
1390 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1391 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1392 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1393 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1394 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1395 * - p2 = (bit 7- 9) - default signal type
1396 * - p2 = (bit 10) - 0 = keep fixed distance, 1 = minimise gaps between signals
1397 * - p2 = (bit 24-31) - user defined signals_density
1398 * @param text unused
1399 * @return the cost of this operation or an error
1401 static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1403 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1404 TileIndex start_tile = tile;
1406 Track track = Extract<Track, 0, 3>(p2);
1407 bool mode = HasBit(p2, 3);
1408 bool semaphores = HasBit(p2, 4);
1409 bool remove = HasBit(p2, 5);
1410 bool autofill = HasBit(p2, 6);
1411 bool minimise_gaps = HasBit(p2, 10);
1412 byte signal_density = GB(p2, 24, 8);
1414 if (p1 >= MapSize() || !ValParamTrackOrientation(track)) return CMD_ERROR;
1415 TileIndex end_tile = p1;
1416 if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
1418 if (!IsPlainRailTile(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1420 /* for vertical/horizontal tracks, double the given signals density
1421 * since the original amount will be too dense (shorter tracks) */
1422 signal_density *= 2;
1424 Trackdir trackdir = TrackToTrackdir(track);
1425 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
1426 if (ret.Failed()) return ret;
1428 track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
1429 Trackdir start_trackdir = trackdir;
1431 /* Must start on a valid track to be able to avoid loops */
1432 if (!HasTrack(tile, track)) return CMD_ERROR;
1434 SignalType sigtype = (SignalType)GB(p2, 7, 3);
1435 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1437 byte signals;
1438 /* copy the signal-style of the first rail-piece if existing */
1439 if (HasSignalOnTrack(tile, track)) {
1440 signals = GetPresentSignals(tile) & SignalOnTrack(track);
1441 assert(signals != 0);
1443 /* copy signal/semaphores style (independent of CTRL) */
1444 semaphores = GetSignalVariant(tile, track) != SIG_ELECTRIC;
1446 sigtype = GetSignalType(tile, track);
1447 /* Don't but copy entry or exit-signal type */
1448 if (sigtype == SIGTYPE_ENTRY || sigtype == SIGTYPE_EXIT) sigtype = SIGTYPE_NORMAL;
1449 } else { // no signals exist, drag a two-way signal stretch
1450 signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
1453 byte signal_dir = 0;
1454 if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
1455 if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
1457 /* signal_ctr - amount of tiles already processed
1458 * last_used_ctr - amount of tiles before previously placed signal
1459 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1460 * last_suitable_ctr - amount of tiles before last possible signal place
1461 * last_suitable_tile - last tile where it is possible to place a signal
1462 * last_suitable_trackdir - trackdir of the last tile
1463 **********
1464 * trackdir - trackdir to build with autorail
1465 * semaphores - semaphores or signals
1466 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1467 * and convert all others to semaphore/signal
1468 * remove - 1 remove signals, 0 build signals */
1469 int signal_ctr = 0;
1470 int last_used_ctr = INT_MIN; // initially INT_MIN to force building/removing at the first tile
1471 int last_suitable_ctr = 0;
1472 TileIndex last_suitable_tile = INVALID_TILE;
1473 Trackdir last_suitable_trackdir = INVALID_TRACKDIR;
1474 CommandCost last_error = CMD_ERROR;
1475 bool had_success = false;
1476 std::vector<TileIndex> tunnel_bridge_blacklist;
1477 for (;;) {
1478 bool tile_ok = true;
1479 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1480 if (container_unordered_remove(tunnel_bridge_blacklist, tile) > 0) {
1481 /* This tile is blacklisted, skip tile and remove from blacklist.
1482 * Mark last used counter as current tile.
1484 tile_ok = false;
1485 last_used_ctr = signal_ctr;
1486 last_suitable_tile = INVALID_TILE;
1490 /* only build/remove signals with the specified density */
1491 if (tile_ok && (remove || minimise_gaps || signal_ctr % signal_density == 0 || IsTileType(tile, MP_TUNNELBRIDGE))) {
1492 uint32 p1 = GB(TrackdirToTrack(trackdir), 0, 3);
1493 SB(p1, 3, 1, mode);
1494 SB(p1, 4, 1, semaphores);
1495 SB(p1, 5, 3, sigtype);
1496 if (!remove && signal_ctr == 0) SetBit(p1, 17);
1498 /* Pick the correct orientation for the track direction */
1499 signals = 0;
1500 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
1501 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
1503 /* Test tiles in between for suitability as well if minimising gaps. */
1504 bool test_only = !remove && minimise_gaps && signal_ctr < (last_used_ctr + signal_density);
1505 CommandCost ret = DoCommand(tile, p1, signals, test_only ? flags & ~DC_EXEC : flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1507 if (!test_only && ret.Succeeded() && IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(tile) == TrackdirToExitdir(trackdir)) {
1508 /* Blacklist far end of tunnel if we just actioned the near end */
1509 tunnel_bridge_blacklist.push_back(GetOtherTunnelBridgeEnd(tile));
1512 if (ret.Succeeded()) {
1513 /* Remember last track piece where we can place a signal. */
1514 last_suitable_ctr = signal_ctr;
1515 last_suitable_tile = tile;
1516 last_suitable_trackdir = trackdir;
1517 } else if (!test_only && last_suitable_tile != INVALID_TILE) {
1518 /* If a signal can't be placed, place it at the last possible position. */
1519 SB(p1, 0, 3, TrackdirToTrack(last_suitable_trackdir));
1520 ClrBit(p1, 17);
1522 /* Pick the correct orientation for the track direction. */
1523 signals = 0;
1524 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(last_suitable_trackdir);
1525 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(last_suitable_trackdir);
1527 ret = DoCommand(last_suitable_tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1529 if (ret.Succeeded() && IsTileType(last_suitable_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(last_suitable_tile) == TrackdirToExitdir(last_suitable_trackdir)) {
1530 /* Blacklist far end of tunnel if we just actioned the near end */
1531 tunnel_bridge_blacklist.push_back(GetOtherTunnelBridgeEnd(last_suitable_tile));
1535 /* Collect cost. */
1536 if (!test_only) {
1537 /* Be user-friendly and try placing signals as much as possible */
1538 if (ret.Succeeded()) {
1539 had_success = true;
1540 total_cost.AddCost(ret);
1541 last_used_ctr = last_suitable_ctr;
1542 last_suitable_tile = INVALID_TILE;
1543 } else {
1544 /* The "No railway" error is the least important one. */
1545 if (ret.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK ||
1546 last_error.GetErrorMessage() == INVALID_STRING_ID) {
1547 last_error = ret;
1553 if (autofill) {
1554 if (!CheckSignalAutoFill(tile, trackdir, signal_ctr, remove)) break;
1556 /* Prevent possible loops */
1557 if (tile == start_tile && trackdir == start_trackdir) break;
1558 } else {
1559 if (tile == end_tile) break;
1561 tile += ToTileIndexDiff(_trackdelta[trackdir]);
1562 signal_ctr++;
1564 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1565 if (IsDiagonalTrackdir(trackdir)) {
1566 signal_ctr++;
1567 } else {
1568 ToggleBit(trackdir, 0);
1573 return had_success ? total_cost : last_error;
1577 * Build signals on a stretch of track.
1578 * Stub for the unified signal builder/remover
1579 * @param tile start tile of drag
1580 * @param flags operation to perform
1581 * @param p1 end tile of drag
1582 * @param p2 various bitstuffed elements
1583 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1584 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1585 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1586 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1587 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1588 * - p2 = (bit 7- 9) - default signal type
1589 * - p2 = (bit 24-31) - user defined signals_density
1590 * @param text unused
1591 * @return the cost of this operation or an error
1592 * @see CmdSignalTrackHelper
1594 CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1596 return CmdSignalTrackHelper(tile, flags, p1, p2, text);
1600 * Remove signals
1601 * @param tile coordinates where signal is being deleted from
1602 * @param flags operation to perform
1603 * @param p1 various bitstuffed elements, only track information is used
1604 * - (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1605 * - (bit 3) - override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1606 * - (bit 4) - 0 = signals, 1 = semaphores
1607 * @param p2 unused
1608 * @param text unused
1609 * @return the cost of this operation or an error
1611 CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1613 Track track = Extract<Track, 0, 3>(p1);
1614 Money cost = _price[PR_CLEAR_SIGNALS];
1616 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1617 TileIndex end = GetOtherTunnelBridgeEnd(tile);
1618 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1619 if (!IsTunnelBridgeWithSignalSimulation(tile)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1621 cost *= ((GetTunnelBridgeLength(tile, end) + 4) >> 2);
1623 CommandCost ret = EnsureNoTrainOnTrack(GetOtherTunnelBridgeEnd(tile), track);
1624 if (ret.Failed()) return ret;
1625 ret = EnsureNoTrainOnTrack(tile, track);
1626 if (ret.Failed()) return ret;
1627 } else {
1628 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1629 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1631 if (!HasSignalOnTrack(tile, track)) {
1632 return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1634 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
1635 if (ret.Failed()) return ret;
1638 /* Only water can remove signals from anyone */
1639 if (_current_company != OWNER_WATER) {
1642 /* Do it? */
1643 if (flags & DC_EXEC) {
1645 if (IsTunnelBridgeWithSignalSimulation(tile)) { // handle tunnel/bridge signals.
1646 TileIndex end = GetOtherTunnelBridgeEnd(tile);
1647 Company::Get(GetTileOwner(tile))->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, end);
1648 ClearBridgeTunnelSignalSimulation(end, tile);
1649 ClearBridgeTunnelSignalSimulation(tile, end);
1650 MarkBridgeOrTunnelDirty(tile);
1651 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, GetTileOwner(tile));
1652 AddSideToSignalBuffer(end, INVALID_DIAGDIR, GetTileOwner(tile));
1653 YapfNotifyTrackLayoutChange(tile, track);
1654 YapfNotifyTrackLayoutChange(end, track);
1655 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1656 return CommandCost(EXPENSES_CONSTRUCTION, cost);
1659 Train *v = NULL;
1660 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1661 v = GetTrainForReservation(tile, track);
1662 } else if (IsPbsSignal(GetSignalType(tile, track))) {
1663 /* PBS signal, might be the end of a path reservation. */
1664 Trackdir td = TrackToTrackdir(track);
1665 for (int i = 0; v == NULL && i < 2; i++, td = ReverseTrackdir(td)) {
1666 /* Only test the active signal side. */
1667 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
1668 TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
1669 TrackBits tracks = TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td));
1670 if (HasReservedTracks(next, tracks)) {
1671 v = GetTrainForReservation(next, TrackBitsToTrack(GetReservedTrackbits(next) & tracks));
1676 /* Remove any links this signal had */
1677 RemoveSignalLink(tile, track);
1678 /* Logic signal: remove signal program */
1679 if (IsLogicSignal(tile, track)) {
1680 DeleteSignalProgram(tile, track);
1683 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1684 SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
1685 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1686 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1687 TraceRestrictNotifySignalRemoval(tile, track);
1689 /* removed last signal from tile? */
1690 if (GetPresentSignals(tile) == 0) {
1691 SetSignalStates(tile, 0);
1692 SetHasSignals(tile, false);
1693 SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
1696 AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
1697 YapfNotifyTrackLayoutChange(tile, track);
1698 if (v != NULL) TryPathReserve(v, false);
1700 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1703 return CommandCost(EXPENSES_CONSTRUCTION, cost);
1707 * Remove signals on a stretch of track.
1708 * Stub for the unified signal builder/remover
1709 * @param tile start tile of drag
1710 * @param flags operation to perform
1711 * @param p1 end tile of drag
1712 * @param p2 various bitstuffed elements
1713 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1714 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1715 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1716 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1717 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1718 * - p2 = (bit 7- 9) - default signal type
1719 * - p2 = (bit 24-31) - user defined signals_density
1720 * @param text unused
1721 * @return the cost of this operation or an error
1722 * @see CmdSignalTrackHelper
1724 CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1726 return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
1729 /** Update power of train under which is the railtype being converted */
1730 static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
1732 if (v->type != VEH_TRAIN) return NULL;
1734 TrainList *affected_trains = static_cast<TrainList*>(data);
1735 affected_trains->Include(Train::From(v)->First());
1737 return NULL;
1741 * Convert one rail type to the other. You can convert normal rail to
1742 * monorail/maglev easily or vice-versa.
1743 * @param tile end tile of rail conversion drag
1744 * @param flags operation to perform
1745 * @param p1 start tile of drag
1746 * @param p2 various bitstuffed elements:
1747 * - p2 = (bit 0 - 4) new railtype to convert to.
1748 * - p2 = (bit 5) build diagonally or not.
1749 * @param text unused
1750 * @return the cost of this operation or an error
1752 CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1754 RailType totype = Extract<RailType, 0, 5>(p2);
1755 TileIndex area_start = p1;
1756 TileIndex area_end = tile;
1757 bool diagonal = HasBit(p2, 5);
1759 if (!ValParamRailtype(totype)) return CMD_ERROR;
1760 if (area_start >= MapSize()) return CMD_ERROR;
1762 TrainList affected_trains;
1764 CommandCost cost(EXPENSES_CONSTRUCTION);
1765 CommandCost error = CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK); // by default, there is no track to convert.
1767 TileIterator *iter = diagonal ? (TileIterator *)new DiagonalTileIterator(area_start, area_end) : new OrthogonalTileIterator(area_start, area_end);
1768 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
1769 TileType tt = GetTileType(tile);
1771 /* Check if there is any track on tile */
1772 switch (tt) {
1773 case MP_RAILWAY:
1774 break;
1775 case MP_STATION:
1776 if (!HasStationRail(tile)) continue;
1777 break;
1778 case MP_ROAD:
1779 if (!IsLevelCrossing(tile)) continue;
1780 if (RailNoLevelCrossings(totype)) {
1781 error.MakeError(STR_ERROR_CROSSING_DISALLOWED);
1782 continue;
1784 break;
1785 case MP_TUNNELBRIDGE:
1786 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
1787 break;
1788 default: continue;
1791 /* Original railtype we are converting from */
1792 RailType type = GetRailType(tile);
1794 /* Converting to the same type or converting 'hidden' elrail -> rail */
1795 if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
1797 /* Trying to convert other's rail */
1798 CommandCost ret = CheckTileOwnership(tile);
1799 if (ret.Failed()) {
1800 error = ret;
1801 continue;
1804 SmallVector<Train *, 2> vehicles_affected;
1806 /* Vehicle on the tile when not converting Rail <-> ElRail
1807 * Tunnels and bridges have special check later */
1808 if (tt != MP_TUNNELBRIDGE) {
1809 if (!IsCompatibleRail(type, totype)) {
1810 CommandCost ret = IsPlainRailTile(tile) ? EnsureNoTrainOnTrackBits(tile, GetTrackBits(tile)) : EnsureNoVehicleOnGround(tile);
1811 if (ret.Failed()) {
1812 error = ret;
1813 continue;
1816 if (flags & DC_EXEC) { // we can safely convert, too
1817 TrackBits reserved = GetReservedTrackbits(tile);
1818 Track track;
1819 while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
1820 Train *v = GetTrainForReservation(tile, track);
1821 if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1822 /* No power on new rail type, reroute. */
1823 FreeTrainTrackReservation(v);
1824 *vehicles_affected.Append() = v;
1828 /* Update the company infrastructure counters. */
1829 if (!IsRailStationTile(tile) || !IsStationTileBlocked(tile)) {
1830 Company *c = Company::Get(GetTileOwner(tile));
1831 uint num_pieces = IsLevelCrossingTile(tile) ? LEVELCROSSING_TRACKBIT_FACTOR : 1;
1832 if (IsPlainRailTile(tile)) {
1833 TrackBits bits = GetTrackBits(tile);
1834 num_pieces = CountBits(bits);
1835 if (TracksOverlap(bits)) num_pieces *= num_pieces;
1837 c->infrastructure.rail[type] -= num_pieces;
1838 c->infrastructure.rail[totype] += num_pieces;
1839 DirtyCompanyInfrastructureWindows(c->index);
1842 SetRailType(tile, totype);
1843 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1844 /* update power of train on this tile */
1845 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1849 switch (tt) {
1850 case MP_RAILWAY:
1851 switch (GetRailTileType(tile)) {
1852 case RAIL_TILE_DEPOT:
1853 if (flags & DC_EXEC) {
1854 /* notify YAPF about the track layout change */
1855 YapfNotifyTrackLayoutChange(tile, GetRailDepotTrack(tile));
1857 /* Update build vehicle window related to this depot */
1858 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
1859 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
1861 cost.AddCost(RailConvertCost(type, totype));
1862 break;
1864 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1865 if (flags & DC_EXEC) {
1866 /* notify YAPF about the track layout change */
1867 TrackBits tracks = GetTrackBits(tile);
1868 while (tracks != TRACK_BIT_NONE) {
1869 YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(&tracks));
1872 cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
1873 break;
1875 break;
1877 case MP_TUNNELBRIDGE: {
1878 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
1880 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1881 * it would cause assert because of different test and exec runs */
1882 if (endtile < tile) {
1883 if (diagonal) {
1884 if (DiagonalTileArea(area_start, area_end).Contains(endtile)) continue;
1885 } else {
1886 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
1890 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1891 if (!IsCompatibleRail(GetRailType(tile), totype)) {
1892 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
1893 if (ret.Failed()) {
1894 error = ret;
1895 continue;
1899 if (flags & DC_EXEC) {
1900 Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
1901 if (HasTunnelBridgeReservation(tile)) {
1902 Train *v = GetTrainForReservation(tile, track);
1903 if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1904 /* No power on new rail type, reroute. */
1905 FreeTrainTrackReservation(v);
1906 *vehicles_affected.Append() = v;
1910 /* Update the company infrastructure counters. */
1911 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1912 Company *c = Company::Get(GetTileOwner(tile));
1913 c->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1914 c->infrastructure.rail[totype] += num_pieces;
1915 DirtyCompanyInfrastructureWindows(c->index);
1917 SetRailType(tile, totype);
1918 SetRailType(endtile, totype);
1920 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1921 FindVehicleOnPos(endtile, &affected_trains, &UpdateTrainPowerProc);
1923 YapfNotifyTrackLayoutChange(tile, track);
1924 YapfNotifyTrackLayoutChange(endtile, track);
1926 if (IsBridge(tile)) {
1927 MarkBridgeDirty(tile);
1928 } else {
1929 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1930 MarkTileDirtyByTile(endtile, ZOOM_LVL_DRAW_MAP);
1934 cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
1935 break;
1938 default: // MP_STATION, MP_ROAD
1939 if (flags & DC_EXEC) {
1940 Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
1941 YapfNotifyTrackLayoutChange(tile, track);
1944 cost.AddCost(RailConvertCost(type, totype));
1945 break;
1948 for (uint i = 0; i < vehicles_affected.Length(); ++i) {
1949 TryPathReserve(vehicles_affected[i], true);
1953 if (flags & DC_EXEC) {
1954 /* Railtype changed, update trains as when entering different track */
1955 for (Train **v = affected_trains.Begin(); v != affected_trains.End(); v++) {
1956 (*v)->ConsistChanged(CCF_TRACK);
1960 delete iter;
1961 return (cost.GetCost() == 0) ? error : cost;
1964 static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
1966 if (_current_company != OWNER_WATER) {
1967 CommandCost ret = CheckTileOwnership(tile);
1968 if (ret.Failed()) return ret;
1971 CommandCost ret = EnsureNoVehicleOnGround(tile);
1972 if (ret.Failed()) return ret;
1974 if (flags & DC_EXEC) {
1975 /* read variables before the depot is removed */
1976 DiagDirection dir = GetRailDepotDirection(tile);
1977 Owner owner = GetTileOwner(tile);
1978 Train *v = NULL;
1980 if (HasDepotReservation(tile)) {
1981 v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
1982 if (v != NULL) FreeTrainTrackReservation(v);
1985 Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1986 DirtyCompanyInfrastructureWindows(owner);
1988 delete Depot::GetByTile(tile);
1989 DoClearSquare(tile);
1990 AddSideToSignalBuffer(tile, dir, owner);
1991 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1992 if (v != NULL) TryPathReserve(v, true);
1995 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
1998 static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
2000 CommandCost cost(EXPENSES_CONSTRUCTION);
2002 if (flags & DC_AUTO) {
2003 if (!IsTileOwner(tile, _current_company)) {
2004 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
2007 if (IsPlainRail(tile)) {
2008 return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2009 } else {
2010 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
2014 switch (GetRailTileType(tile)) {
2015 case RAIL_TILE_SIGNALS:
2016 case RAIL_TILE_NORMAL: {
2017 Slope tileh = GetTileSlope(tile);
2018 /* Is there flat water on the lower halftile that gets cleared expensively? */
2019 bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
2021 TrackBits tracks = GetTrackBits(tile);
2022 while (tracks != TRACK_BIT_NONE) {
2023 Track track = RemoveFirstTrack(&tracks);
2024 CommandCost ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
2025 if (ret.Failed()) return ret;
2026 cost.AddCost(ret);
2029 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
2030 * Same holds for non-companies clearing the tile, e.g. disasters. */
2031 if (water_ground && !(flags & DC_BANKRUPT) && Company::IsValidID(_current_company)) {
2032 CommandCost ret = EnsureNoVehicleOnGround(tile);
2033 if (ret.Failed()) return ret;
2035 /* The track was removed, and left a coast tile. Now also clear the water. */
2036 if (flags & DC_EXEC) DoClearSquare(tile);
2037 cost.AddCost(_price[PR_CLEAR_WATER]);
2040 return cost;
2043 case RAIL_TILE_DEPOT:
2044 return RemoveTrainDepot(tile, flags);
2046 default:
2047 return CMD_ERROR;
2052 * Get surface height in point (x,y)
2053 * On tiles with halftile foundations move (x,y) to a safe point wrt. track
2055 static uint GetSaveSlopeZ(uint x, uint y, Track track)
2057 switch (track) {
2058 case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
2059 case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
2060 case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
2061 case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
2062 default: break;
2064 return GetSlopePixelZ(x, y);
2067 static void DrawSingleSignal(TileIndex tile, const RailtypeInfo *rti, Track track, SignalState condition, SignalOffsets image, uint pos)
2069 bool side;
2070 switch (_settings_game.construction.train_signal_side) {
2071 case 0: side = false; break; // left
2072 case 2: side = true; break; // right
2073 default: side = _settings_game.vehicle.road_side != 0; break; // driving side
2075 static const Point SignalPositions[2][12] = {
2076 { // Signals on the left side
2077 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
2078 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
2079 /* LOWER LOWER X X Y Y */
2080 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
2081 }, { // Signals on the right side
2082 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
2083 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
2084 /* LOWER LOWER X X Y Y */
2085 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
2089 uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
2090 uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
2092 SignalType type = GetSignalType(tile, track);
2093 SignalVariant variant = GetSignalVariant(tile, track);
2095 SpriteID sprite = GetCustomSignalSprite(rti, tile, type, variant, condition);
2096 bool is_custom_sprite = (sprite != 0);
2097 if (sprite != 0) {
2098 sprite += image;
2099 } else {
2100 /* Normal electric signals are stored in a different sprite block than all other signals. */
2101 sprite = (type == SIGTYPE_NORMAL && variant == SIG_ELECTRIC) ? SPR_ORIGINAL_SIGNALS_BASE : SPR_SIGNALS_BASE - 16;
2102 sprite += type * 16 + variant * 64 + image * 2 + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
2105 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
2108 static uint32 _drawtile_track_palette;
2112 /** Offsets for drawing fences */
2113 struct FenceOffset {
2114 Corner height_ref; //!< Corner to use height offset from.
2115 int x_offs; //!< Bounding box X offset.
2116 int y_offs; //!< Bounding box Y offset.
2117 int x_size; //!< Bounding box X size.
2118 int y_size; //!< Bounding box Y size.
2121 /** Offsets for drawing fences */
2122 static FenceOffset _fence_offsets[] = {
2123 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
2124 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
2125 { CORNER_W, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
2126 { CORNER_N, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
2127 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
2128 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
2129 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
2130 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
2131 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
2132 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
2133 { CORNER_E, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
2134 { CORNER_S, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
2135 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
2136 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
2137 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
2138 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
2142 * Draw a track fence.
2143 * @param ti Tile drawing information.
2144 * @param base_image First fence sprite.
2145 * @param num_sprites Number of fence sprites.
2146 * @param rfo Fence to draw.
2148 static void DrawTrackFence(const TileInfo *ti, SpriteID base_image, uint num_sprites, RailFenceOffset rfo)
2150 int z = ti->z;
2151 if (_fence_offsets[rfo].height_ref != CORNER_INVALID) {
2152 z += GetSlopePixelZInCorner(RemoveHalftileSlope(ti->tileh), _fence_offsets[rfo].height_ref);
2154 AddSortableSpriteToDraw(base_image + (rfo % num_sprites), _drawtile_track_palette,
2155 ti->x + _fence_offsets[rfo].x_offs,
2156 ti->y + _fence_offsets[rfo].y_offs,
2157 _fence_offsets[rfo].x_size,
2158 _fence_offsets[rfo].y_size,
2159 4, z);
2163 * Draw fence at NW border matching the tile slope.
2165 static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2167 RailFenceOffset rfo = RFO_FLAT_X_NW;
2168 if (ti->tileh & SLOPE_NW) rfo = (ti->tileh & SLOPE_W) ? RFO_SLOPE_SW_NW : RFO_SLOPE_NE_NW;
2169 DrawTrackFence(ti, base_image, num_sprites, rfo);
2173 * Draw fence at SE border matching the tile slope.
2175 static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2177 RailFenceOffset rfo = RFO_FLAT_X_SE;
2178 if (ti->tileh & SLOPE_SE) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW_SE : RFO_SLOPE_NE_SE;
2179 DrawTrackFence(ti, base_image, num_sprites, rfo);
2183 * Draw fence at NE border matching the tile slope.
2185 static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2187 RailFenceOffset rfo = RFO_FLAT_Y_NE;
2188 if (ti->tileh & SLOPE_NE) rfo = (ti->tileh & SLOPE_E) ? RFO_SLOPE_SE_NE : RFO_SLOPE_NW_NE;
2189 DrawTrackFence(ti, base_image, num_sprites, rfo);
2193 static byte GetTrackGrowthPhase(TileIndex ti, TrackBits trackbits)
2195 if (!IsTileType(ti, MP_RAILWAY))
2196 return 0;
2198 if (!IsPlainRailTile(ti))
2199 return 0;
2201 if ((GetTrackBits(ti) & trackbits) == 0)
2202 return 0;
2204 return GetTrackGrowthPhase(ti);
2208 * GetTrackGrowthPhaseEx returns a calculated growth factor
2209 * for a specific track on a tile - by also looking at its
2210 * neighbours
2212 byte GetTrackGrowthPhaseEx(TileIndex ti, Track track)
2214 byte phase = GetTrackGrowthPhase(ti);
2215 if (phase == 3) return 3;
2217 /* If this track piece is connected to a neighbour tile///
2218 * and that neighbour is used less often - we can't
2219 * be the track piece that is used so often on this tile
2221 Trackdir td1 = TrackToTrackdir(track);
2222 DiagDirection dd1 = TrackdirToExitdir(td1);
2223 TrackBits tb1 = DiagdirReachesTracks(dd1);
2224 TileIndex ti1 = ti + TileOffsByDiagDir(dd1);
2225 byte phase1 = GetTrackGrowthPhase(ti1, tb1);
2226 if (phase1 == 3) return 3;
2228 /* Same check for the other neighbour */
2229 Trackdir td2 = ReverseTrackdir(td1);
2230 DiagDirection dd2 = TrackdirToExitdir(td2);
2231 TrackBits tb2 = DiagdirReachesTracks(dd2);
2232 TileIndex ti2 = ti + TileOffsByDiagDir(dd2);
2233 byte phase2 = GetTrackGrowthPhase(ti2, tb2);
2234 if (phase2 == 3) return 3;
2236 /* Return the highest growth factor */
2237 return max(phase, max(phase1, phase2));
2240 static bool GetTrackGrowthSpriteBase(TileIndex tile, Track track, SpriteID& base)
2242 byte phase = GetTrackGrowthPhaseEx(tile, track);
2243 if (phase == 0)
2244 return false;
2246 assert(phase <= 3);
2248 base = SPR_OLDTRACKS_BASE + 10 * (phase - 1);
2249 return true;
2252 static bool GetTrackGrowthPalette(TileIndex tile, SpriteID& pal)
2254 pal = PAL_NONE;
2257 * In arctic, use the 'BARE' palette always, looks better on that terrain
2258 * obsolete when it will get its own overlays (for snow, also)
2260 switch (_settings_game.game_creation.landscape) {
2261 case LT_ARCTIC: pal = PALETTE_TO_BARE_LAND; break;
2262 default: break;
2266 * Use 'BARE' palette for desert in tropical and snow in arctic since it
2267 * looks better than green. But use other overlays in future!!
2269 switch (GetRailGroundType(tile)) {
2270 case RAIL_GROUND_ICE_DESERT: /* fallthrough */
2271 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2272 default: break;
2275 /* Both base and pal set; we can return true */
2276 return true;
2279 void DrawTrackGrowth(TileInfo* ti, TrackBits track)
2281 SpriteID pal, base;
2282 TileIndex tile = ti->tile;
2283 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(ti->tile))->label;
2285 if (railTypeLabel == _planning_tracks_label ||
2286 railTypeLabel == _pipeline_tracks_label ||
2287 railTypeLabel == _wires_tracks_label) {
2288 // Never age these specialized tracks.
2289 return;
2292 if (!GetTrackGrowthPalette(tile, pal)) return;
2294 /* future support for tunnels */
2295 Slope tileh = ti->tileh;
2296 if (IsTunnelTile(ti->tile)) tileh = SLOPE_FLAT;
2298 switch (tileh) {
2299 case SLOPE_NW:
2300 assert(track == TRACK_BIT_Y);
2301 if (GetTrackGrowthSpriteBase(tile, TRACK_Y, base))
2302 DrawGroundSprite(base + 9, pal);
2303 break;
2304 case SLOPE_SW:
2305 assert(track == TRACK_BIT_X);
2306 if (GetTrackGrowthSpriteBase(tile, TRACK_X, base))
2307 DrawGroundSprite(base + 8, pal);
2308 break;
2309 case SLOPE_SE:
2310 assert(track == TRACK_BIT_Y);
2311 if (GetTrackGrowthSpriteBase(tile, TRACK_Y, base))
2312 DrawGroundSprite(base + 7, pal);
2313 break;
2314 case SLOPE_NE:
2315 assert(track == TRACK_BIT_X);
2316 if (GetTrackGrowthSpriteBase(tile, TRACK_X, base))
2317 DrawGroundSprite(base + 6, pal);
2318 break;
2319 default:
2320 /* any track bits on any other slope are drawn normally */
2321 if ((track & TRACK_BIT_Y) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_Y, base)) DrawGroundSprite(base + 0, pal);
2322 if ((track & TRACK_BIT_X) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_X, base)) DrawGroundSprite(base + 1, pal);
2323 if ((track & TRACK_BIT_UPPER) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_UPPER, base)) DrawGroundSprite(base + 2, pal);
2324 if ((track & TRACK_BIT_LOWER) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_LOWER, base)) DrawGroundSprite(base + 3, pal);
2325 if ((track & TRACK_BIT_RIGHT) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_RIGHT, base)) DrawGroundSprite(base + 4, pal);
2326 if ((track & TRACK_BIT_LEFT) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_LEFT, base)) DrawGroundSprite(base + 5, pal);
2327 break;
2332 * Draw fence at SW border matching the tile slope.
2334 static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2336 RailFenceOffset rfo = RFO_FLAT_Y_SW;
2337 if (ti->tileh & SLOPE_SW) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE_SW : RFO_SLOPE_NW_SW;
2338 DrawTrackFence(ti, base_image, num_sprites, rfo);
2342 * Draw track fences.
2343 * @param ti Tile drawing information.
2344 * @param rti Rail type information.
2346 static void DrawTrackDetails(const TileInfo *ti, const RailtypeInfo *rti)
2348 /* Base sprite for track fences.
2349 * Note: Halftile slopes only have fences on the upper part. */
2350 uint num_sprites = 0;
2351 SpriteID base_image = GetCustomRailSprite(rti, ti->tile, RTSG_FENCES, IsHalftileSlope(ti->tileh) ? TCX_UPPER_HALFTILE : TCX_NORMAL, &num_sprites);
2352 if (base_image == 0) {
2353 base_image = SPR_TRACK_FENCE_FLAT_X;
2354 num_sprites = 8;
2357 assert(num_sprites > 0);
2359 switch (GetRailGroundType(ti->tile)) {
2360 case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image, num_sprites); break;
2361 case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image, num_sprites); break;
2362 case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW(ti, base_image, num_sprites);
2363 DrawTrackFence_SE(ti, base_image, num_sprites); break;
2364 case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image, num_sprites); break;
2365 case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image, num_sprites); break;
2366 case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE(ti, base_image, num_sprites);
2367 DrawTrackFence_SW(ti, base_image, num_sprites); break;
2368 case RAIL_GROUND_FENCE_VERT1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2369 case RAIL_GROUND_FENCE_VERT2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2370 case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2371 case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2372 case RAIL_GROUND_WATER: {
2373 Corner track_corner;
2374 if (IsHalftileSlope(ti->tileh)) {
2375 /* Steep slope or one-corner-raised slope with halftile foundation */
2376 track_corner = GetHalftileSlopeCorner(ti->tileh);
2377 } else {
2378 /* Three-corner-raised slope */
2379 track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2381 switch (track_corner) {
2382 case CORNER_W: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2383 case CORNER_S: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2384 case CORNER_E: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2385 case CORNER_N: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2386 default: NOT_REACHED();
2388 break;
2390 default: break;
2394 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2395 static const int INF = 1000; // big number compared to tilesprite size
2396 static const SubSprite _halftile_sub_sprite[4] = {
2397 { -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
2398 { -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
2399 { -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
2400 { -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2403 static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
2405 DrawGroundSprite(sprite, pal, NULL, 0, (ti->tileh & s) ? -8 : 0);
2408 static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailtypeInfo *rti)
2410 RailGroundType rgt = GetRailGroundType(ti->tile);
2411 Foundation f = GetRailFoundation(ti->tileh, track);
2412 Corner halftile_corner = CORNER_INVALID;
2414 if (IsNonContinuousFoundation(f)) {
2415 /* Save halftile corner */
2416 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2417 /* Draw lower part first */
2418 track &= ~CornerToTrackBits(halftile_corner);
2419 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2422 DrawFoundation(ti, f);
2423 /* DrawFoundation modifies ti */
2425 /* Draw ground */
2426 if (rgt == RAIL_GROUND_WATER) {
2427 if (track != TRACK_BIT_NONE || IsSteepSlope(ti->tileh)) {
2428 /* three-corner-raised slope or steep slope with track on upper part */
2429 DrawShoreTile(ti->tileh);
2430 } else {
2431 /* single-corner-raised slope with track on upper part */
2432 DrawGroundSprite(SPR_FLAT_WATER_TILE, PAL_NONE);
2434 } else {
2435 SpriteID image;
2437 switch (rgt) {
2438 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2439 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2440 default: image = SPR_FLAT_GRASS_TILE; break;
2443 image += SlopeToSpriteOffset(ti->tileh);
2445 DrawGroundSprite(image, PAL_NONE);
2448 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2449 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2450 TrackBits pbs = _settings_client.gui.show_track_reservation ? GetRailReservationTrackBits(ti->tile) : TRACK_BIT_NONE;
2452 if (track == TRACK_BIT_NONE) {
2453 /* Half-tile foundation, no track here? */
2454 } else if (ti->tileh == SLOPE_NW && track == TRACK_BIT_Y) {
2455 DrawGroundSprite(ground + RTO_SLOPE_NW, PAL_NONE);
2456 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NW, PALETTE_CRASH);
2457 } else if (ti->tileh == SLOPE_NE && track == TRACK_BIT_X) {
2458 DrawGroundSprite(ground + RTO_SLOPE_NE, PAL_NONE);
2459 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NE, PALETTE_CRASH);
2460 } else if (ti->tileh == SLOPE_SE && track == TRACK_BIT_Y) {
2461 DrawGroundSprite(ground + RTO_SLOPE_SE, PAL_NONE);
2462 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SE, PALETTE_CRASH);
2463 } else if (ti->tileh == SLOPE_SW && track == TRACK_BIT_X) {
2464 DrawGroundSprite(ground + RTO_SLOPE_SW, PAL_NONE);
2465 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SW, PALETTE_CRASH);
2466 } else {
2467 switch (track) {
2468 /* Draw single ground sprite when not overlapping. No track overlay
2469 * is necessary for these sprites. */
2470 case TRACK_BIT_X: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2471 case TRACK_BIT_Y: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2472 case TRACK_BIT_UPPER: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N); break;
2473 case TRACK_BIT_LOWER: DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2474 case TRACK_BIT_RIGHT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E); break;
2475 case TRACK_BIT_LEFT: DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2476 case TRACK_BIT_CROSS: DrawGroundSprite(ground + RTO_CROSSING_XY, PAL_NONE); break;
2477 case TRACK_BIT_HORZ: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N);
2478 DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2479 case TRACK_BIT_VERT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E);
2480 DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2482 default:
2483 /* We're drawing a junction tile */
2484 if ((track & TRACK_BIT_3WAY_NE) == 0) {
2485 DrawGroundSprite(ground + RTO_JUNCTION_SW, PAL_NONE);
2486 } else if ((track & TRACK_BIT_3WAY_SW) == 0) {
2487 DrawGroundSprite(ground + RTO_JUNCTION_NE, PAL_NONE);
2488 } else if ((track & TRACK_BIT_3WAY_NW) == 0) {
2489 DrawGroundSprite(ground + RTO_JUNCTION_SE, PAL_NONE);
2490 } else if ((track & TRACK_BIT_3WAY_SE) == 0) {
2491 DrawGroundSprite(ground + RTO_JUNCTION_NW, PAL_NONE);
2492 } else {
2493 DrawGroundSprite(ground + RTO_JUNCTION_NSEW, PAL_NONE);
2496 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2497 track &= ~pbs;
2499 /* Draw regular track bits */
2500 if (track & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PAL_NONE);
2501 if (track & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PAL_NONE);
2502 if (track & TRACK_BIT_UPPER) DrawGroundSprite(overlay + RTO_N, PAL_NONE);
2503 if (track & TRACK_BIT_LOWER) DrawGroundSprite(overlay + RTO_S, PAL_NONE);
2504 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(overlay + RTO_E, PAL_NONE);
2505 if (track & TRACK_BIT_LEFT) DrawGroundSprite(overlay + RTO_W, PAL_NONE);
2508 /* Draw reserved track bits */
2509 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2510 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2511 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2512 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2513 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2514 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2517 if (IsValidCorner(halftile_corner)) {
2518 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2519 overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY, TCX_UPPER_HALFTILE);
2520 ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND, TCX_UPPER_HALFTILE);
2522 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2523 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2525 SpriteID image;
2526 switch (rgt) {
2527 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2528 case RAIL_GROUND_ICE_DESERT:
2529 case RAIL_GROUND_HALF_SNOW: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2530 default: image = SPR_FLAT_GRASS_TILE; break;
2533 image += SlopeToSpriteOffset(fake_slope);
2535 DrawGroundSprite(image, PAL_NONE, &(_halftile_sub_sprite[halftile_corner]));
2537 track = CornerToTrackBits(halftile_corner);
2539 int offset;
2540 switch (track) {
2541 default: NOT_REACHED();
2542 case TRACK_BIT_UPPER: offset = RTO_N; break;
2543 case TRACK_BIT_LOWER: offset = RTO_S; break;
2544 case TRACK_BIT_RIGHT: offset = RTO_E; break;
2545 case TRACK_BIT_LEFT: offset = RTO_W; break;
2548 DrawTrackSprite(ground + offset, PAL_NONE, ti, fake_slope);
2549 if (_settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, track)) {
2550 DrawTrackSprite(overlay + offset, PALETTE_CRASH, ti, fake_slope);
2556 * Draw ground sprite and track bits
2557 * @param ti TileInfo
2558 * @param track TrackBits to draw
2560 static void DrawTrackBits(TileInfo *ti, TrackBits track)
2562 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2564 if (rti->UsesOverlay()) {
2565 DrawTrackBitsOverlay(ti, track, rti);
2566 if (_settings_client.gui.show_track_overgrowth) DrawTrackGrowth(ti, track);
2567 return;
2570 RailGroundType rgt = GetRailGroundType(ti->tile);
2571 Foundation f = GetRailFoundation(ti->tileh, track);
2572 Corner halftile_corner = CORNER_INVALID;
2574 if (IsNonContinuousFoundation(f)) {
2575 /* Save halftile corner */
2576 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2577 /* Draw lower part first */
2578 track &= ~CornerToTrackBits(halftile_corner);
2579 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2582 DrawFoundation(ti, f);
2583 /* DrawFoundation modifies ti */
2585 SpriteID image;
2586 PaletteID pal = PAL_NONE;
2587 const SubSprite *sub = NULL;
2588 bool junction = false;
2590 /* Select the sprite to use. */
2591 if (track == 0) {
2592 /* Clear ground (only track on halftile foundation) */
2593 if (rgt == RAIL_GROUND_WATER) {
2594 if (IsSteepSlope(ti->tileh)) {
2595 DrawShoreTile(ti->tileh);
2596 image = 0;
2597 } else {
2598 image = SPR_FLAT_WATER_TILE;
2600 } else {
2601 switch (rgt) {
2602 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2603 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2604 default: image = SPR_FLAT_GRASS_TILE; break;
2606 image += SlopeToSpriteOffset(ti->tileh);
2608 } else {
2609 if (ti->tileh != SLOPE_FLAT) {
2610 /* track on non-flat ground */
2611 image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
2612 } else {
2613 /* track on flat ground */
2614 (image = rti->base_sprites.track_y, track == TRACK_BIT_Y) ||
2615 (image++, track == TRACK_BIT_X) ||
2616 (image++, track == TRACK_BIT_UPPER) ||
2617 (image++, track == TRACK_BIT_LOWER) ||
2618 (image++, track == TRACK_BIT_RIGHT) ||
2619 (image++, track == TRACK_BIT_LEFT) ||
2620 (image++, track == TRACK_BIT_CROSS) ||
2622 (image = rti->base_sprites.track_ns, track == TRACK_BIT_HORZ) ||
2623 (image++, track == TRACK_BIT_VERT) ||
2625 (junction = true, false) ||
2626 (image = rti->base_sprites.ground, (track & TRACK_BIT_3WAY_NE) == 0) ||
2627 (image++, (track & TRACK_BIT_3WAY_SW) == 0) ||
2628 (image++, (track & TRACK_BIT_3WAY_NW) == 0) ||
2629 (image++, (track & TRACK_BIT_3WAY_SE) == 0) ||
2630 (image++, true);
2633 switch (rgt) {
2634 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2635 case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
2636 case RAIL_GROUND_WATER: {
2637 /* three-corner-raised slope */
2638 DrawShoreTile(ti->tileh);
2639 Corner track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2640 sub = &(_halftile_sub_sprite[track_corner]);
2641 break;
2643 default: break;
2647 if (image != 0) DrawGroundSprite(image, pal, sub);
2649 /* Draw track pieces individually for junction tiles */
2650 if (junction) {
2651 if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
2652 if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
2653 if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
2654 if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
2655 if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
2656 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
2659 /* PBS debugging, draw reserved tracks darker */
2660 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
2661 /* Get reservation, but mask track on halftile slope */
2662 TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
2663 if (pbs & TRACK_BIT_X) {
2664 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2665 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2666 } else {
2667 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2670 if (pbs & TRACK_BIT_Y) {
2671 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2672 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2673 } else {
2674 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2677 if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
2678 if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
2679 if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
2680 if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
2683 if (IsValidCorner(halftile_corner)) {
2684 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2686 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2687 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2688 image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
2689 pal = PAL_NONE;
2690 switch (rgt) {
2691 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2692 case RAIL_GROUND_ICE_DESERT:
2693 case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
2694 default: break;
2696 DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
2698 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
2699 static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
2700 DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, -(int)TILE_HEIGHT);
2704 /* Draw track overgrowth */
2705 if (_settings_client.gui.show_track_overgrowth) DrawTrackGrowth(ti, track);
2708 static void DrawSignals(TileIndex tile, TrackBits rails, const RailtypeInfo *rti)
2710 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2712 if (!(rails & TRACK_BIT_Y)) {
2713 if (!(rails & TRACK_BIT_X)) {
2714 if (rails & TRACK_BIT_LEFT) {
2715 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
2716 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
2718 if (rails & TRACK_BIT_RIGHT) {
2719 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
2720 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
2722 if (rails & TRACK_BIT_UPPER) {
2723 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
2724 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
2726 if (rails & TRACK_BIT_LOWER) {
2727 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
2728 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
2730 } else {
2731 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
2732 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
2734 } else {
2735 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
2736 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
2740 static void DrawTile_Track(TileInfo *ti)
2742 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2744 _drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
2746 if (IsPlainRail(ti->tile)) {
2747 TrackBits rails = GetTrackBits(ti->tile);
2749 DrawTrackBits(ti, rails);
2751 if (HasBit(_display_opt, DO_RAIL_FENCES)) DrawTrackDetails(ti, rti);
2753 DrawOverlay(ti, MP_RAILWAY);
2755 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2758 if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails, rti);
2759 } else {
2760 /* draw depot */
2761 const DrawTileSprites *dts;
2762 PaletteID pal = PAL_NONE;
2763 SpriteID relocation;
2765 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
2767 if (IsInvisibilitySet(TO_BUILDINGS)) {
2768 /* Draw rail instead of depot */
2769 dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
2770 } else {
2771 dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
2774 SpriteID image;
2775 if (rti->UsesOverlay()) {
2776 image = SPR_FLAT_GRASS_TILE;
2777 } else {
2778 image = dts->ground.sprite;
2779 if (image != SPR_FLAT_GRASS_TILE) image += rti->GetRailtypeSpriteOffset();
2782 /* adjust ground tile for desert
2783 * don't adjust for snow, because snow in depots looks weird */
2784 if (IsSnowRailGround(ti->tile) && _settings_game.game_creation.landscape == LT_TROPIC) {
2785 if (image != SPR_FLAT_GRASS_TILE) {
2786 image += rti->snow_offset; // tile with tracks
2787 } else {
2788 image = SPR_FLAT_SNOW_DESERT_TILE; // flat ground
2792 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
2794 if (rti->UsesOverlay()) {
2795 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2797 switch (GetRailDepotDirection(ti->tile)) {
2798 case DIAGDIR_NE:
2799 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2800 FALLTHROUGH;
2801 case DIAGDIR_SW:
2802 DrawGroundSprite(ground + RTO_X, PAL_NONE);
2803 break;
2804 case DIAGDIR_NW:
2805 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2806 FALLTHROUGH;
2807 case DIAGDIR_SE:
2808 DrawGroundSprite(ground + RTO_Y, PAL_NONE);
2809 break;
2810 default:
2811 break;
2814 if (_settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2815 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2817 switch (GetRailDepotDirection(ti->tile)) {
2818 case DIAGDIR_NE:
2819 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2820 FALLTHROUGH;
2821 case DIAGDIR_SW:
2822 DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2823 break;
2824 case DIAGDIR_NW:
2825 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2826 FALLTHROUGH;
2827 case DIAGDIR_SE:
2828 DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2829 break;
2830 default:
2831 break;
2834 } else {
2835 /* PBS debugging, draw reserved tracks darker */
2836 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2837 switch (GetRailDepotDirection(ti->tile)) {
2838 case DIAGDIR_NE:
2839 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2840 FALLTHROUGH;
2841 case DIAGDIR_SW:
2842 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2843 break;
2844 case DIAGDIR_NW:
2845 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2846 FALLTHROUGH;
2847 case DIAGDIR_SE:
2848 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2849 break;
2850 default:
2851 break;
2855 int depot_sprite = GetCustomRailSprite(rti, ti->tile, RTSG_DEPOT);
2856 relocation = depot_sprite != 0 ? depot_sprite - SPR_RAIL_DEPOT_SE_1 : rti->GetRailtypeSpriteOffset();
2858 DrawOverlay(ti, MP_RAILWAY);
2860 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2862 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, _drawtile_track_palette);
2864 DrawBridgeMiddle(ti);
2867 void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
2869 const DrawTileSprites *dts = &_depot_gfx_table[dir];
2870 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
2871 SpriteID image = rti->UsesOverlay() ? SPR_FLAT_GRASS_TILE : dts->ground.sprite;
2872 uint32 offset = rti->GetRailtypeSpriteOffset();
2874 if (image != SPR_FLAT_GRASS_TILE) image += offset;
2875 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
2877 DrawSprite(image, PAL_NONE, x, y);
2879 if (rti->UsesOverlay()) {
2880 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2882 switch (dir) {
2883 case DIAGDIR_SW: DrawSprite(ground + RTO_X, PAL_NONE, x, y); break;
2884 case DIAGDIR_SE: DrawSprite(ground + RTO_Y, PAL_NONE, x, y); break;
2885 default: break;
2888 int depot_sprite = GetCustomRailSprite(rti, INVALID_TILE, RTSG_DEPOT);
2889 if (depot_sprite != 0) offset = depot_sprite - SPR_RAIL_DEPOT_SE_1;
2891 DrawRailTileSeqInGUI(x, y, dts, offset, 0, palette);
2894 static int GetSlopePixelZ_Track(TileIndex tile, uint x, uint y)
2896 if (IsPlainRail(tile)) {
2897 int z;
2898 Slope tileh = GetTilePixelSlope(tile, &z);
2899 if (tileh == SLOPE_FLAT) return z;
2901 z += ApplyPixelFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
2902 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2903 } else {
2904 return GetTileMaxPixelZ(tile);
2908 static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
2910 return IsPlainRail(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
2913 void AgeTrack(TileIndex ti)
2915 assert(IsPlainRailTile(ti));
2917 byte age = GetRailAge(ti);
2919 const byte maxi = 255;
2920 if (age == maxi)
2921 return;
2923 byte inv = maxi - age;
2925 static byte shift = 7;
2926 byte delta = max(1, inv >> shift);
2927 inv -= delta;
2929 age = maxi - inv;
2931 byte old_growth = GetTrackGrowthPhase(ti);
2933 SetRailAge(ti, age);
2935 /* If rounded growth amount changes, redraw */
2936 if (GetTrackGrowthPhase(ti) != old_growth)
2937 MarkTileDirtyByTile(ti);
2940 static void TileLoop_Track(TileIndex tile)
2942 if (IsPlainRailTile(tile)) AgeTrack(tile);
2944 RailGroundType old_ground = GetRailGroundType(tile);
2945 RailGroundType new_ground;
2947 if (old_ground == RAIL_GROUND_WATER) {
2948 TileLoop_Water(tile);
2949 return;
2952 switch (_settings_game.game_creation.landscape) {
2953 case LT_ARCTIC: {
2954 int z;
2955 Slope slope = GetTileSlope(tile, &z);
2956 bool half = false;
2958 /* for non-flat track, use lower part of track
2959 * in other cases, use the highest part with track */
2960 if (IsPlainRail(tile)) {
2961 TrackBits track = GetTrackBits(tile);
2962 Foundation f = GetRailFoundation(slope, track);
2964 switch (f) {
2965 case FOUNDATION_NONE:
2966 /* no foundation - is the track on the upper side of three corners raised tile? */
2967 if (slope != SLOPE_FLAT) z++;
2968 break;
2970 case FOUNDATION_INCLINED_X:
2971 case FOUNDATION_INCLINED_Y:
2972 /* sloped track - is it on a steep slope? */
2973 if (IsSteepSlope(slope)) z++;
2974 break;
2976 case FOUNDATION_STEEP_LOWER:
2977 /* only lower part of steep slope */
2978 z++;
2979 break;
2981 default:
2982 /* if it is a steep slope, then there is a track on higher part */
2983 if (IsSteepSlope(slope)) z++;
2984 z++;
2985 break;
2988 half = IsInsideMM(f, FOUNDATION_STEEP_BOTH, FOUNDATION_HALFTILE_N + 1);
2989 } else {
2990 /* is the depot on a non-flat tile? */
2991 if (slope != SLOPE_FLAT) z++;
2994 /* 'z' is now the lowest part of the highest track bit -
2995 * for sloped track, it is 'z' of lower part
2996 * for two track bits, it is 'z' of higher track bit
2997 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2998 if (z > GetSnowLine()) {
2999 if (half && z - GetSnowLine() == 1) {
3000 /* track on non-continuous foundation, lower part is not under snow */
3001 new_ground = RAIL_GROUND_HALF_SNOW;
3002 } else {
3003 new_ground = RAIL_GROUND_ICE_DESERT;
3005 goto set_ground;
3007 break;
3010 case LT_TROPIC:
3011 if (GetTropicZone(tile) == TROPICZONE_DESERT) {
3012 new_ground = RAIL_GROUND_ICE_DESERT;
3013 goto set_ground;
3015 break;
3018 new_ground = RAIL_GROUND_GRASS;
3020 if (IsPlainRail(tile) && old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
3021 /* determine direction of fence */
3022 TrackBits rail = GetTrackBits(tile);
3024 Owner owner = GetTileOwner(tile);
3025 byte fences = 0;
3027 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
3028 static const TrackBits dir_to_trackbits[DIAGDIR_END] = {TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW};
3030 /* Track bit on this edge => no fence. */
3031 if ((rail & dir_to_trackbits[d]) != TRACK_BIT_NONE) continue;
3033 TileIndex tile2 = tile + TileOffsByDiagDir(d);
3035 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
3036 if (!IsValidTile(tile2) || IsTileType(tile2, MP_HOUSE) || IsTileType(tile2, MP_INDUSTRY) ||
3037 IsTileType(tile2, MP_ROAD) || (IsTileType(tile2, MP_OBJECT) && !IsObjectType(tile2, OBJECT_OWNED_LAND)) || IsTileType(tile2, MP_TUNNELBRIDGE) || !IsTileOwner(tile2, owner)) {
3038 fences |= 1 << d;
3042 switch (fences) {
3043 case 0: break;
3044 case (1 << DIAGDIR_NE): new_ground = RAIL_GROUND_FENCE_NE; break;
3045 case (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_SE; break;
3046 case (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_SW; break;
3047 case (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_NW; break;
3048 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_NESW; break;
3049 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_SENW; break;
3050 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_VERT1; break;
3051 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
3052 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
3053 case (1 << DIAGDIR_SW) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_VERT2; break;
3054 default: NOT_REACHED();
3058 set_ground:
3059 if (old_ground != new_ground) {
3060 SetRailGroundType(tile, new_ground);
3061 MarkTileDirtyByTile(tile);
3066 static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3068 /* Case of half tile slope with water. */
3069 if (mode == TRANSPORT_WATER && IsPlainRail(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
3070 TrackBits tb = GetTrackBits(tile);
3071 switch (tb) {
3072 default: NOT_REACHED();
3073 case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
3074 case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
3075 case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
3076 case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
3078 return CombineTrackStatus(TrackBitsToTrackdirBits(tb), TRACKDIR_BIT_NONE);
3081 if (mode != TRANSPORT_RAIL) return 0;
3083 TrackBits trackbits = TRACK_BIT_NONE;
3084 TrackdirBits red_signals = TRACKDIR_BIT_NONE;
3086 switch (GetRailTileType(tile)) {
3087 default: NOT_REACHED();
3088 case RAIL_TILE_NORMAL:
3089 trackbits = GetTrackBits(tile);
3090 break;
3092 case RAIL_TILE_SIGNALS: {
3093 trackbits = GetTrackBits(tile);
3094 byte a = GetPresentSignals(tile);
3095 uint b = GetSignalStates(tile);
3097 b &= a;
3099 /* When signals are not present (in neither direction),
3100 * we pretend them to be green. Otherwise, it depends on
3101 * the signal type. For signals that are only active from
3102 * one side, we set the missing signals explicitly to
3103 * `green'. Otherwise, they implicitly become `red'. */
3104 if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
3105 if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
3107 if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
3108 if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
3109 if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
3110 if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
3112 break;
3115 case RAIL_TILE_DEPOT: {
3116 DiagDirection dir = GetRailDepotDirection(tile);
3118 if (side != INVALID_DIAGDIR && side != dir) break;
3120 trackbits = DiagDirToDiagTrackBits(dir);
3121 break;
3125 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
3128 static bool ClickTile_Track(TileIndex tile)
3130 if (_ctrl_pressed && IsPlainRailTile(tile)) {
3131 TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
3133 if (trackbits & TRACK_BIT_VERT) { // N-S direction
3134 trackbits = (_tile_fract_coords.x <= _tile_fract_coords.y) ? TRACK_BIT_RIGHT : TRACK_BIT_LEFT;
3137 if (trackbits & TRACK_BIT_HORZ) { // E-W direction
3138 trackbits = (_tile_fract_coords.x + _tile_fract_coords.y <= 15) ? TRACK_BIT_UPPER : TRACK_BIT_LOWER;
3141 Track track = FindFirstTrack(trackbits);
3142 if (HasTrack(tile, track) && HasSignalOnTrack(tile, track)) {
3143 if (GetSignalType(tile, track) == SIGTYPE_LOGIC) {
3144 SignalProgram* program = FindSignalProgram(tile, track);
3145 if (program != nullptr) {
3146 ShowSignalProgramWindow(program);
3148 } else {
3149 ShowTraceRestrictProgramWindow(tile, track);
3151 return true;
3155 if (!IsRailDepot(tile)) return false;
3157 ShowDepotWindow(tile, VEH_TRAIN);
3158 return true;
3161 static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
3163 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3164 td->rail_speed = rti->max_speed;
3165 td->railtype = rti->strings.name;
3166 td->owner[0] = GetTileOwner(tile);
3167 switch (GetRailTileType(tile)) {
3168 case RAIL_TILE_NORMAL:
3169 td->str = STR_LAI_RAIL_DESCRIPTION_TRACK;
3170 break;
3172 case RAIL_TILE_SIGNALS: {
3173 static const StringID signal_type[SIGTYPE_END][SIGTYPE_END] = {
3175 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS,
3176 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
3177 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
3178 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
3179 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
3180 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
3181 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_LOGICSIGNALS
3184 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
3185 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS,
3186 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
3187 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
3188 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
3189 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
3190 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_LOGICSIGNALS
3193 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
3194 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
3195 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS,
3196 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
3197 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
3198 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
3199 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_LOGICSIGNALS
3202 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
3203 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
3204 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
3205 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS,
3206 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
3207 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
3208 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_LOGICSIGNALS
3211 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
3212 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
3213 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
3214 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
3215 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS,
3216 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
3217 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_LOGICSIGNALS
3220 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
3221 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
3222 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
3223 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
3224 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
3225 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS,
3226 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRY_LOGICSIGNALS
3229 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_LOGICSIGNALS,
3230 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_LOGICSIGNALS,
3231 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_LOGICSIGNALS,
3232 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_LOGICSIGNALS,
3233 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_LOGICSIGNALS,
3234 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRY_LOGICSIGNALS,
3235 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_LOGICSIGNALS
3239 SignalType primary_signal;
3240 SignalType secondary_signal;
3241 if (HasSignalOnTrack(tile, TRACK_UPPER)) {
3242 primary_signal = GetSignalType(tile, TRACK_UPPER);
3243 secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
3244 } else {
3245 secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
3248 td->str = signal_type[secondary_signal][primary_signal];
3250 if (IsRestrictedSignal(tile)) {
3251 SetDParamX(td->dparam, 0, td->str);
3252 SetDParamX(td->dparam, 1, rti->strings.name);
3253 td->str = STR_LAI_RAIL_DESCRIPTION_RESTRICTED_SIGNAL;
3255 break;
3258 case RAIL_TILE_DEPOT:
3259 td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
3260 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
3261 if (td->rail_speed > 0) {
3262 td->rail_speed = min(td->rail_speed, 61);
3263 } else {
3264 td->rail_speed = 61;
3267 td->build_date = Depot::GetByTile(tile)->build_date;
3268 break;
3270 default:
3271 NOT_REACHED();
3275 static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
3277 if (!IsTileOwner(tile, old_owner)) return;
3279 if (new_owner != INVALID_OWNER) {
3280 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
3281 uint num_pieces = 1;
3282 if (IsPlainRail(tile)) {
3283 TrackBits bits = GetTrackBits(tile);
3284 num_pieces = CountBits(bits);
3285 if (TracksOverlap(bits)) num_pieces *= num_pieces;
3287 RailType rt = GetRailType(tile);
3288 Company::Get(old_owner)->infrastructure.rail[rt] -= num_pieces;
3289 Company::Get(new_owner)->infrastructure.rail[rt] += num_pieces;
3291 if (HasSignals(tile)) {
3292 uint num_sigs = CountBits(GetPresentSignals(tile));
3293 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
3294 Company::Get(new_owner)->infrastructure.signal += num_sigs;
3297 SetTileOwner(tile, new_owner);
3298 } else {
3299 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
3303 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
3304 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
3305 static const int8 _deltacoord_leaveoffset[8] = {
3306 -1, 0, 1, 0, /* x */
3307 0, 1, 0, -1 /* y */
3312 * Compute number of ticks when next wagon will leave a depot.
3313 * Negative means next wagon should have left depot n ticks before.
3314 * @param v vehicle outside (leaving) the depot
3315 * @return number of ticks when the next wagon will leave
3317 int TicksToLeaveDepot(const Train *v)
3319 DiagDirection dir = GetRailDepotDirection(v->tile);
3320 int length = v->CalcNextVehicleOffset();
3322 switch (dir) {
3323 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
3324 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
3325 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
3326 default:
3327 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
3330 return 0; // make compilers happy
3334 * Tile callback routine when vehicle enters tile
3335 * @see vehicle_enter_tile_proc
3337 static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int x, int y)
3339 /* this routine applies only to trains in depot tiles */
3340 if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
3342 Train *v = Train::From(u);
3344 /* depot direction */
3345 DiagDirection dir = GetRailDepotDirection(tile);
3347 /* Calculate the point where the following wagon should be activated. */
3348 int length = v->CalcNextVehicleOffset();
3350 byte fract_coord_leave =
3351 ((_fractcoords_enter[dir] & 0x0F) + // x
3352 (length + 1) * _deltacoord_leaveoffset[dir]) +
3353 (((_fractcoords_enter[dir] >> 4) + // y
3354 ((length + 1) * _deltacoord_leaveoffset[dir + 4])) << 4);
3356 byte fract_coord = (x & 0xF) + ((y & 0xF) << 4);
3358 if (_fractcoords_behind[dir] == fract_coord) {
3359 /* make sure a train is not entering the tile from behind */
3360 return VETSB_CANNOT_ENTER;
3361 } else if (_fractcoords_enter[dir] == fract_coord) {
3362 if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) {
3363 /* enter the depot */
3364 v->track = TRACK_BIT_DEPOT,
3365 v->vehstatus |= VS_HIDDEN; // hide it
3366 v->direction = ReverseDir(v->direction);
3367 if (v->Next() == NULL) VehicleEnterDepot(v->First());
3368 v->tile = tile;
3370 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
3371 return VETSB_ENTERED_WORMHOLE;
3373 } else if (fract_coord_leave == fract_coord) {
3374 if (DiagDirToDir(dir) == v->direction) {
3375 /* leave the depot? */
3376 if ((v = v->Next()) != NULL) {
3377 v->vehstatus &= ~VS_HIDDEN;
3378 v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
3383 return VETSB_CONTINUE;
3387 * Tests if autoslope is allowed.
3389 * @param tile The tile.
3390 * @param flags Terraform command flags.
3391 * @param z_old Old TileZ.
3392 * @param tileh_old Old TileSlope.
3393 * @param z_new New TileZ.
3394 * @param tileh_new New TileSlope.
3395 * @param rail_bits Trackbits.
3397 static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old, Slope tileh_old, int z_new, Slope tileh_new, TrackBits rail_bits)
3399 if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3401 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
3402 if (CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3404 /* Get the slopes on top of the foundations */
3405 z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
3406 z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
3408 Corner track_corner;
3409 switch (rail_bits) {
3410 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
3411 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
3412 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
3413 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
3415 /* Surface slope must not be changed */
3416 default:
3417 if (z_old != z_new || tileh_old != tileh_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3418 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3421 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
3422 z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
3423 z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
3424 if (z_old != z_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3426 CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3427 /* Make the ground dirty, if surface slope has changed */
3428 if (tileh_old != tileh_new) {
3429 /* If there is flat water on the lower halftile add the cost for clearing it */
3430 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price[PR_CLEAR_WATER]);
3431 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3433 return cost;
3437 * Test-procedure for HasVehicleOnPos to check for a ship.
3439 static Vehicle *EnsureNoShipProc(Vehicle *v, void *data)
3441 return v->type == VEH_SHIP ? v : NULL;
3444 static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3446 int z_old;
3447 Slope tileh_old = GetTileSlope(tile, &z_old);
3448 if (IsPlainRail(tile)) {
3449 TrackBits rail_bits = GetTrackBits(tile);
3450 /* Is there flat water on the lower halftile that must be cleared expensively? */
3451 bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
3453 /* Allow clearing the water only if there is no ship */
3454 if (was_water && HasVehicleOnPos(tile, NULL, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
3456 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
3457 CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
3459 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
3460 Corner allowed_corner;
3461 switch (rail_bits) {
3462 case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
3463 case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
3464 case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
3465 case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
3466 default: return autoslope_result;
3469 Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
3471 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3472 if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
3474 /* Everything is valid, which only changes allowed_corner */
3475 for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
3476 if (allowed_corner == corner) continue;
3477 if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
3480 /* Make the ground dirty */
3481 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3483 /* allow terraforming */
3484 return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0);
3485 } else if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() &&
3486 AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) {
3487 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3489 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3493 extern const TileTypeProcs _tile_type_rail_procs = {
3494 DrawTile_Track, // draw_tile_proc
3495 GetSlopePixelZ_Track, // get_slope_z_proc
3496 ClearTile_Track, // clear_tile_proc
3497 NULL, // add_accepted_cargo_proc
3498 GetTileDesc_Track, // get_tile_desc_proc
3499 GetTileTrackStatus_Track, // get_tile_track_status_proc
3500 ClickTile_Track, // click_tile_proc
3501 NULL, // animate_tile_proc
3502 TileLoop_Track, // tile_loop_proc
3503 ChangeTileOwner_Track, // change_tile_owner_proc
3504 NULL, // add_produced_cargo_proc
3505 VehicleEnter_Track, // vehicle_enter_tile_proc
3506 GetFoundation_Track, // get_foundation_proc
3507 TerraformTile_Track, // terraform_tile_proc