Rework the way the ReinitSeparation command is called. The old way was way too danger...
[openttd-joker.git] / src / rail_cmd.cpp
blob21308cc83d9c74a6d4c7ecc20f715ba72bc8ae5b
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 * Resolve sprites of custom rail types
135 void InitRailTypes()
137 // If this is compatible/has power on a legacy railtype, then it is compatible with everything compatible with that legacy type.
138 // This ensures multiple track sets are fully compatible not just with legacy but also with eachother.
139 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
140 RailtypeInfo *rti = &_railtypes[rt];
142 assert(rti != nullptr);
144 for (RailType legacy_rt = RAILTYPE_RAIL; legacy_rt <= RAILTYPE_MAGLEV; legacy_rt++) {
145 RailtypeInfo *legacy_rti = &_railtypes[legacy_rt];
147 assert(legacy_rti != nullptr);
149 if (IsCompatibleRail(rt, legacy_rt)) {
150 rti->compatible_railtypes |= legacy_rti->compatible_railtypes;
153 if (HasPowerOnRail(rt, legacy_rt)) {
154 // If this has power on a legacy railtype, then it has power on everything compatible with that legacy type.
155 // This ensures multiple track sets are fully compatible not just with legacy but also with eachother.
156 rti->powered_railtypes |= legacy_rti->powered_railtypes;
161 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
162 RailtypeInfo *rti = &_railtypes[rt];
163 ResolveRailTypeGUISprites(rti);
166 _sorted_railtypes_size = 0;
167 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
168 if (_railtypes[rt].label != 0) {
169 _sorted_railtypes[_sorted_railtypes_size++] = rt;
173 // Sort by compatibility and max speed.
174 std::sort(std::begin(_sorted_railtypes), std::begin(_sorted_railtypes) + _sorted_railtypes_size, [](RailType first, RailType second)
176 RailType rt[2] = { first, second };
177 uint sort_value[2];
179 for (int i = 0; i < 2; ++i) {
180 sort_value[i] = (GetRailTypeInfo(rt[i])->max_speed != 0) ? GetRailTypeInfo(rt[i])->max_speed : UINT16_MAX;
182 if (!HasPowerOnRail(rt[i], RAILTYPE_RAIL)) {
183 sort_value[i] += (1 << 16);
185 if (!HasPowerOnRail(rt[i], RAILTYPE_ELECTRIC)) {
186 sort_value[i] += (1 << 17);
188 if (!HasPowerOnRail(rt[i], RAILTYPE_MONO)) {
189 sort_value[i] += (1 << 18);
191 if (!HasPowerOnRail(rt[i], RAILTYPE_MAGLEV)) {
192 sort_value[i] += (1 << 19);
199 return sort_value[0] < sort_value[1];
204 * Allocate a new rail type label
206 RailType AllocateRailType(RailTypeLabel label)
208 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
209 RailtypeInfo *rti = &_railtypes[rt];
211 if (rti->label == 0) {
212 /* Set up new rail type */
213 *rti = _original_railtypes[RAILTYPE_RAIL];
214 rti->label = label;
215 rti->alternate_labels.Clear();
217 /* Make us compatible with ourself. */
218 rti->powered_railtypes = (RailTypes)(1 << rt);
219 rti->compatible_railtypes = (RailTypes)(1 << rt);
221 /* We also introduce ourself. */
222 rti->introduces_railtypes = (RailTypes)(1 << rt);
224 /* Default sort order; order of allocation, but with some
225 * offsets so it's easier for NewGRF to pick a spot without
226 * changing the order of other (original) rail types.
227 * The << is so you can place other railtypes in between the
228 * other railtypes, the 7 is to be able to place something
229 * before the first (default) rail type. */
230 rti->sorting_order = rt << 4 | 7;
231 return rt;
235 return INVALID_RAILTYPE;
238 static const byte _track_sloped_sprites[14] = {
239 14, 15, 22, 13,
240 0, 21, 17, 12,
241 23, 0, 18, 20,
242 19, 16
246 /* 4
247 * ---------
248 * |\ /|
249 * | \ 1/ |
250 * | \ / |
251 * | \ / |
252 * 16| \ |32
253 * | / \2 |
254 * | / \ |
255 * | / \ |
256 * |/ \|
257 * ---------
263 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
264 * MAP3LO byte: abcd???? => Signal Exists?
265 * a and b are for diagonals, upper and left,
266 * one for each direction. (ie a == NE->SW, b ==
267 * SW->NE, or v.v., I don't know. b and c are
268 * similar for lower and right.
269 * MAP2 byte: ????abcd => Type of ground.
270 * MAP3LO byte: ????abcd => Type of rail.
271 * MAP5: 00abcdef => rail
272 * 01abcdef => rail w/ signals
273 * 10uuuuuu => unused
274 * 11uuuudd => rail depot
278 * Tests if a vehicle interacts with the specified track.
279 * All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
281 * @param tile The tile.
282 * @param track The track.
283 * @return Succeeded command (no train found), or a failed command (a train was found).
285 static CommandCost EnsureNoTrainOnTrack(TileIndex tile, Track track)
287 TrackBits rail_bits = TrackToTrackBits(track);
288 return EnsureNoTrainOnTrackBits(tile, rail_bits);
292 * Check that the new track bits may be built.
293 * @param tile %Tile to build on.
294 * @param to_build New track bits.
295 * @param flags Flags of the operation.
296 * @return Succeeded or failed command.
298 static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
300 if (!IsPlainRail(tile)) return CommandError(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
302 /* So, we have a tile with tracks on it (and possibly signals). Let's see
303 * what tracks first */
304 TrackBits current = GetTrackBits(tile); // The current track layout.
305 TrackBits future = current | to_build; // The track layout we want to build.
307 /* Are we really building something new? */
308 if (current == future) {
309 /* Nothing new is being built */
310 return CommandError(STR_ERROR_ALREADY_BUILT);
313 /* Let's see if we may build this */
314 if ((flags & DC_NO_RAIL_OVERLAP) || HasSignals(tile)) {
315 /* If we are not allowed to overlap (flag is on for ai companies or we have
316 * signals on the tile), check that */
317 if (future != TRACK_BIT_HORZ && future != TRACK_BIT_VERT) {
318 return CommandError((flags & DC_NO_RAIL_OVERLAP) ? STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION : STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
321 /* Normally, we may overlap and any combination is valid */
322 return CommandCost();
326 /** Valid TrackBits on a specific (non-steep)-slope without foundation */
327 static const TrackBits _valid_tracks_without_foundation[15] = {
328 TRACK_BIT_ALL,
329 TRACK_BIT_RIGHT,
330 TRACK_BIT_UPPER,
331 TRACK_BIT_X,
333 TRACK_BIT_LEFT,
334 TRACK_BIT_NONE,
335 TRACK_BIT_Y,
336 TRACK_BIT_LOWER,
338 TRACK_BIT_LOWER,
339 TRACK_BIT_Y,
340 TRACK_BIT_NONE,
341 TRACK_BIT_LEFT,
343 TRACK_BIT_X,
344 TRACK_BIT_UPPER,
345 TRACK_BIT_RIGHT,
348 /** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
349 static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
350 TRACK_BIT_NONE,
351 TRACK_BIT_LEFT,
352 TRACK_BIT_LOWER,
353 TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
355 TRACK_BIT_RIGHT,
356 TRACK_BIT_ALL,
357 TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
358 TRACK_BIT_ALL,
360 TRACK_BIT_UPPER,
361 TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
362 TRACK_BIT_ALL,
363 TRACK_BIT_ALL,
365 TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
366 TRACK_BIT_ALL,
367 TRACK_BIT_ALL
371 * Checks if a track combination is valid on a specific slope and returns the needed foundation.
373 * @param tileh Tile slope.
374 * @param bits Trackbits.
375 * @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
377 Foundation GetRailFoundation(Slope tileh, TrackBits bits)
379 if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
381 if (IsSteepSlope(tileh)) {
382 /* Test for inclined foundations */
383 if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
384 if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
386 /* Get higher track */
387 Corner highest_corner = GetHighestSlopeCorner(tileh);
388 TrackBits higher_track = CornerToTrackBits(highest_corner);
390 /* Only higher track? */
391 if (bits == higher_track) return HalftileFoundation(highest_corner);
393 /* Overlap with higher track? */
394 if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
396 /* either lower track or both higher and lower track */
397 return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
398 } else {
399 if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
401 bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
403 Corner track_corner;
404 switch (bits) {
405 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
406 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
407 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
408 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
410 case TRACK_BIT_HORZ:
411 if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
412 if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
413 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
415 case TRACK_BIT_VERT:
416 if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
417 if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
418 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
420 case TRACK_BIT_X:
421 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
422 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
424 case TRACK_BIT_Y:
425 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
426 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
428 default:
429 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
431 /* Single diagonal track */
433 /* Track must be at least valid on leveled foundation */
434 if (!valid_on_leveled) return FOUNDATION_INVALID;
436 /* If slope has three raised corners, build leveled foundation */
437 if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
439 /* If neighboured corners of track_corner are lowered, build halftile foundation */
440 if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
442 /* else special anti-zig-zag foundation */
443 return SpecialRailFoundation(track_corner);
449 * Tests if a track can be build on a tile.
451 * @param tileh Tile slope.
452 * @param rail_bits Tracks to build.
453 * @param existing Tracks already built.
454 * @param tile Tile (used for water test)
455 * @return Error message or cost for foundation building.
457 static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
459 /* don't allow building on the lower side of a coast */
460 if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
461 if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return CommandError(STR_ERROR_CAN_T_BUILD_ON_WATER);
464 Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
466 /* check track/slope combination */
467 if ((f_new == FOUNDATION_INVALID) ||
468 ((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
469 return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
472 Foundation f_old = GetRailFoundation(tileh, existing);
473 return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
476 /* Validate functions for rail building */
477 static inline bool ValParamTrackOrientation(Track track)
479 return IsValidTrack(track);
483 * Build a single piece of rail
484 * @param tile tile to build on
485 * @param flags operation to perform
486 * @param p1 railtype of being built piece (normal, mono, maglev)
487 * @param p2 rail track to build
488 * @param text unused
489 * @return the cost of this operation or an error
491 CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
493 RailType railtype = Extract<RailType, 0, 5>(p1);
494 Track track = Extract<Track, 0, 3>(p2);
495 CommandCost cost(EXPENSES_CONSTRUCTION);
497 _rail_track_endtile = INVALID_TILE;
499 if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CommandError();
501 Slope tileh = GetTileSlope(tile);
502 TrackBits trackbit = TrackToTrackBits(track);
504 switch (GetTileType(tile)) {
505 case MP_RAILWAY: {
506 CommandCost ret = CheckTileOwnership(tile);
507 if (ret.Failed()) return ret;
509 if (!IsPlainRail(tile)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); // just get appropriate error message
511 if (!IsCompatibleRail(GetRailType(tile), railtype)) return CommandError(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
513 ret = CheckTrackCombination(tile, trackbit, flags);
514 if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
515 if (ret.Failed()) {
516 if (ret.GetErrorMessage() == STR_ERROR_ALREADY_BUILT) _rail_track_endtile = tile;
517 return ret;
520 ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
521 if (ret.Failed()) return ret;
522 cost.AddCost(ret);
524 /* If the rail types don't match, try to convert only if engines of
525 * the new rail type are not powered on the present rail type and engines of
526 * the present rail type are powered on the new rail type. */
527 if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
528 if (HasPowerOnRail(GetRailType(tile), railtype)) {
529 ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
530 if (ret.Failed()) return ret;
531 cost.AddCost(ret);
532 } else {
533 return CommandError();
537 if (flags & DC_EXEC) {
538 SetRailGroundType(tile, RAIL_GROUND_BARREN);
539 TrackBits bits = GetTrackBits(tile);
540 SetTrackBits(tile, bits | trackbit);
541 ResetRailAge(tile);
542 /* Subtract old infrastructure count. */
543 uint pieces = CountBits(bits);
544 if (TracksOverlap(bits)) pieces *= pieces;
545 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
546 /* Add new infrastructure count. */
547 pieces = CountBits(bits | trackbit);
548 if (TracksOverlap(bits | trackbit)) pieces *= pieces;
549 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
550 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
552 break;
555 case MP_ROAD: {
556 /* Level crossings may only be built on these slopes */
557 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return CommandError(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
559 CommandCost ret = EnsureNoVehicleOnGround(tile);
560 if (ret.Failed()) return ret;
562 if (IsNormalRoad(tile)) {
563 if (HasRoadWorks(tile)) return CommandError(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
565 if (GetDisallowedRoadDirections(tile) != DRD_NONE) return CommandError(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
567 if (RailNoLevelCrossings(railtype)) return CommandError(STR_ERROR_CROSSING_DISALLOWED);
569 RoadTypes roadtypes = GetRoadTypes(tile);
570 RoadBits road = GetRoadBits(tile, ROADTYPE_ROAD);
571 RoadBits tram = GetRoadBits(tile, ROADTYPE_TRAM);
572 if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
573 (track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
574 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
575 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
576 /* Disallow breaking end-of-line of someone else
577 * so trams can still reverse on this tile. */
578 if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
579 CommandCost ret = CheckOwnership(tram_owner);
580 if (ret.Failed()) return ret;
582 /* Crossings must always have a road... */
583 uint num_new_road_pieces = 2 - CountBits(road);
584 if (road == ROAD_NONE) road_owner = _current_company;
585 roadtypes |= ROADTYPES_ROAD;
586 /* ...but tram is not required. */
587 uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
589 cost.AddCost((num_new_road_pieces + num_new_tram_pieces) * _price[PR_BUILD_ROAD]);
591 if (flags & DC_EXEC) {
592 MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtypes, GetTownIndex(tile));
593 UpdateLevelCrossing(tile, false);
594 Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
595 DirtyCompanyInfrastructureWindows(_current_company);
596 if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
597 Company::Get(road_owner)->infrastructure.road[ROADTYPE_ROAD] += num_new_road_pieces;
598 DirtyCompanyInfrastructureWindows(road_owner);
600 if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
601 Company::Get(tram_owner)->infrastructure.road[ROADTYPE_TRAM] += num_new_tram_pieces;
602 DirtyCompanyInfrastructureWindows(tram_owner);
605 break;
609 if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
610 _rail_track_endtile = tile;
611 return CommandError(STR_ERROR_ALREADY_BUILT);
614 FALLTHROUGH;
616 default: {
617 /* Will there be flat water on the lower halftile? */
618 bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
620 CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
621 if (ret.Failed()) return ret;
622 cost.AddCost(ret);
624 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
625 if (ret.Failed()) return ret;
626 cost.AddCost(ret);
628 if (water_ground) {
629 cost.AddCost(-_price[PR_CLEAR_WATER]);
630 cost.AddCost(_price[PR_CLEAR_ROUGH]);
633 if (flags & DC_EXEC) {
634 MakeRailNormal(tile, _current_company, trackbit, railtype);
635 if (water_ground) SetRailGroundType(tile, RAIL_GROUND_WATER);
636 Company::Get(_current_company)->infrastructure.rail[railtype]++;
637 DirtyCompanyInfrastructureWindows(_current_company);
639 break;
643 if (flags & DC_EXEC) {
644 MarkTileDirtyByTile(tile);
645 AddTrackToSignalBuffer(tile, track, _current_company);
646 YapfNotifyTrackLayoutChange(tile, track);
649 cost.AddCost(RailBuildCost(railtype));
650 _rail_track_endtile = tile;
651 return cost;
655 * Remove a single piece of track
656 * @param tile tile to remove track from
657 * @param flags operation to perform
658 * @param p1 unused
659 * @param p2 rail orientation
660 * @param text unused
661 * @return the cost of this operation or an error
663 CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
665 Track track = Extract<Track, 0, 3>(p2);
666 CommandCost cost(EXPENSES_CONSTRUCTION);
667 bool crossing = false;
669 _rail_track_endtile = INVALID_TILE;
671 if (!ValParamTrackOrientation(track)) return CommandError();
672 TrackBits trackbit = TrackToTrackBits(track);
674 /* Need to read tile owner now because it may change when the rail is removed
675 * Also, in case of floods, _current_company != owner
676 * There may be invalid tiletype even in exec run (when removing long track),
677 * so do not call GetTileOwner(tile) in any case here */
678 Owner owner = INVALID_OWNER;
680 Train *v = nullptr;
682 switch (GetTileType(tile)) {
683 case MP_ROAD: {
684 if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
686 if (_current_company != OWNER_WATER) {
687 CommandCost ret = CheckTileOwnership(tile);
688 if (ret.Failed()) return ret;
691 if (!(flags & DC_BANKRUPT)) {
692 CommandCost ret = EnsureNoVehicleOnGround(tile);
693 if (ret.Failed()) return ret;
696 cost.AddCost(RailClearCost(GetRailType(tile)));
698 if (flags & DC_EXEC) {
699 if (HasReservedTracks(tile, trackbit)) {
700 v = GetTrainForReservation(tile, track);
701 if (v != nullptr) FreeTrainTrackReservation(v);
703 owner = GetTileOwner(tile);
704 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
705 DirtyCompanyInfrastructureWindows(owner);
706 MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypes(tile), GetTownIndex(tile), GetRoadOwner(tile, ROADTYPE_ROAD), GetRoadOwner(tile, ROADTYPE_TRAM));
707 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
709 break;
712 case MP_RAILWAY: {
713 TrackBits present;
714 /* There are no rails present at depots. */
715 if (!IsPlainRail(tile)) return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
717 if (_current_company != OWNER_WATER) {
718 CommandCost ret = CheckTileOwnership(tile);
719 if (ret.Failed()) return ret;
722 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
723 if (ret.Failed()) return ret;
725 present = GetTrackBits(tile);
726 if ((present & trackbit) == 0) return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
727 if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
729 cost.AddCost(RailClearCost(GetRailType(tile)));
731 /* Charge extra to remove signals on the track, if they are there */
732 if (HasSignalOnTrack(tile, track)) {
733 cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
736 if (flags & DC_EXEC) {
737 if (HasReservedTracks(tile, trackbit)) {
738 v = GetTrainForReservation(tile, track);
739 if (v != nullptr) FreeTrainTrackReservation(v);
742 owner = GetTileOwner(tile);
744 /* Subtract old infrastructure count. */
745 uint pieces = CountBits(present);
746 if (TracksOverlap(present)) pieces *= pieces;
747 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
748 /* Add new infrastructure count. */
749 present ^= trackbit;
750 pieces = CountBits(present);
751 if (TracksOverlap(present)) pieces *= pieces;
752 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
753 DirtyCompanyInfrastructureWindows(owner);
755 if (present == 0) {
756 Slope tileh = GetTileSlope(tile);
757 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
758 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
759 MakeShore(tile);
760 } else {
761 DoClearSquare(tile);
763 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
764 } else {
765 SetTrackBits(tile, present);
766 SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
769 break;
772 default: return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
775 if (flags & DC_EXEC) {
776 /* if we got that far, 'owner' variable is set correctly */
777 assert(Company::IsValidID(owner));
779 MarkTileDirtyByTile(tile);
780 if (crossing) {
781 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
782 * are removing one of these pieces, we'll need to update signals for
783 * both directions explicitly, as after the track is removed it won't
784 * 'connect' with the other piece. */
785 AddTrackToSignalBuffer(tile, TRACK_X, owner);
786 AddTrackToSignalBuffer(tile, TRACK_Y, owner);
787 YapfNotifyTrackLayoutChange(tile, TRACK_X);
788 YapfNotifyTrackLayoutChange(tile, TRACK_Y);
789 } else {
790 AddTrackToSignalBuffer(tile, track, owner);
791 YapfNotifyTrackLayoutChange(tile, track);
794 if (v != nullptr) TryPathReserve(v, true);
797 _rail_track_endtile = tile;
798 return cost;
803 * Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
804 * The function floods the lower halftile, if the tile has a halftile foundation.
806 * @param t The tile to flood.
807 * @return true if something was flooded.
809 bool FloodHalftile(TileIndex t)
811 assert(IsPlainRailTile(t));
813 bool flooded = false;
814 if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
816 Slope tileh = GetTileSlope(t);
817 TrackBits rail_bits = GetTrackBits(t);
819 if (IsSlopeWithOneCornerRaised(tileh)) {
820 TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
822 TrackBits to_remove = lower_track & rail_bits;
823 if (to_remove != 0) {
824 Backup<CompanyByte> cur_company(_current_company, OWNER_WATER, FILE_LINE);
825 flooded = DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL).Succeeded();
826 cur_company.Restore();
827 if (!flooded) return flooded; // not yet floodable
828 rail_bits = rail_bits & ~to_remove;
829 if (rail_bits == 0) {
830 MakeShore(t);
831 MarkTileDirtyByTile(t);
832 return flooded;
836 if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
837 flooded = true;
838 SetRailGroundType(t, RAIL_GROUND_WATER);
839 MarkTileDirtyByTile(t);
841 } else {
842 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
843 if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
844 if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
845 flooded = true;
846 SetRailGroundType(t, RAIL_GROUND_WATER);
847 MarkTileDirtyByTile(t);
851 return flooded;
854 static const TileIndexDiffC _trackdelta[] = {
855 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
856 { 0, 0 },
857 { 0, 0 },
858 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
859 { 0, 0 },
860 { 0, 0 }
864 static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
866 int x = TileX(start);
867 int y = TileY(start);
868 int ex = TileX(end);
869 int ey = TileY(end);
871 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CommandError();
873 /* calculate delta x,y from start to end tile */
874 int dx = ex - x;
875 int dy = ey - y;
877 /* calculate delta x,y for the first direction */
878 int trdx = _trackdelta[*trackdir].x;
879 int trdy = _trackdelta[*trackdir].y;
881 if (!IsDiagonalTrackdir(*trackdir)) {
882 trdx += _trackdelta[*trackdir ^ 1].x;
883 trdy += _trackdelta[*trackdir ^ 1].y;
886 /* validate the direction */
887 while ((trdx <= 0 && dx > 0) ||
888 (trdx >= 0 && dx < 0) ||
889 (trdy <= 0 && dy > 0) ||
890 (trdy >= 0 && dy < 0)) {
891 if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
892 SetBit(*trackdir, 3); // reverse the direction
893 trdx = -trdx;
894 trdy = -trdy;
895 } else { // other direction is invalid too, invalid drag
896 return CommandError();
900 /* (for diagonal tracks, this is already made sure of by above test), but:
901 * for non-diagonal tracks, check if the start and end tile are on 1 line */
902 if (!IsDiagonalTrackdir(*trackdir)) {
903 trdx = _trackdelta[*trackdir].x;
904 trdy = _trackdelta[*trackdir].y;
905 if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CommandError();
908 return CommandCost();
912 * Build or remove a stretch of railroad tracks.
913 * @param tile start tile of drag
914 * @param flags operation to perform
915 * @param p1 end tile of drag
916 * @param p2 various bitstuffed elements
917 * - p2 = (bit 0-4) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
918 * - p2 = (bit 5-7) - track-orientation, valid values: 0-5 (Track enum)
919 * - p2 = (bit 8) - 0 = build, 1 = remove tracks
920 * - p2 = (bit 9) - 0 = build up to an obstacle, 1 = fail if an obstacle is found (used for AIs).
921 * @param text unused
922 * @return the cost of this operation or an error
924 static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
926 CommandCost total_cost(EXPENSES_CONSTRUCTION);
927 RailType railtype = Extract<RailType, 0, 5>(p2);
928 Track track = Extract<Track, 5, 3>(p2);
929 bool remove = HasBit(p2, 8);
930 bool fail_if_obstacle = HasBit(p2, 9);
932 _rail_track_endtile = INVALID_TILE;
934 if ((!remove && !ValParamRailtype(railtype)) || !ValParamTrackOrientation(track)) return CommandError();
935 if (p1 >= MapSize()) return CommandError();
936 TileIndex end_tile = p1;
937 Trackdir trackdir = TrackToTrackdir(track);
939 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
940 if (ret.Failed()) return ret;
942 bool had_success = false;
943 CommandCost last_error = CommandError();
944 for (;;) {
945 TileIndex last_endtile = _rail_track_endtile;
946 CommandCost ret = DoCommand(tile, remove ? 0 : railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
948 if (ret.Failed()) {
949 last_error = ret;
950 if (_rail_track_endtile == INVALID_TILE) _rail_track_endtile = last_endtile;
951 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
952 if (fail_if_obstacle) return last_error;
953 break;
956 /* Ownership errors are more important. */
957 if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
958 } else {
959 had_success = true;
960 total_cost.AddCost(ret);
963 if (tile == end_tile) break;
965 tile += ToTileIndexDiff(_trackdelta[trackdir]);
967 /* toggle railbit for the non-diagonal tracks */
968 if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
971 if (had_success) return total_cost;
972 return last_error;
976 * Build rail on a stretch of track.
977 * Stub for the unified rail builder/remover
978 * @param tile start tile of drag
979 * @param flags operation to perform
980 * @param p1 end tile of drag
981 * @param p2 various bitstuffed elements
982 * - p2 = (bit 0-4) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
983 * - p2 = (bit 5-7) - track-orientation, valid values: 0-5 (Track enum)
984 * - p2 = (bit 8) - 0 = build, 1 = remove tracks
985 * @param text unused
986 * @return the cost of this operation or an error
987 * @see CmdRailTrackHelper
989 CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
991 return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 8), text);
995 * Build rail on a stretch of track.
996 * Stub for the unified rail builder/remover
997 * @param tile start tile of drag
998 * @param flags operation to perform
999 * @param p1 end tile of drag
1000 * @param p2 various bitstuffed elements
1001 * - p2 = (bit 0-4) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
1002 * - p2 = (bit 5-7) - track-orientation, valid values: 0-5 (Track enum)
1003 * - p2 = (bit 8) - 0 = build, 1 = remove tracks
1004 * @param text unused
1005 * @return the cost of this operation or an error
1006 * @see CmdRailTrackHelper
1008 CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1010 return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 8), text);
1014 * Build a train depot
1015 * @param tile position of the train depot
1016 * @param flags operation to perform
1017 * @param p1 rail type
1018 * @param p2 bit 0..1 entrance direction (DiagDirection)
1019 * @param text unused
1020 * @return the cost of this operation or an error
1022 * @todo When checking for the tile slope,
1023 * distinguish between "Flat land required" and "land sloped in wrong direction"
1025 CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1027 /* check railtype and valid direction for depot (0 through 3), 4 in total */
1028 RailType railtype = Extract<RailType, 0, 5>(p1);
1029 if (!ValParamRailtype(railtype)) return CommandError();
1031 Slope tileh = GetTileSlope(tile);
1033 DiagDirection dir = Extract<DiagDirection, 0, 2>(p2);
1035 /* Prohibit construction if
1036 * The tile is non-flat AND
1037 * 1) build-on-slopes is disabled
1038 * 2) the tile is steep i.e. spans two height levels
1039 * 3) the exit points in the wrong direction
1042 if (tileh != SLOPE_FLAT && (
1043 !_settings_game.construction.build_on_slopes ||
1044 !CanBuildDepotByTileh(dir, tileh)
1045 )) {
1046 return CommandError(STR_ERROR_FLAT_LAND_REQUIRED);
1049 CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1050 if (cost.Failed()) return cost;
1052 if (IsBridgeAbove(tile)) return CommandError(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1054 if (!Depot::CanAllocateItem()) return CommandError();
1056 if (flags & DC_EXEC) {
1057 Depot *d = new Depot(tile);
1058 d->build_date = _date;
1060 MakeRailDepot(tile, _current_company, d->index, dir, railtype);
1061 MarkTileDirtyByTile(tile);
1062 MakeDefaultName(d);
1064 Company::Get(_current_company)->infrastructure.rail[railtype]++;
1065 DirtyCompanyInfrastructureWindows(_current_company);
1067 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, _current_company);
1068 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1071 cost.AddCost(_price[PR_BUILD_DEPOT_TRAIN]);
1072 cost.AddCost(RailBuildCost(railtype));
1073 return cost;
1076 static void ClearBridgeTunnelSignalSimulation(TileIndex entrance, TileIndex exit)
1078 if (IsBridge(entrance)) ClearBridgeEntranceSimulatedSignals(entrance);
1079 ClrTunnelBridgeSignalSimulationEntrance(entrance);
1080 ClrTunnelBridgeSignalSimulationExit(exit);
1083 static void SetupBridgeTunnelSignalSimulation(TileIndex entrance, TileIndex exit)
1085 SetTunnelBridgeSignalSimulationEntrance(entrance);
1086 SetTunnelBridgeSignalState(entrance, SIGNAL_STATE_GREEN);
1087 SetTunnelBridgeSignalSimulationExit(exit);
1091 * Build signals, alternate between double/single, signal/semaphore,
1092 * pre/exit/combo-signals, and what-else not. If the rail piece does not
1093 * have any signals, bit 4 (cycle signal-type) is ignored
1094 * @param tile tile where to build the signals
1095 * @param flags operation to perform
1096 * @param p1 various bitstuffed elements
1097 * - p1 = (bit 0-2) - track-orientation, valid values: 0-5 (Track enum)
1098 * - p1 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal or (for bit 7) toggle variant (CTRL-toggle)
1099 * - p1 = (bit 4) - 0 = signals, 1 = semaphores
1100 * - p1 = (bit 5-7) - type of the signal, for valid values see enum SignalType in rail_map.h
1101 * - p1 = (bit 8) - convert the present signal type and variant
1102 * - p1 = (bit 9-11)- start cycle from this signal type
1103 * - p1 = (bit 12-14)-wrap around after this signal type
1104 * - p1 = (bit 15-16)-cycle the signal direction this many times
1105 * - p1 = (bit 17) - 1 = don't modify an existing signal but don't fail either, 0 = always set new signal type
1106 * @param p2 used for CmdBuildManySignals() to copy direction of first signal
1107 * @param text unused
1108 * @return the cost of this operation or an error
1109 * @todo p2 should be replaced by two bits for "along" and "against" the track.
1111 CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1113 Track track = Extract<Track, 0, 3>(p1);
1114 bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed
1115 SignalVariant sigvar = (ctrl_pressed ^ HasBit(p1, 4)) ? SIG_SEMAPHORE : SIG_ELECTRIC; // the signal variant of the new signal
1116 SignalType sigtype = Extract<SignalType, 5, 3>(p1); // the signal type of the new signal
1117 bool convert_signal = HasBit(p1, 8); // convert button pressed
1118 SignalType cycle_start = Extract<SignalType, 9, 3>(p1);
1119 SignalType cycle_stop = Extract<SignalType, 12, 3>(p1);
1120 uint num_dir_cycle = GB(p1, 15, 2);
1122 if (sigtype > SIGTYPE_LAST) return CommandError();
1123 if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CommandError();
1125 /* You can only build signals on plain rail tiles or tunnel/bridges, and the selected track must exist */
1126 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1127 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return CommandError();
1128 CommandCost ret = EnsureNoTrainOnTrack(GetOtherTunnelBridgeEnd(tile), track);
1129 if (ret.Failed()) return ret;
1130 ret = EnsureNoTrainOnTrack(tile, track);
1131 if (ret.Failed()) return ret;
1132 } else if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1133 return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1135 /* Protect against invalid signal copying */
1136 if (p2 != 0 && (p2 & SignalOnTrack(track)) == 0) return CommandError();
1138 CommandCost ret = CheckTileOwnership(tile);
1139 if (ret.Failed()) return ret;
1141 CommandCost cost;
1142 /* handle signals simulation on tunnel/bridge. */
1143 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1144 TileIndex tile_exit = GetOtherTunnelBridgeEnd(tile);
1145 cost = CommandCost();
1146 bool flip_variant = false;
1147 bool is_pbs = (sigtype == SIGTYPE_PBS) || (sigtype == SIGTYPE_PBS_ONEWAY);
1148 if (!IsTunnelBridgeWithSignalSimulation(tile)) { // toggle signal zero costs.
1149 if (convert_signal) return CommandError(STR_ERROR_THERE_ARE_NO_SIGNALS);
1150 if (p2 != 12) cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] * ((GetTunnelBridgeLength(tile, tile_exit) + 4) >> 2)); // minimal 1
1151 } else {
1152 if (HasBit(p1, 17)) return CommandCost();
1153 if ((p2 != 0 && (sigvar == SIG_SEMAPHORE) != IsTunnelBridgeSemaphore(tile)) ||
1154 (convert_signal && (ctrl_pressed || (sigvar == SIG_SEMAPHORE) != IsTunnelBridgeSemaphore(tile)))) {
1155 flip_variant = true;
1156 cost = CommandCost(EXPENSES_CONSTRUCTION, (_price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]) *
1157 ((GetTunnelBridgeLength(tile, tile_exit) + 4) >> 2)); // minimal 1
1160 if (flags & DC_EXEC) {
1161 Company * const c = Company::Get(GetTileOwner(tile));
1162 if (IsTunnelBridgeWithSignalSimulation(tile)) c->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, tile_exit);
1163 if (p2 == 0 && IsTunnelBridgeWithSignalSimulation(tile)) { // Toggle signal if already signals present.
1164 if (convert_signal) {
1165 if (flip_variant) {
1166 SetTunnelBridgeSemaphore(tile, !IsTunnelBridgeSemaphore(tile));
1167 SetTunnelBridgeSemaphore(tile_exit, IsTunnelBridgeSemaphore(tile));
1169 if (!ctrl_pressed) {
1170 SetTunnelBridgePBS(tile, is_pbs);
1171 SetTunnelBridgePBS(tile_exit, is_pbs);
1173 } else if (ctrl_pressed) {
1174 SetTunnelBridgePBS(tile, !IsTunnelBridgePBS(tile));
1175 SetTunnelBridgePBS(tile_exit, IsTunnelBridgePBS(tile));
1176 } else {
1177 if (IsTunnelBridgeSignalSimulationEntrance(tile)) {
1178 ClearBridgeTunnelSignalSimulation(tile, tile_exit);
1179 SetupBridgeTunnelSignalSimulation(tile_exit, tile);
1180 } else {
1181 ClearBridgeTunnelSignalSimulation(tile_exit, tile);
1182 SetupBridgeTunnelSignalSimulation(tile, tile_exit);
1185 } else {
1186 /* Create one direction tunnel/bridge if required. */
1187 if (p2 == 0) {
1188 SetupBridgeTunnelSignalSimulation(tile, tile_exit);
1189 } else if (p2 == 4 || p2 == 8) {
1190 DiagDirection tbdir = GetTunnelBridgeDirection(tile);
1191 /* If signal only on one side build accordingly one-way tunnel/bridge. */
1192 if ((p2 == 8 && (tbdir == DIAGDIR_NE || tbdir == DIAGDIR_SE)) ||
1193 (p2 == 4 && (tbdir == DIAGDIR_SW || tbdir == DIAGDIR_NW))) {
1194 ClearBridgeTunnelSignalSimulation(tile_exit, tile);
1195 SetupBridgeTunnelSignalSimulation(tile, tile_exit);
1196 } else {
1197 ClearBridgeTunnelSignalSimulation(tile, tile_exit);
1198 SetupBridgeTunnelSignalSimulation(tile_exit, tile);
1202 if (p2 == 0 || p2 == 4 || p2 == 8) {
1203 SetTunnelBridgeSemaphore(tile, sigvar == SIG_SEMAPHORE);
1204 SetTunnelBridgeSemaphore(tile_exit, sigvar == SIG_SEMAPHORE);
1205 SetTunnelBridgePBS(tile, is_pbs);
1206 SetTunnelBridgePBS(tile_exit, is_pbs);
1210 if (IsTunnelBridgeSignalSimulationExit(tile) && IsTunnelBridgePBS(tile) && !HasTunnelBridgeReservation(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_RED);
1211 if (IsTunnelBridgeSignalSimulationExit(tile_exit) && IsTunnelBridgePBS(tile_exit) && !HasTunnelBridgeReservation(tile_exit)) SetTunnelBridgeSignalState(tile_exit, SIGNAL_STATE_RED);
1213 MarkBridgeOrTunnelDirty(tile);
1214 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, GetTileOwner(tile));
1215 AddSideToSignalBuffer(tile_exit, INVALID_DIAGDIR, GetTileOwner(tile));
1216 YapfNotifyTrackLayoutChange(tile, track);
1217 YapfNotifyTrackLayoutChange(tile_exit, track);
1218 if (IsTunnelBridgeWithSignalSimulation(tile)) c->infrastructure.signal += GetTunnelBridgeSignalSimulationSignalCount(tile, tile_exit);
1219 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1221 return cost;
1224 /* See if this is a valid track combination for signals (no overlap) */
1225 if (TracksOverlap(GetTrackBits(tile))) return CommandError(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
1227 /* In case we don't want to change an existing signal, return without error. */
1228 if (HasBit(p1, 17) && HasSignalOnTrack(tile, track)) return CommandCost();
1230 /* you can not convert a signal if no signal is on track */
1231 if (convert_signal && !HasSignalOnTrack(tile, track)) return CommandError(STR_ERROR_THERE_ARE_NO_SIGNALS);
1233 if (!HasSignalOnTrack(tile, track)) {
1234 /* build new signals */
1235 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS]);
1236 } else {
1237 if (p2 != 0 && sigvar != GetSignalVariant(tile, track)) {
1238 /* convert signals <-> semaphores */
1239 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1241 } else if (convert_signal) {
1242 /* convert button pressed */
1243 if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
1244 /* convert electric <-> semaphore */
1245 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1246 } else {
1247 /* it is free to change signal type: normal-pre-exit-combo */
1248 cost = CommandCost();
1251 } else {
1252 /* it is free to change orientation/pre-exit-combo signals */
1253 cost = CommandCost();
1257 if (flags & DC_EXEC) {
1258 Train *v = nullptr;
1259 /* The new/changed signal could block our path. As this can lead to
1260 * stale reservations, we clear the path reservation here and try
1261 * to redo it later on. */
1262 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1263 v = GetTrainForReservation(tile, track);
1264 if (v != nullptr) FreeTrainTrackReservation(v);
1267 if (!HasSignals(tile)) {
1268 /* there are no signals at all on this tile yet */
1269 SetHasSignals(tile, true);
1270 SetSignalStates(tile, 0xF); // all signals are on
1271 SetPresentSignals(tile, 0); // no signals built by default
1272 SetSignalType(tile, track, sigtype);
1273 SetSignalVariant(tile, track, sigvar);
1276 /* Subtract old signal infrastructure count. */
1277 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1279 if (p2 == 0) {
1280 if (!HasSignalOnTrack(tile, track)) {
1281 /* build new signals */
1282 SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsOrLogicSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
1283 SetSignalType(tile, track, sigtype);
1284 SetSignalVariant(tile, track, sigvar);
1286 /* logic signals: create a new signal program */
1287 if (sigtype == SIGTYPE_LOGIC) {
1288 CreateSignalProgram(tile, track);
1291 while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
1292 } else {
1293 if (convert_signal) {
1294 /* convert signal button pressed */
1295 if (ctrl_pressed) {
1296 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1297 SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1298 /* Query current signal type so the check for PBS signals below works. */
1299 sigtype = GetSignalType(tile, track);
1300 } else {
1301 /* convert the present signal to the chosen type and variant */
1303 /* logic signals: create or delete signal program as necessary */
1304 SignalTypeChanged(tile, track, GetSignalType(tile, track), sigtype);
1306 SetSignalType(tile, track, sigtype);
1307 SetSignalVariant(tile, track, sigvar);
1308 if (IsPbsOrLogicSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1309 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1313 } else if (ctrl_pressed) {
1314 /* cycle between cycle_start and cycle_end */
1315 sigtype = (SignalType)(GetSignalType(tile, track) + 1);
1316 if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
1318 /* logic signals: create or delete signal program as necessary */
1319 SignalTypeChanged(tile, track, GetSignalType(tile, track), sigtype);
1321 SetSignalType(tile, track, sigtype);
1322 if (IsPbsOrLogicSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1323 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1325 } else {
1326 /* cycle the signal side: both -> left -> right -> both -> ... */
1327 CycleSignalSide(tile, track);
1328 /* Query current signal type so the check for PBS signals below works. */
1329 sigtype = GetSignalType(tile, track);
1332 } else {
1333 /* If CmdBuildManySignals is called with copying signals, just copy the
1334 * direction of the first signal given as parameter by CmdBuildManySignals */
1335 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (p2 & SignalOnTrack(track)));
1336 SetSignalVariant(tile, track, sigvar);
1337 SetSignalType(tile, track, sigtype);
1339 /* logic signals: create a new signal program */
1340 if (sigtype == SIGTYPE_LOGIC) {
1341 CreateSignalProgram(tile, track);
1345 /* Add new signal infrastructure count. */
1346 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1347 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1349 if (IsPbsSignal(sigtype)) {
1350 /* PBS signals should show red unless they are on reserved tiles without a train. */
1351 uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
1352 SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetRailReservationTrackBits(tile), track) && EnsureNoVehicleOnGround(tile).Succeeded() ? UINT_MAX : 0) & mask));
1354 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1355 AddTrackToSignalBuffer(tile, track, _current_company);
1356 YapfNotifyTrackLayoutChange(tile, track);
1357 if (v != nullptr) {
1358 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1359 if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
1360 !IsSafeWaitingPosition(v, v->tile, v->GetVehicleTrackdir(), true, _settings_game.pf.forbid_90_deg)) {
1361 TryPathReserve(v, true);
1366 return cost;
1369 static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal_ctr, bool remove)
1371 tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
1372 if (tile == INVALID_TILE) return false;
1374 /* Check for track bits on the new tile */
1375 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
1377 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
1378 trackdirbits &= TrackdirReachesTrackdirs(trackdir);
1380 /* No track bits, must stop */
1381 if (trackdirbits == TRACKDIR_BIT_NONE) return false;
1383 /* Get the first track dir */
1384 trackdir = RemoveFirstTrackdir(&trackdirbits);
1386 /* Any left? It's a junction so we stop */
1387 if (trackdirbits != TRACKDIR_BIT_NONE) return false;
1389 switch (GetTileType(tile)) {
1390 case MP_RAILWAY:
1391 if (IsRailDepot(tile)) return false;
1392 if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
1393 signal_ctr++;
1394 if (IsDiagonalTrackdir(trackdir)) {
1395 signal_ctr++;
1396 /* Ensure signal_ctr even so X and Y pieces get signals */
1397 ClrBit(signal_ctr, 0);
1399 return true;
1401 case MP_ROAD:
1402 if (!IsLevelCrossing(tile)) return false;
1403 signal_ctr += 2;
1404 return true;
1406 case MP_TUNNELBRIDGE: {
1407 if (!remove && IsTunnelBridgeWithSignalSimulation(tile)) return false;
1408 TileIndex orig_tile = tile; // backup old value
1410 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
1411 if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
1413 /* Skip to end of tunnel or bridge
1414 * note that tile is a parameter by reference, so it must be updated */
1415 tile = GetOtherTunnelBridgeEnd(tile);
1417 signal_ctr += (GetTunnelBridgeLength(orig_tile, tile) + 2) * 2;
1418 return true;
1421 default: return false;
1426 * Build many signals by dragging; AutoSignals
1427 * @param tile start tile of drag
1428 * @param flags operation to perform
1429 * @param p1 end tile of drag
1430 * @param p2 various bitstuffed elements
1431 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1432 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1433 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1434 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1435 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1436 * - p2 = (bit 7- 9) - default signal type
1437 * - p2 = (bit 10) - 0 = keep fixed distance, 1 = minimise gaps between signals
1438 * - p2 = (bit 24-31) - user defined signals_density
1439 * @param text unused
1440 * @return the cost of this operation or an error
1442 static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1444 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1445 TileIndex start_tile = tile;
1447 Track track = Extract<Track, 0, 3>(p2);
1448 bool mode = HasBit(p2, 3);
1449 bool semaphores = HasBit(p2, 4);
1450 bool remove = HasBit(p2, 5);
1451 bool autofill = HasBit(p2, 6);
1452 bool minimise_gaps = HasBit(p2, 10);
1453 byte signal_density = GB(p2, 24, 8);
1455 if (p1 >= MapSize() || !ValParamTrackOrientation(track)) return CommandError();
1456 TileIndex end_tile = p1;
1457 if (signal_density == 0 || signal_density > 20) return CommandError();
1459 if (!IsPlainRailTile(tile)) return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1461 /* for vertical/horizontal tracks, double the given signals density
1462 * since the original amount will be too dense (shorter tracks) */
1463 signal_density *= 2;
1465 Trackdir trackdir = TrackToTrackdir(track);
1466 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
1467 if (ret.Failed()) return ret;
1469 track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
1470 Trackdir start_trackdir = trackdir;
1472 /* Must start on a valid track to be able to avoid loops */
1473 if (!HasTrack(tile, track)) return CommandError();
1475 SignalType sigtype = (SignalType)GB(p2, 7, 3);
1476 if (sigtype > SIGTYPE_LAST) return CommandError();
1478 byte signals;
1479 /* copy the signal-style of the first rail-piece if existing */
1480 if (HasSignalOnTrack(tile, track)) {
1481 signals = GetPresentSignals(tile) & SignalOnTrack(track);
1482 assert(signals != 0);
1484 /* copy signal/semaphores style (independent of CTRL) */
1485 semaphores = GetSignalVariant(tile, track) != SIG_ELECTRIC;
1487 sigtype = GetSignalType(tile, track);
1488 /* Don't but copy entry or exit-signal type */
1489 if (sigtype == SIGTYPE_ENTRY || sigtype == SIGTYPE_EXIT) sigtype = SIGTYPE_NORMAL;
1490 } else { // no signals exist, drag a two-way signal stretch
1491 signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
1494 byte signal_dir = 0;
1495 if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
1496 if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
1498 /* signal_ctr - amount of tiles already processed
1499 * last_used_ctr - amount of tiles before previously placed signal
1500 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1501 * last_suitable_ctr - amount of tiles before last possible signal place
1502 * last_suitable_tile - last tile where it is possible to place a signal
1503 * last_suitable_trackdir - trackdir of the last tile
1504 **********
1505 * trackdir - trackdir to build with autorail
1506 * semaphores - semaphores or signals
1507 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1508 * and convert all others to semaphore/signal
1509 * remove - 1 remove signals, 0 build signals */
1510 int signal_ctr = 0;
1511 int last_used_ctr = INT_MIN; // initially INT_MIN to force building/removing at the first tile
1512 int last_suitable_ctr = 0;
1513 TileIndex last_suitable_tile = INVALID_TILE;
1514 Trackdir last_suitable_trackdir = INVALID_TRACKDIR;
1515 CommandCost last_error = CommandError();
1516 bool had_success = false;
1517 std::vector<TileIndex> tunnel_bridge_blacklist;
1518 for (;;) {
1519 bool tile_ok = true;
1520 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1521 if (container_unordered_remove(tunnel_bridge_blacklist, tile) > 0) {
1522 /* This tile is blacklisted, skip tile and remove from blacklist.
1523 * Mark last used counter as current tile.
1525 tile_ok = false;
1526 last_used_ctr = signal_ctr;
1527 last_suitable_tile = INVALID_TILE;
1531 /* only build/remove signals with the specified density */
1532 if (tile_ok && (remove || minimise_gaps || signal_ctr % signal_density == 0 || IsTileType(tile, MP_TUNNELBRIDGE))) {
1533 uint32 p1 = GB(TrackdirToTrack(trackdir), 0, 3);
1534 SB(p1, 3, 1, mode);
1535 SB(p1, 4, 1, semaphores);
1536 SB(p1, 5, 3, sigtype);
1537 if (!remove && signal_ctr == 0) SetBit(p1, 17);
1539 /* Pick the correct orientation for the track direction */
1540 signals = 0;
1541 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
1542 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
1544 /* Test tiles in between for suitability as well if minimising gaps. */
1545 bool test_only = !remove && minimise_gaps && signal_ctr < (last_used_ctr + signal_density);
1546 CommandCost ret = DoCommand(tile, p1, signals, test_only ? flags & ~DC_EXEC : flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1548 if (!test_only && ret.Succeeded() && IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(tile) == TrackdirToExitdir(trackdir)) {
1549 /* Blacklist far end of tunnel if we just actioned the near end */
1550 tunnel_bridge_blacklist.push_back(GetOtherTunnelBridgeEnd(tile));
1553 if (ret.Succeeded()) {
1554 /* Remember last track piece where we can place a signal. */
1555 last_suitable_ctr = signal_ctr;
1556 last_suitable_tile = tile;
1557 last_suitable_trackdir = trackdir;
1558 } else if (!test_only && last_suitable_tile != INVALID_TILE) {
1559 /* If a signal can't be placed, place it at the last possible position. */
1560 SB(p1, 0, 3, TrackdirToTrack(last_suitable_trackdir));
1561 ClrBit(p1, 17);
1563 /* Pick the correct orientation for the track direction. */
1564 signals = 0;
1565 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(last_suitable_trackdir);
1566 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(last_suitable_trackdir);
1568 ret = DoCommand(last_suitable_tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1570 if (ret.Succeeded() && IsTileType(last_suitable_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(last_suitable_tile) == TrackdirToExitdir(last_suitable_trackdir)) {
1571 /* Blacklist far end of tunnel if we just actioned the near end */
1572 tunnel_bridge_blacklist.push_back(GetOtherTunnelBridgeEnd(last_suitable_tile));
1576 /* Collect cost. */
1577 if (!test_only) {
1578 /* Be user-friendly and try placing signals as much as possible */
1579 if (ret.Succeeded()) {
1580 had_success = true;
1581 total_cost.AddCost(ret);
1582 last_used_ctr = last_suitable_ctr;
1583 last_suitable_tile = INVALID_TILE;
1584 } else {
1585 /* The "No railway" error is the least important one. */
1586 if (ret.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK ||
1587 last_error.GetErrorMessage() == INVALID_STRING_ID) {
1588 last_error = ret;
1594 if (autofill) {
1595 if (!CheckSignalAutoFill(tile, trackdir, signal_ctr, remove)) break;
1597 /* Prevent possible loops */
1598 if (tile == start_tile && trackdir == start_trackdir) break;
1599 } else {
1600 if (tile == end_tile) break;
1602 tile += ToTileIndexDiff(_trackdelta[trackdir]);
1603 signal_ctr++;
1605 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1606 if (IsDiagonalTrackdir(trackdir)) {
1607 signal_ctr++;
1608 } else {
1609 ToggleBit(trackdir, 0);
1614 return had_success ? total_cost : last_error;
1618 * Build signals on a stretch of track.
1619 * Stub for the unified signal builder/remover
1620 * @param tile start tile of drag
1621 * @param flags operation to perform
1622 * @param p1 end tile of drag
1623 * @param p2 various bitstuffed elements
1624 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1625 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1626 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1627 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1628 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1629 * - p2 = (bit 7- 9) - default signal type
1630 * - p2 = (bit 24-31) - user defined signals_density
1631 * @param text unused
1632 * @return the cost of this operation or an error
1633 * @see CmdSignalTrackHelper
1635 CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1637 return CmdSignalTrackHelper(tile, flags, p1, p2, text);
1641 * Remove signals
1642 * @param tile coordinates where signal is being deleted from
1643 * @param flags operation to perform
1644 * @param p1 various bitstuffed elements, only track information is used
1645 * - (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1646 * - (bit 3) - override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1647 * - (bit 4) - 0 = signals, 1 = semaphores
1648 * @param p2 unused
1649 * @param text unused
1650 * @return the cost of this operation or an error
1652 CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1654 Track track = Extract<Track, 0, 3>(p1);
1655 Money cost = _price[PR_CLEAR_SIGNALS];
1657 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1658 TileIndex end = GetOtherTunnelBridgeEnd(tile);
1659 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1660 if (!IsTunnelBridgeWithSignalSimulation(tile)) return CommandError(STR_ERROR_THERE_ARE_NO_SIGNALS);
1662 cost *= ((GetTunnelBridgeLength(tile, end) + 4) >> 2);
1664 CommandCost ret = EnsureNoTrainOnTrack(GetOtherTunnelBridgeEnd(tile), track);
1665 if (ret.Failed()) return ret;
1666 ret = EnsureNoTrainOnTrack(tile, track);
1667 if (ret.Failed()) return ret;
1668 } else {
1669 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1670 return CommandError(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1672 if (!HasSignalOnTrack(tile, track)) {
1673 return CommandError(STR_ERROR_THERE_ARE_NO_SIGNALS);
1675 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
1676 if (ret.Failed()) return ret;
1679 /* Only water can remove signals from anyone */
1680 if (_current_company != OWNER_WATER) {
1683 /* Do it? */
1684 if (flags & DC_EXEC) {
1686 if (IsTunnelBridgeWithSignalSimulation(tile)) { // handle tunnel/bridge signals.
1687 TileIndex end = GetOtherTunnelBridgeEnd(tile);
1688 Company::Get(GetTileOwner(tile))->infrastructure.signal -= GetTunnelBridgeSignalSimulationSignalCount(tile, end);
1689 ClearBridgeTunnelSignalSimulation(end, tile);
1690 ClearBridgeTunnelSignalSimulation(tile, end);
1691 MarkBridgeOrTunnelDirty(tile);
1692 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, GetTileOwner(tile));
1693 AddSideToSignalBuffer(end, INVALID_DIAGDIR, GetTileOwner(tile));
1694 YapfNotifyTrackLayoutChange(tile, track);
1695 YapfNotifyTrackLayoutChange(end, track);
1696 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1697 return CommandCost(EXPENSES_CONSTRUCTION, cost);
1700 Train *v = nullptr;
1701 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1702 v = GetTrainForReservation(tile, track);
1703 } else if (IsPbsSignal(GetSignalType(tile, track))) {
1704 /* PBS signal, might be the end of a path reservation. */
1705 Trackdir td = TrackToTrackdir(track);
1706 for (int i = 0; v == nullptr && i < 2; i++, td = ReverseTrackdir(td)) {
1707 /* Only test the active signal side. */
1708 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
1709 TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
1710 TrackBits tracks = TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td));
1711 if (HasReservedTracks(next, tracks)) {
1712 v = GetTrainForReservation(next, TrackBitsToTrack(GetReservedTrackbits(next) & tracks));
1717 /* Remove any links this signal had */
1718 RemoveSignalLink(tile, track);
1719 /* Logic signal: remove signal program */
1720 if (IsLogicSignal(tile, track)) {
1721 DeleteSignalProgram(tile, track);
1724 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1725 SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
1726 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1727 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1728 TraceRestrictNotifySignalRemoval(tile, track);
1730 /* removed last signal from tile? */
1731 if (GetPresentSignals(tile) == 0) {
1732 SetSignalStates(tile, 0);
1733 SetHasSignals(tile, false);
1734 SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
1737 AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
1738 YapfNotifyTrackLayoutChange(tile, track);
1739 if (v != nullptr) TryPathReserve(v, false);
1741 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1744 return CommandCost(EXPENSES_CONSTRUCTION, cost);
1748 * Remove signals on a stretch of track.
1749 * Stub for the unified signal builder/remover
1750 * @param tile start tile of drag
1751 * @param flags operation to perform
1752 * @param p1 end tile of drag
1753 * @param p2 various bitstuffed elements
1754 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1755 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1756 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1757 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1758 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1759 * - p2 = (bit 7- 9) - default signal type
1760 * - p2 = (bit 24-31) - user defined signals_density
1761 * @param text unused
1762 * @return the cost of this operation or an error
1763 * @see CmdSignalTrackHelper
1765 CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1767 return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
1770 /** Update power of train under which is the railtype being converted */
1771 static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
1773 if (v->type != VEH_TRAIN) return nullptr;
1775 TrainList *affected_trains = static_cast<TrainList*>(data);
1776 affected_trains->Include(Train::From(v)->First());
1778 return nullptr;
1782 * Convert one rail type to the other. You can convert normal rail to
1783 * monorail/maglev easily or vice-versa.
1784 * @param tile end tile of rail conversion drag
1785 * @param flags operation to perform
1786 * @param p1 start tile of drag
1787 * @param p2 various bitstuffed elements:
1788 * - p2 = (bit 0 - 4) new railtype to convert to.
1789 * - p2 = (bit 5) build diagonally or not.
1790 * @param text unused
1791 * @return the cost of this operation or an error
1793 CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1795 RailType totype = Extract<RailType, 0, 5>(p2);
1796 TileIndex area_start = p1;
1797 TileIndex area_end = tile;
1798 bool diagonal = HasBit(p2, 5);
1800 if (!ValParamRailtype(totype)) return CommandError();
1801 if (area_start >= MapSize()) return CommandError();
1803 TrainList affected_trains;
1805 CommandCost cost(EXPENSES_CONSTRUCTION);
1806 CommandCost error = CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK); // by default, there is no track to convert.
1808 TileIterator *iter = diagonal ? (TileIterator *)new DiagonalTileIterator(area_start, area_end) : new OrthogonalTileIterator(area_start, area_end);
1809 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
1810 TileType tt = GetTileType(tile);
1812 /* Check if there is any track on tile */
1813 switch (tt) {
1814 case MP_RAILWAY:
1815 break;
1816 case MP_STATION:
1817 if (!HasStationRail(tile)) continue;
1818 break;
1819 case MP_ROAD:
1820 if (!IsLevelCrossing(tile)) continue;
1821 if (RailNoLevelCrossings(totype)) {
1822 error.MakeError(STR_ERROR_CROSSING_DISALLOWED);
1823 continue;
1825 break;
1826 case MP_TUNNELBRIDGE:
1827 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
1828 break;
1829 default: continue;
1832 /* Original railtype we are converting from */
1833 RailType type = GetRailType(tile);
1835 /* Converting to the same type or converting 'hidden' elrail -> rail */
1836 if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
1838 /* Trying to convert other's rail */
1839 CommandCost ret = CheckTileOwnership(tile);
1840 if (ret.Failed()) {
1841 error = ret;
1842 continue;
1845 SmallVector<Train *, 2> vehicles_affected;
1847 /* Vehicle on the tile when not converting Rail <-> ElRail
1848 * Tunnels and bridges have special check later */
1849 if (tt != MP_TUNNELBRIDGE) {
1850 if (!IsCompatibleRail(type, totype)) {
1851 CommandCost ret = IsPlainRailTile(tile) ? EnsureNoTrainOnTrackBits(tile, GetTrackBits(tile)) : EnsureNoVehicleOnGround(tile);
1852 if (ret.Failed()) {
1853 error = ret;
1854 continue;
1857 if (flags & DC_EXEC) { // we can safely convert, too
1858 TrackBits reserved = GetReservedTrackbits(tile);
1859 Track track;
1860 while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
1861 Train *v = GetTrainForReservation(tile, track);
1862 if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
1863 /* No power on new rail type, reroute. */
1864 FreeTrainTrackReservation(v);
1865 *vehicles_affected.Append() = v;
1869 /* Update the company infrastructure counters. */
1870 if (!IsRailStationTile(tile) || !IsStationTileBlocked(tile)) {
1871 Company *c = Company::Get(GetTileOwner(tile));
1872 uint num_pieces = IsLevelCrossingTile(tile) ? LEVELCROSSING_TRACKBIT_FACTOR : 1;
1873 if (IsPlainRailTile(tile)) {
1874 TrackBits bits = GetTrackBits(tile);
1875 num_pieces = CountBits(bits);
1876 if (TracksOverlap(bits)) num_pieces *= num_pieces;
1878 c->infrastructure.rail[type] -= num_pieces;
1879 c->infrastructure.rail[totype] += num_pieces;
1880 DirtyCompanyInfrastructureWindows(c->index);
1883 SetRailType(tile, totype);
1884 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1885 /* update power of train on this tile */
1886 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1890 switch (tt) {
1891 case MP_RAILWAY:
1892 switch (GetRailTileType(tile)) {
1893 case RAIL_TILE_DEPOT:
1894 if (flags & DC_EXEC) {
1895 /* notify YAPF about the track layout change */
1896 YapfNotifyTrackLayoutChange(tile, GetRailDepotTrack(tile));
1898 /* Update build vehicle window related to this depot */
1899 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
1900 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
1902 cost.AddCost(RailConvertCost(type, totype));
1903 break;
1905 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1906 if (flags & DC_EXEC) {
1907 /* notify YAPF about the track layout change */
1908 TrackBits tracks = GetTrackBits(tile);
1909 while (tracks != TRACK_BIT_NONE) {
1910 YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(&tracks));
1913 cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
1914 break;
1916 break;
1918 case MP_TUNNELBRIDGE: {
1919 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
1921 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1922 * it would cause assert because of different test and exec runs */
1923 if (endtile < tile) {
1924 if (diagonal) {
1925 if (DiagonalTileArea(area_start, area_end).Contains(endtile)) continue;
1926 } else {
1927 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
1931 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1932 if (!IsCompatibleRail(GetRailType(tile), totype)) {
1933 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
1934 if (ret.Failed()) {
1935 error = ret;
1936 continue;
1940 if (flags & DC_EXEC) {
1941 Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
1942 if (HasTunnelBridgeReservation(tile)) {
1943 Train *v = GetTrainForReservation(tile, track);
1944 if (v != nullptr && !HasPowerOnRail(v->railtype, totype)) {
1945 /* No power on new rail type, reroute. */
1946 FreeTrainTrackReservation(v);
1947 *vehicles_affected.Append() = v;
1951 /* Update the company infrastructure counters. */
1952 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1953 Company *c = Company::Get(GetTileOwner(tile));
1954 c->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1955 c->infrastructure.rail[totype] += num_pieces;
1956 DirtyCompanyInfrastructureWindows(c->index);
1958 SetRailType(tile, totype);
1959 SetRailType(endtile, totype);
1961 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1962 FindVehicleOnPos(endtile, &affected_trains, &UpdateTrainPowerProc);
1964 YapfNotifyTrackLayoutChange(tile, track);
1965 YapfNotifyTrackLayoutChange(endtile, track);
1967 if (IsBridge(tile)) {
1968 MarkBridgeDirty(tile);
1969 } else {
1970 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1971 MarkTileDirtyByTile(endtile, ZOOM_LVL_DRAW_MAP);
1975 cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
1976 break;
1979 default: // MP_STATION, MP_ROAD
1980 if (flags & DC_EXEC) {
1981 Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
1982 YapfNotifyTrackLayoutChange(tile, track);
1985 cost.AddCost(RailConvertCost(type, totype));
1986 break;
1989 for (uint i = 0; i < vehicles_affected.Length(); ++i) {
1990 TryPathReserve(vehicles_affected[i], true);
1994 if (flags & DC_EXEC) {
1995 /* Railtype changed, update trains as when entering different track */
1996 for (Train **v = affected_trains.Begin(); v != affected_trains.End(); v++) {
1997 (*v)->ConsistChanged(CCF_TRACK);
2001 delete iter;
2002 return (cost.GetCost() == 0) ? error : cost;
2005 static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
2007 if (_current_company != OWNER_WATER) {
2008 CommandCost ret = CheckTileOwnership(tile);
2009 if (ret.Failed()) return ret;
2012 CommandCost ret = EnsureNoVehicleOnGround(tile);
2013 if (ret.Failed()) return ret;
2015 if (flags & DC_EXEC) {
2016 /* read variables before the depot is removed */
2017 DiagDirection dir = GetRailDepotDirection(tile);
2018 Owner owner = GetTileOwner(tile);
2019 Train *v = nullptr;
2021 if (HasDepotReservation(tile)) {
2022 v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
2023 if (v != nullptr) FreeTrainTrackReservation(v);
2026 Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
2027 DirtyCompanyInfrastructureWindows(owner);
2029 delete Depot::GetByTile(tile);
2030 DoClearSquare(tile);
2031 AddSideToSignalBuffer(tile, dir, owner);
2032 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
2033 if (v != nullptr) TryPathReserve(v, true);
2036 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
2039 static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
2041 CommandCost cost(EXPENSES_CONSTRUCTION);
2043 if (flags & DC_AUTO) {
2044 if (!IsTileOwner(tile, _current_company)) {
2045 return CommandError(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
2048 if (IsPlainRail(tile)) {
2049 return CommandError(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2050 } else {
2051 return CommandError(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
2055 switch (GetRailTileType(tile)) {
2056 case RAIL_TILE_SIGNALS:
2057 case RAIL_TILE_NORMAL: {
2058 Slope tileh = GetTileSlope(tile);
2059 /* Is there flat water on the lower halftile that gets cleared expensively? */
2060 bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
2062 TrackBits tracks = GetTrackBits(tile);
2063 while (tracks != TRACK_BIT_NONE) {
2064 Track track = RemoveFirstTrack(&tracks);
2065 CommandCost ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
2066 if (ret.Failed()) return ret;
2067 cost.AddCost(ret);
2070 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
2071 * Same holds for non-companies clearing the tile, e.g. disasters. */
2072 if (water_ground && !(flags & DC_BANKRUPT) && Company::IsValidID(_current_company)) {
2073 CommandCost ret = EnsureNoVehicleOnGround(tile);
2074 if (ret.Failed()) return ret;
2076 /* The track was removed, and left a coast tile. Now also clear the water. */
2077 if (flags & DC_EXEC) DoClearSquare(tile);
2078 cost.AddCost(_price[PR_CLEAR_WATER]);
2081 return cost;
2084 case RAIL_TILE_DEPOT:
2085 return RemoveTrainDepot(tile, flags);
2087 default:
2088 return CommandError();
2093 * Get surface height in point (x,y)
2094 * On tiles with halftile foundations move (x,y) to a safe point wrt. track
2096 static uint GetSaveSlopeZ(uint x, uint y, Track track)
2098 switch (track) {
2099 case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
2100 case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
2101 case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
2102 case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
2103 default: break;
2105 return GetSlopePixelZ(x, y);
2108 static void DrawSingleSignal(TileIndex tile, const RailtypeInfo *rti, Track track, SignalState condition, SignalOffsets image, uint pos)
2110 bool side;
2111 switch (_settings_game.construction.train_signal_side) {
2112 case 0: side = false; break; // left
2113 case 2: side = true; break; // right
2114 default: side = _settings_game.vehicle.road_side != 0; break; // driving side
2116 static const Point SignalPositions[2][12] = {
2117 { // Signals on the left side
2118 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
2119 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
2120 /* LOWER LOWER X X Y Y */
2121 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
2122 }, { // Signals on the right side
2123 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
2124 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
2125 /* LOWER LOWER X X Y Y */
2126 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
2130 uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
2131 uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
2133 SignalType type = GetSignalType(tile, track);
2134 SignalVariant variant = GetSignalVariant(tile, track);
2136 SpriteID sprite = GetCustomSignalSprite(rti, tile, type, variant, condition);
2137 bool is_custom_sprite = (sprite != 0);
2138 if (sprite != 0) {
2139 sprite += image;
2140 } else {
2141 /* Normal electric signals are stored in a different sprite block than all other signals. */
2142 sprite = (type == SIGTYPE_NORMAL && variant == SIG_ELECTRIC) ? SPR_ORIGINAL_SIGNALS_BASE : SPR_SIGNALS_BASE - 16;
2143 sprite += type * 16 + variant * 64 + image * 2 + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
2146 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
2149 static uint32 _drawtile_track_palette;
2153 /** Offsets for drawing fences */
2154 struct FenceOffset {
2155 Corner height_ref; //!< Corner to use height offset from.
2156 int x_offs; //!< Bounding box X offset.
2157 int y_offs; //!< Bounding box Y offset.
2158 int x_size; //!< Bounding box X size.
2159 int y_size; //!< Bounding box Y size.
2162 /** Offsets for drawing fences */
2163 static FenceOffset _fence_offsets[] = {
2164 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
2165 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
2166 { CORNER_W, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
2167 { CORNER_N, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
2168 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
2169 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
2170 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
2171 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
2172 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
2173 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
2174 { CORNER_E, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
2175 { CORNER_S, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
2176 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
2177 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
2178 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
2179 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
2183 * Draw a track fence.
2184 * @param ti Tile drawing information.
2185 * @param base_image First fence sprite.
2186 * @param num_sprites Number of fence sprites.
2187 * @param rfo Fence to draw.
2189 static void DrawTrackFence(const TileInfo *ti, SpriteID base_image, uint num_sprites, RailFenceOffset rfo)
2191 int z = ti->z;
2192 if (_fence_offsets[rfo].height_ref != CORNER_INVALID) {
2193 z += GetSlopePixelZInCorner(RemoveHalftileSlope(ti->tileh), _fence_offsets[rfo].height_ref);
2195 AddSortableSpriteToDraw(base_image + (rfo % num_sprites), _drawtile_track_palette,
2196 ti->x + _fence_offsets[rfo].x_offs,
2197 ti->y + _fence_offsets[rfo].y_offs,
2198 _fence_offsets[rfo].x_size,
2199 _fence_offsets[rfo].y_size,
2200 4, z);
2204 * Draw fence at NW border matching the tile slope.
2206 static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2208 RailFenceOffset rfo = RFO_FLAT_X_NW;
2209 if (ti->tileh & SLOPE_NW) rfo = (ti->tileh & SLOPE_W) ? RFO_SLOPE_SW_NW : RFO_SLOPE_NE_NW;
2210 DrawTrackFence(ti, base_image, num_sprites, rfo);
2214 * Draw fence at SE border matching the tile slope.
2216 static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2218 RailFenceOffset rfo = RFO_FLAT_X_SE;
2219 if (ti->tileh & SLOPE_SE) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW_SE : RFO_SLOPE_NE_SE;
2220 DrawTrackFence(ti, base_image, num_sprites, rfo);
2224 * Draw fence at NE border matching the tile slope.
2226 static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2228 RailFenceOffset rfo = RFO_FLAT_Y_NE;
2229 if (ti->tileh & SLOPE_NE) rfo = (ti->tileh & SLOPE_E) ? RFO_SLOPE_SE_NE : RFO_SLOPE_NW_NE;
2230 DrawTrackFence(ti, base_image, num_sprites, rfo);
2234 static byte GetTrackGrowthPhase(TileIndex ti, TrackBits trackbits)
2236 if (!IsTileType(ti, MP_RAILWAY))
2237 return 0;
2239 if (!IsPlainRailTile(ti))
2240 return 0;
2242 if ((GetTrackBits(ti) & trackbits) == 0)
2243 return 0;
2245 return GetTrackGrowthPhase(ti);
2249 * GetTrackGrowthPhaseEx returns a calculated growth factor
2250 * for a specific track on a tile - by also looking at its
2251 * neighbours
2253 byte GetTrackGrowthPhaseEx(TileIndex ti, Track track)
2255 byte phase = GetTrackGrowthPhase(ti);
2256 if (phase == 3) return 3;
2258 /* If this track piece is connected to a neighbour tile///
2259 * and that neighbour is used less often - we can't
2260 * be the track piece that is used so often on this tile
2262 Trackdir td1 = TrackToTrackdir(track);
2263 DiagDirection dd1 = TrackdirToExitdir(td1);
2264 TrackBits tb1 = DiagdirReachesTracks(dd1);
2265 TileIndex ti1 = ti + TileOffsByDiagDir(dd1);
2266 byte phase1 = GetTrackGrowthPhase(ti1, tb1);
2267 if (phase1 == 3) return 3;
2269 /* Same check for the other neighbour */
2270 Trackdir td2 = ReverseTrackdir(td1);
2271 DiagDirection dd2 = TrackdirToExitdir(td2);
2272 TrackBits tb2 = DiagdirReachesTracks(dd2);
2273 TileIndex ti2 = ti + TileOffsByDiagDir(dd2);
2274 byte phase2 = GetTrackGrowthPhase(ti2, tb2);
2275 if (phase2 == 3) return 3;
2277 /* Return the highest growth factor */
2278 return max(phase, max(phase1, phase2));
2281 static bool GetTrackGrowthSpriteBase(TileIndex tile, Track track, SpriteID& base)
2283 byte phase = GetTrackGrowthPhaseEx(tile, track);
2284 if (phase == 0)
2285 return false;
2287 assert(phase <= 3);
2289 base = SPR_OLDTRACKS_BASE + 10 * (phase - 1);
2290 return true;
2293 static bool GetTrackGrowthPalette(TileIndex tile, SpriteID& pal)
2295 pal = PAL_NONE;
2298 * In arctic, use the 'BARE' palette always, looks better on that terrain
2299 * obsolete when it will get its own overlays (for snow, also)
2301 switch (_settings_game.game_creation.landscape) {
2302 case LT_ARCTIC: pal = PALETTE_TO_BARE_LAND; break;
2303 default: break;
2307 * Use 'BARE' palette for desert in tropical and snow in arctic since it
2308 * looks better than green. But use other overlays in future!!
2310 switch (GetRailGroundType(tile)) {
2311 case RAIL_GROUND_ICE_DESERT: /* fallthrough */
2312 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2313 default: break;
2316 /* Both base and pal set; we can return true */
2317 return true;
2320 void DrawTrackGrowth(TileInfo* ti, TrackBits track)
2322 SpriteID pal, base;
2323 TileIndex tile = ti->tile;
2324 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(ti->tile))->label;
2326 if (railTypeLabel == _planning_tracks_label ||
2327 railTypeLabel == _pipeline_tracks_label ||
2328 railTypeLabel == _wires_tracks_label) {
2329 // Never age these specialized tracks.
2330 return;
2333 if (!GetTrackGrowthPalette(tile, pal)) return;
2335 /* future support for tunnels */
2336 Slope tileh = ti->tileh;
2337 if (IsTunnelTile(ti->tile)) tileh = SLOPE_FLAT;
2339 switch (tileh) {
2340 case SLOPE_NW:
2341 assert(track == TRACK_BIT_Y);
2342 if (GetTrackGrowthSpriteBase(tile, TRACK_Y, base))
2343 DrawGroundSprite(base + 9, pal);
2344 break;
2345 case SLOPE_SW:
2346 assert(track == TRACK_BIT_X);
2347 if (GetTrackGrowthSpriteBase(tile, TRACK_X, base))
2348 DrawGroundSprite(base + 8, pal);
2349 break;
2350 case SLOPE_SE:
2351 assert(track == TRACK_BIT_Y);
2352 if (GetTrackGrowthSpriteBase(tile, TRACK_Y, base))
2353 DrawGroundSprite(base + 7, pal);
2354 break;
2355 case SLOPE_NE:
2356 assert(track == TRACK_BIT_X);
2357 if (GetTrackGrowthSpriteBase(tile, TRACK_X, base))
2358 DrawGroundSprite(base + 6, pal);
2359 break;
2360 default:
2361 /* any track bits on any other slope are drawn normally */
2362 if ((track & TRACK_BIT_Y) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_Y, base)) DrawGroundSprite(base + 0, pal);
2363 if ((track & TRACK_BIT_X) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_X, base)) DrawGroundSprite(base + 1, pal);
2364 if ((track & TRACK_BIT_UPPER) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_UPPER, base)) DrawGroundSprite(base + 2, pal);
2365 if ((track & TRACK_BIT_LOWER) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_LOWER, base)) DrawGroundSprite(base + 3, pal);
2366 if ((track & TRACK_BIT_RIGHT) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_RIGHT, base)) DrawGroundSprite(base + 4, pal);
2367 if ((track & TRACK_BIT_LEFT) != 0 && GetTrackGrowthSpriteBase(tile, TRACK_LEFT, base)) DrawGroundSprite(base + 5, pal);
2368 break;
2373 * Draw fence at SW border matching the tile slope.
2375 static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
2377 RailFenceOffset rfo = RFO_FLAT_Y_SW;
2378 if (ti->tileh & SLOPE_SW) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE_SW : RFO_SLOPE_NW_SW;
2379 DrawTrackFence(ti, base_image, num_sprites, rfo);
2383 * Draw track fences.
2384 * @param ti Tile drawing information.
2385 * @param rti Rail type information.
2387 static void DrawTrackDetails(const TileInfo *ti, const RailtypeInfo *rti)
2389 /* Base sprite for track fences.
2390 * Note: Halftile slopes only have fences on the upper part. */
2391 uint num_sprites = 0;
2392 SpriteID base_image = GetCustomRailSprite(rti, ti->tile, RTSG_FENCES, IsHalftileSlope(ti->tileh) ? TCX_UPPER_HALFTILE : TCX_NORMAL, &num_sprites);
2393 if (base_image == 0) {
2394 base_image = SPR_TRACK_FENCE_FLAT_X;
2395 num_sprites = 8;
2398 assert(num_sprites > 0);
2400 switch (GetRailGroundType(ti->tile)) {
2401 case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image, num_sprites); break;
2402 case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image, num_sprites); break;
2403 case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW(ti, base_image, num_sprites);
2404 DrawTrackFence_SE(ti, base_image, num_sprites); break;
2405 case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image, num_sprites); break;
2406 case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image, num_sprites); break;
2407 case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE(ti, base_image, num_sprites);
2408 DrawTrackFence_SW(ti, base_image, num_sprites); break;
2409 case RAIL_GROUND_FENCE_VERT1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2410 case RAIL_GROUND_FENCE_VERT2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2411 case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2412 case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2413 case RAIL_GROUND_WATER: {
2414 Corner track_corner;
2415 if (IsHalftileSlope(ti->tileh)) {
2416 /* Steep slope or one-corner-raised slope with halftile foundation */
2417 track_corner = GetHalftileSlopeCorner(ti->tileh);
2418 } else {
2419 /* Three-corner-raised slope */
2420 track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2422 switch (track_corner) {
2423 case CORNER_W: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2424 case CORNER_S: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2425 case CORNER_E: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2426 case CORNER_N: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2427 default: NOT_REACHED();
2429 break;
2431 default: break;
2435 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2436 static const int INF = 1000; // big number compared to tilesprite size
2437 static const SubSprite _halftile_sub_sprite[4] = {
2438 { -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
2439 { -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
2440 { -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
2441 { -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2444 static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
2446 DrawGroundSprite(sprite, pal, nullptr, 0, (ti->tileh & s) ? -8 : 0);
2449 static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailtypeInfo *rti)
2451 RailGroundType rgt = GetRailGroundType(ti->tile);
2452 Foundation f = GetRailFoundation(ti->tileh, track);
2453 Corner halftile_corner = CORNER_INVALID;
2455 if (IsNonContinuousFoundation(f)) {
2456 /* Save halftile corner */
2457 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2458 /* Draw lower part first */
2459 track &= ~CornerToTrackBits(halftile_corner);
2460 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2463 DrawFoundation(ti, f);
2464 /* DrawFoundation modifies ti */
2466 /* Draw ground */
2467 if (rgt == RAIL_GROUND_WATER) {
2468 if (track != TRACK_BIT_NONE || IsSteepSlope(ti->tileh)) {
2469 /* three-corner-raised slope or steep slope with track on upper part */
2470 DrawShoreTile(ti->tileh);
2471 } else {
2472 /* single-corner-raised slope with track on upper part */
2473 DrawGroundSprite(SPR_FLAT_WATER_TILE, PAL_NONE);
2475 } else {
2476 SpriteID image;
2478 switch (rgt) {
2479 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2480 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2481 default: image = SPR_FLAT_GRASS_TILE; break;
2484 image += SlopeToSpriteOffset(ti->tileh);
2486 DrawGroundSprite(image, PAL_NONE);
2489 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2490 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2491 TrackBits pbs = _settings_client.gui.show_track_reservation ? GetRailReservationTrackBits(ti->tile) : TRACK_BIT_NONE;
2493 if (track == TRACK_BIT_NONE) {
2494 /* Half-tile foundation, no track here? */
2495 } else if (ti->tileh == SLOPE_NW && track == TRACK_BIT_Y) {
2496 DrawGroundSprite(ground + RTO_SLOPE_NW, PAL_NONE);
2497 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NW, PALETTE_CRASH);
2498 } else if (ti->tileh == SLOPE_NE && track == TRACK_BIT_X) {
2499 DrawGroundSprite(ground + RTO_SLOPE_NE, PAL_NONE);
2500 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NE, PALETTE_CRASH);
2501 } else if (ti->tileh == SLOPE_SE && track == TRACK_BIT_Y) {
2502 DrawGroundSprite(ground + RTO_SLOPE_SE, PAL_NONE);
2503 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SE, PALETTE_CRASH);
2504 } else if (ti->tileh == SLOPE_SW && track == TRACK_BIT_X) {
2505 DrawGroundSprite(ground + RTO_SLOPE_SW, PAL_NONE);
2506 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SW, PALETTE_CRASH);
2507 } else {
2508 switch (track) {
2509 /* Draw single ground sprite when not overlapping. No track overlay
2510 * is necessary for these sprites. */
2511 case TRACK_BIT_X: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2512 case TRACK_BIT_Y: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2513 case TRACK_BIT_UPPER: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N); break;
2514 case TRACK_BIT_LOWER: DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2515 case TRACK_BIT_RIGHT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E); break;
2516 case TRACK_BIT_LEFT: DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2517 case TRACK_BIT_CROSS: DrawGroundSprite(ground + RTO_CROSSING_XY, PAL_NONE); break;
2518 case TRACK_BIT_HORZ: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N);
2519 DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2520 case TRACK_BIT_VERT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E);
2521 DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2523 default:
2524 /* We're drawing a junction tile */
2525 if ((track & TRACK_BIT_3WAY_NE) == 0) {
2526 DrawGroundSprite(ground + RTO_JUNCTION_SW, PAL_NONE);
2527 } else if ((track & TRACK_BIT_3WAY_SW) == 0) {
2528 DrawGroundSprite(ground + RTO_JUNCTION_NE, PAL_NONE);
2529 } else if ((track & TRACK_BIT_3WAY_NW) == 0) {
2530 DrawGroundSprite(ground + RTO_JUNCTION_SE, PAL_NONE);
2531 } else if ((track & TRACK_BIT_3WAY_SE) == 0) {
2532 DrawGroundSprite(ground + RTO_JUNCTION_NW, PAL_NONE);
2533 } else {
2534 DrawGroundSprite(ground + RTO_JUNCTION_NSEW, PAL_NONE);
2537 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2538 track &= ~pbs;
2540 /* Draw regular track bits */
2541 if (track & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PAL_NONE);
2542 if (track & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PAL_NONE);
2543 if (track & TRACK_BIT_UPPER) DrawGroundSprite(overlay + RTO_N, PAL_NONE);
2544 if (track & TRACK_BIT_LOWER) DrawGroundSprite(overlay + RTO_S, PAL_NONE);
2545 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(overlay + RTO_E, PAL_NONE);
2546 if (track & TRACK_BIT_LEFT) DrawGroundSprite(overlay + RTO_W, PAL_NONE);
2549 /* Draw reserved track bits */
2550 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2551 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2552 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2553 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2554 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2555 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2558 if (IsValidCorner(halftile_corner)) {
2559 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2560 overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY, TCX_UPPER_HALFTILE);
2561 ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND, TCX_UPPER_HALFTILE);
2563 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2564 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2566 SpriteID image;
2567 switch (rgt) {
2568 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2569 case RAIL_GROUND_ICE_DESERT:
2570 case RAIL_GROUND_HALF_SNOW: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2571 default: image = SPR_FLAT_GRASS_TILE; break;
2574 image += SlopeToSpriteOffset(fake_slope);
2576 DrawGroundSprite(image, PAL_NONE, &(_halftile_sub_sprite[halftile_corner]));
2578 track = CornerToTrackBits(halftile_corner);
2580 int offset;
2581 switch (track) {
2582 default: NOT_REACHED();
2583 case TRACK_BIT_UPPER: offset = RTO_N; break;
2584 case TRACK_BIT_LOWER: offset = RTO_S; break;
2585 case TRACK_BIT_RIGHT: offset = RTO_E; break;
2586 case TRACK_BIT_LEFT: offset = RTO_W; break;
2589 DrawTrackSprite(ground + offset, PAL_NONE, ti, fake_slope);
2590 if (_settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, track)) {
2591 DrawTrackSprite(overlay + offset, PALETTE_CRASH, ti, fake_slope);
2597 * Draw ground sprite and track bits
2598 * @param ti TileInfo
2599 * @param track TrackBits to draw
2601 static void DrawTrackBits(TileInfo *ti, TrackBits track)
2603 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2605 if (rti->UsesOverlay()) {
2606 DrawTrackBitsOverlay(ti, track, rti);
2607 if (_settings_client.gui.show_track_overgrowth) DrawTrackGrowth(ti, track);
2608 return;
2611 RailGroundType rgt = GetRailGroundType(ti->tile);
2612 Foundation f = GetRailFoundation(ti->tileh, track);
2613 Corner halftile_corner = CORNER_INVALID;
2615 if (IsNonContinuousFoundation(f)) {
2616 /* Save halftile corner */
2617 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2618 /* Draw lower part first */
2619 track &= ~CornerToTrackBits(halftile_corner);
2620 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2623 DrawFoundation(ti, f);
2624 /* DrawFoundation modifies ti */
2626 SpriteID image;
2627 PaletteID pal = PAL_NONE;
2628 const SubSprite *sub = nullptr;
2629 bool junction = false;
2631 /* Select the sprite to use. */
2632 if (track == 0) {
2633 /* Clear ground (only track on halftile foundation) */
2634 if (rgt == RAIL_GROUND_WATER) {
2635 if (IsSteepSlope(ti->tileh)) {
2636 DrawShoreTile(ti->tileh);
2637 image = 0;
2638 } else {
2639 image = SPR_FLAT_WATER_TILE;
2641 } else {
2642 switch (rgt) {
2643 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2644 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2645 default: image = SPR_FLAT_GRASS_TILE; break;
2647 image += SlopeToSpriteOffset(ti->tileh);
2649 } else {
2650 if (ti->tileh != SLOPE_FLAT) {
2651 /* track on non-flat ground */
2652 image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
2653 } else {
2654 /* track on flat ground */
2655 (image = rti->base_sprites.track_y, track == TRACK_BIT_Y) ||
2656 (image++, track == TRACK_BIT_X) ||
2657 (image++, track == TRACK_BIT_UPPER) ||
2658 (image++, track == TRACK_BIT_LOWER) ||
2659 (image++, track == TRACK_BIT_RIGHT) ||
2660 (image++, track == TRACK_BIT_LEFT) ||
2661 (image++, track == TRACK_BIT_CROSS) ||
2663 (image = rti->base_sprites.track_ns, track == TRACK_BIT_HORZ) ||
2664 (image++, track == TRACK_BIT_VERT) ||
2666 (junction = true, false) ||
2667 (image = rti->base_sprites.ground, (track & TRACK_BIT_3WAY_NE) == 0) ||
2668 (image++, (track & TRACK_BIT_3WAY_SW) == 0) ||
2669 (image++, (track & TRACK_BIT_3WAY_NW) == 0) ||
2670 (image++, (track & TRACK_BIT_3WAY_SE) == 0) ||
2671 (image++, true);
2674 switch (rgt) {
2675 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2676 case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
2677 case RAIL_GROUND_WATER: {
2678 /* three-corner-raised slope */
2679 DrawShoreTile(ti->tileh);
2680 Corner track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2681 sub = &(_halftile_sub_sprite[track_corner]);
2682 break;
2684 default: break;
2688 if (image != 0) DrawGroundSprite(image, pal, sub);
2690 /* Draw track pieces individually for junction tiles */
2691 if (junction) {
2692 if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
2693 if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
2694 if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
2695 if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
2696 if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
2697 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
2700 /* PBS debugging, draw reserved tracks darker */
2701 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
2702 /* Get reservation, but mask track on halftile slope */
2703 TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
2704 if (pbs & TRACK_BIT_X) {
2705 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2706 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2707 } else {
2708 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2711 if (pbs & TRACK_BIT_Y) {
2712 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2713 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2714 } else {
2715 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2718 if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
2719 if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
2720 if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
2721 if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, nullptr, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
2724 if (IsValidCorner(halftile_corner)) {
2725 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2727 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2728 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2729 image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
2730 pal = PAL_NONE;
2731 switch (rgt) {
2732 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2733 case RAIL_GROUND_ICE_DESERT:
2734 case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
2735 default: break;
2737 DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
2739 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
2740 static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
2741 DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, nullptr, 0, -(int)TILE_HEIGHT);
2745 /* Draw track overgrowth */
2746 if (_settings_client.gui.show_track_overgrowth) DrawTrackGrowth(ti, track);
2749 static void DrawSignals(TileIndex tile, TrackBits rails, const RailtypeInfo *rti)
2751 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2753 if (!(rails & TRACK_BIT_Y)) {
2754 if (!(rails & TRACK_BIT_X)) {
2755 if (rails & TRACK_BIT_LEFT) {
2756 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
2757 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
2759 if (rails & TRACK_BIT_RIGHT) {
2760 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
2761 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
2763 if (rails & TRACK_BIT_UPPER) {
2764 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
2765 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
2767 if (rails & TRACK_BIT_LOWER) {
2768 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
2769 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
2771 } else {
2772 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
2773 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
2775 } else {
2776 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
2777 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
2781 static void DrawTile_Track(TileInfo *ti)
2783 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2785 _drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
2787 if (IsPlainRail(ti->tile)) {
2788 TrackBits rails = GetTrackBits(ti->tile);
2790 DrawTrackBits(ti, rails);
2792 if (HasBit(_display_opt, DO_RAIL_FENCES)) DrawTrackDetails(ti, rti);
2794 DrawOverlay(ti, MP_RAILWAY);
2796 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2799 if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails, rti);
2800 } else {
2801 /* draw depot */
2802 const DrawTileSprites *dts;
2803 PaletteID pal = PAL_NONE;
2804 SpriteID relocation;
2806 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
2808 if (IsInvisibilitySet(TO_BUILDINGS)) {
2809 /* Draw rail instead of depot */
2810 dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
2811 } else {
2812 dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
2815 SpriteID image;
2816 if (rti->UsesOverlay()) {
2817 image = SPR_FLAT_GRASS_TILE;
2818 } else {
2819 image = dts->ground.sprite;
2820 if (image != SPR_FLAT_GRASS_TILE) image += rti->GetRailtypeSpriteOffset();
2823 // Adjust ground tile for desert and snow.
2824 if (IsSnowRailGround(ti->tile)) {
2825 if (image != SPR_FLAT_GRASS_TILE) {
2826 image += rti->snow_offset; // tile with tracks
2827 } else {
2828 image = SPR_FLAT_SNOW_DESERT_TILE; // flat ground
2832 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
2834 if (rti->UsesOverlay()) {
2835 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2837 switch (GetRailDepotDirection(ti->tile)) {
2838 case DIAGDIR_NE:
2839 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2840 FALLTHROUGH;
2841 case DIAGDIR_SW:
2842 DrawGroundSprite(ground + RTO_X, PAL_NONE);
2843 break;
2844 case DIAGDIR_NW:
2845 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2846 FALLTHROUGH;
2847 case DIAGDIR_SE:
2848 DrawGroundSprite(ground + RTO_Y, PAL_NONE);
2849 break;
2850 default:
2851 break;
2854 if (_settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2855 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2857 switch (GetRailDepotDirection(ti->tile)) {
2858 case DIAGDIR_NE:
2859 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2860 FALLTHROUGH;
2861 case DIAGDIR_SW:
2862 DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2863 break;
2864 case DIAGDIR_NW:
2865 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2866 FALLTHROUGH;
2867 case DIAGDIR_SE:
2868 DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2869 break;
2870 default:
2871 break;
2874 } else {
2875 /* PBS debugging, draw reserved tracks darker */
2876 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2877 switch (GetRailDepotDirection(ti->tile)) {
2878 case DIAGDIR_NE:
2879 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2880 FALLTHROUGH;
2881 case DIAGDIR_SW:
2882 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2883 break;
2884 case DIAGDIR_NW:
2885 if (!IsInvisibilitySet(TO_BUILDINGS)) break;
2886 FALLTHROUGH;
2887 case DIAGDIR_SE:
2888 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2889 break;
2890 default:
2891 break;
2895 int depot_sprite = GetCustomRailSprite(rti, ti->tile, RTSG_DEPOT);
2896 relocation = depot_sprite != 0 ? depot_sprite - SPR_RAIL_DEPOT_SE_1 : rti->GetRailtypeSpriteOffset();
2898 DrawOverlay(ti, MP_RAILWAY);
2900 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2902 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, _drawtile_track_palette);
2904 DrawBridgeMiddle(ti);
2907 void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
2909 const DrawTileSprites *dts = &_depot_gfx_table[dir];
2910 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
2911 SpriteID image = rti->UsesOverlay() ? SPR_FLAT_GRASS_TILE : dts->ground.sprite;
2912 uint32 offset = rti->GetRailtypeSpriteOffset();
2914 if (image != SPR_FLAT_GRASS_TILE) image += offset;
2915 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
2917 DrawSprite(image, PAL_NONE, x, y);
2919 if (rti->UsesOverlay()) {
2920 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2922 switch (dir) {
2923 case DIAGDIR_SW: DrawSprite(ground + RTO_X, PAL_NONE, x, y); break;
2924 case DIAGDIR_SE: DrawSprite(ground + RTO_Y, PAL_NONE, x, y); break;
2925 default: break;
2928 int depot_sprite = GetCustomRailSprite(rti, INVALID_TILE, RTSG_DEPOT);
2929 if (depot_sprite != 0) offset = depot_sprite - SPR_RAIL_DEPOT_SE_1;
2931 DrawRailTileSeqInGUI(x, y, dts, offset, 0, palette);
2934 static int GetSlopePixelZ_Track(TileIndex tile, uint x, uint y)
2936 if (IsPlainRail(tile)) {
2937 int z;
2938 Slope tileh = GetTilePixelSlope(tile, &z);
2939 if (tileh == SLOPE_FLAT) return z;
2941 z += ApplyPixelFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
2942 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2943 } else {
2944 return GetTileMaxPixelZ(tile);
2948 static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
2950 return IsPlainRail(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
2953 void AgeTrack(TileIndex ti)
2955 assert(IsPlainRailTile(ti));
2957 byte age = GetRailAge(ti);
2959 const byte maxi = 255;
2960 if (age == maxi)
2961 return;
2963 byte inv = maxi - age;
2965 static byte shift = 7;
2966 byte delta = max(1, inv >> shift);
2967 inv -= delta;
2969 age = maxi - inv;
2971 byte old_growth = GetTrackGrowthPhase(ti);
2973 SetRailAge(ti, age);
2975 /* If rounded growth amount changes, redraw */
2976 if (GetTrackGrowthPhase(ti) != old_growth)
2977 MarkTileDirtyByTile(ti);
2980 static void TileLoop_Track(TileIndex tile)
2982 if (IsPlainRailTile(tile)) AgeTrack(tile);
2984 RailGroundType old_ground = GetRailGroundType(tile);
2985 RailGroundType new_ground;
2987 if (old_ground == RAIL_GROUND_WATER) {
2988 TileLoop_Water(tile);
2989 return;
2992 switch (_settings_game.game_creation.landscape) {
2993 case LT_ARCTIC: {
2994 int z;
2995 Slope slope = GetTileSlope(tile, &z);
2996 bool half = false;
2998 /* for non-flat track, use lower part of track
2999 * in other cases, use the highest part with track */
3000 if (IsPlainRail(tile)) {
3001 TrackBits track = GetTrackBits(tile);
3002 Foundation f = GetRailFoundation(slope, track);
3004 switch (f) {
3005 case FOUNDATION_NONE:
3006 /* no foundation - is the track on the upper side of three corners raised tile? */
3007 if (slope != SLOPE_FLAT) z++;
3008 break;
3010 case FOUNDATION_INCLINED_X:
3011 case FOUNDATION_INCLINED_Y:
3012 /* sloped track - is it on a steep slope? */
3013 if (IsSteepSlope(slope)) z++;
3014 break;
3016 case FOUNDATION_STEEP_LOWER:
3017 /* only lower part of steep slope */
3018 z++;
3019 break;
3021 default:
3022 /* if it is a steep slope, then there is a track on higher part */
3023 if (IsSteepSlope(slope)) z++;
3024 z++;
3025 break;
3028 half = IsInsideMM(f, FOUNDATION_STEEP_BOTH, FOUNDATION_HALFTILE_N + 1);
3029 } else {
3030 /* is the depot on a non-flat tile? */
3031 if (slope != SLOPE_FLAT) z++;
3034 /* 'z' is now the lowest part of the highest track bit -
3035 * for sloped track, it is 'z' of lower part
3036 * for two track bits, it is 'z' of higher track bit
3037 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
3038 if (z > GetSnowLine()) {
3039 if (half && z - GetSnowLine() == 1) {
3040 /* track on non-continuous foundation, lower part is not under snow */
3041 new_ground = RAIL_GROUND_HALF_SNOW;
3042 } else {
3043 new_ground = RAIL_GROUND_ICE_DESERT;
3045 goto set_ground;
3047 break;
3050 case LT_TROPIC:
3051 if (GetTropicZone(tile) == TROPICZONE_DESERT) {
3052 new_ground = RAIL_GROUND_ICE_DESERT;
3053 goto set_ground;
3055 break;
3058 new_ground = RAIL_GROUND_GRASS;
3060 if (IsPlainRail(tile) && old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
3061 /* determine direction of fence */
3062 TrackBits rail = GetTrackBits(tile);
3064 Owner owner = GetTileOwner(tile);
3065 byte fences = 0;
3067 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
3068 static const TrackBits dir_to_trackbits[DIAGDIR_END] = {TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW};
3070 /* Track bit on this edge => no fence. */
3071 if ((rail & dir_to_trackbits[d]) != TRACK_BIT_NONE) continue;
3073 TileIndex tile2 = tile + TileOffsByDiagDir(d);
3075 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
3076 if (!IsValidTile(tile2) || IsTileType(tile2, MP_HOUSE) || IsTileType(tile2, MP_INDUSTRY) ||
3077 IsTileType(tile2, MP_ROAD) || (IsTileType(tile2, MP_OBJECT) && !IsObjectType(tile2, OBJECT_OWNED_LAND)) || IsTileType(tile2, MP_TUNNELBRIDGE) || !IsTileOwner(tile2, owner)) {
3078 fences |= 1 << d;
3082 switch (fences) {
3083 case 0: break;
3084 case (1 << DIAGDIR_NE): new_ground = RAIL_GROUND_FENCE_NE; break;
3085 case (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_SE; break;
3086 case (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_SW; break;
3087 case (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_NW; break;
3088 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_NESW; break;
3089 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_SENW; break;
3090 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_VERT1; break;
3091 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
3092 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
3093 case (1 << DIAGDIR_SW) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_VERT2; break;
3094 default: NOT_REACHED();
3098 set_ground:
3099 if (old_ground != new_ground) {
3100 SetRailGroundType(tile, new_ground);
3101 MarkTileDirtyByTile(tile);
3106 static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3108 /* Case of half tile slope with water. */
3109 if (mode == TRANSPORT_WATER && IsPlainRail(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
3110 TrackBits tb = GetTrackBits(tile);
3111 switch (tb) {
3112 default: NOT_REACHED();
3113 case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
3114 case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
3115 case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
3116 case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
3118 return CombineTrackStatus(TrackBitsToTrackdirBits(tb), TRACKDIR_BIT_NONE);
3121 if (mode != TRANSPORT_RAIL) return 0;
3123 TrackBits trackbits = TRACK_BIT_NONE;
3124 TrackdirBits red_signals = TRACKDIR_BIT_NONE;
3126 switch (GetRailTileType(tile)) {
3127 default: NOT_REACHED();
3128 case RAIL_TILE_NORMAL:
3129 trackbits = GetTrackBits(tile);
3130 break;
3132 case RAIL_TILE_SIGNALS: {
3133 trackbits = GetTrackBits(tile);
3134 byte a = GetPresentSignals(tile);
3135 uint b = GetSignalStates(tile);
3137 b &= a;
3139 /* When signals are not present (in neither direction),
3140 * we pretend them to be green. Otherwise, it depends on
3141 * the signal type. For signals that are only active from
3142 * one side, we set the missing signals explicitly to
3143 * `green'. Otherwise, they implicitly become `red'. */
3144 if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
3145 if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
3147 if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
3148 if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
3149 if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
3150 if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
3152 break;
3155 case RAIL_TILE_DEPOT: {
3156 DiagDirection dir = GetRailDepotDirection(tile);
3158 if (side != INVALID_DIAGDIR && side != dir) break;
3160 trackbits = DiagDirToDiagTrackBits(dir);
3161 break;
3165 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
3168 static bool ClickTile_Track(TileIndex tile)
3170 if (_ctrl_pressed && IsPlainRailTile(tile)) {
3171 TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
3173 if (trackbits & TRACK_BIT_VERT) { // N-S direction
3174 trackbits = (_tile_fract_coords.x <= _tile_fract_coords.y) ? TRACK_BIT_RIGHT : TRACK_BIT_LEFT;
3177 if (trackbits & TRACK_BIT_HORZ) { // E-W direction
3178 trackbits = (_tile_fract_coords.x + _tile_fract_coords.y <= 15) ? TRACK_BIT_UPPER : TRACK_BIT_LOWER;
3181 Track track = FindFirstTrack(trackbits);
3182 if (HasTrack(tile, track) && HasSignalOnTrack(tile, track)) {
3183 if (GetSignalType(tile, track) == SIGTYPE_LOGIC) {
3184 SignalProgram* program = FindSignalProgram(tile, track);
3185 if (program != nullptr) {
3186 ShowSignalProgramWindow(program);
3188 } else {
3189 ShowTraceRestrictProgramWindow(tile, track);
3191 return true;
3195 if (!IsRailDepot(tile)) return false;
3197 ShowDepotWindow(tile, VEH_TRAIN);
3198 return true;
3201 static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
3203 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3204 td->rail_speed = rti->max_speed;
3205 td->railtype = rti->strings.name;
3206 td->owner[0] = GetTileOwner(tile);
3207 switch (GetRailTileType(tile)) {
3208 case RAIL_TILE_NORMAL:
3209 td->str = STR_LAI_RAIL_DESCRIPTION_TRACK;
3210 break;
3212 case RAIL_TILE_SIGNALS: {
3213 static const StringID signal_type[SIGTYPE_END][SIGTYPE_END] = {
3215 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS,
3216 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
3217 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
3218 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
3219 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
3220 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
3221 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_LOGICSIGNALS
3224 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
3225 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS,
3226 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
3227 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
3228 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
3229 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
3230 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_LOGICSIGNALS
3233 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
3234 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
3235 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS,
3236 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
3237 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
3238 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
3239 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_LOGICSIGNALS
3242 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
3243 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
3244 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
3245 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS,
3246 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
3247 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
3248 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_LOGICSIGNALS
3251 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
3252 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
3253 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
3254 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
3255 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS,
3256 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
3257 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_LOGICSIGNALS
3260 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
3261 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
3262 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
3263 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
3264 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
3265 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS,
3266 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRY_LOGICSIGNALS
3269 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_LOGICSIGNALS,
3270 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_LOGICSIGNALS,
3271 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_LOGICSIGNALS,
3272 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_LOGICSIGNALS,
3273 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_LOGICSIGNALS,
3274 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRY_LOGICSIGNALS,
3275 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_LOGICSIGNALS
3279 SignalType primary_signal;
3280 SignalType secondary_signal;
3281 if (HasSignalOnTrack(tile, TRACK_UPPER)) {
3282 primary_signal = GetSignalType(tile, TRACK_UPPER);
3283 secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
3284 } else {
3285 secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
3288 td->str = signal_type[secondary_signal][primary_signal];
3290 if (IsRestrictedSignal(tile)) {
3291 SetDParamX(td->dparam, 0, td->str);
3292 SetDParamX(td->dparam, 1, rti->strings.name);
3293 td->str = STR_LAI_RAIL_DESCRIPTION_RESTRICTED_SIGNAL;
3295 break;
3298 case RAIL_TILE_DEPOT:
3299 td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
3300 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
3301 if (td->rail_speed > 0) {
3302 td->rail_speed = min(td->rail_speed, 61);
3303 } else {
3304 td->rail_speed = 61;
3307 td->build_date = Depot::GetByTile(tile)->build_date;
3308 break;
3310 default:
3311 NOT_REACHED();
3315 static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
3317 if (!IsTileOwner(tile, old_owner)) return;
3319 if (new_owner != INVALID_OWNER) {
3320 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
3321 uint num_pieces = 1;
3322 if (IsPlainRail(tile)) {
3323 TrackBits bits = GetTrackBits(tile);
3324 num_pieces = CountBits(bits);
3325 if (TracksOverlap(bits)) num_pieces *= num_pieces;
3327 RailType rt = GetRailType(tile);
3328 Company::Get(old_owner)->infrastructure.rail[rt] -= num_pieces;
3329 Company::Get(new_owner)->infrastructure.rail[rt] += num_pieces;
3331 if (HasSignals(tile)) {
3332 uint num_sigs = CountBits(GetPresentSignals(tile));
3333 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
3334 Company::Get(new_owner)->infrastructure.signal += num_sigs;
3337 SetTileOwner(tile, new_owner);
3338 } else {
3339 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
3343 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
3344 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
3345 static const int8 _deltacoord_leaveoffset[8] = {
3346 -1, 0, 1, 0, /* x */
3347 0, 1, 0, -1 /* y */
3352 * Compute number of ticks when next wagon will leave a depot.
3353 * Negative means next wagon should have left depot n ticks before.
3354 * @param v vehicle outside (leaving) the depot
3355 * @return number of ticks when the next wagon will leave
3357 int TicksToLeaveDepot(const Train *v)
3359 DiagDirection dir = GetRailDepotDirection(v->tile);
3360 int length = v->CalcNextVehicleOffset();
3362 switch (dir) {
3363 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
3364 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
3365 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
3366 default:
3367 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
3370 return 0; // make compilers happy
3374 * Tile callback routine when vehicle enters tile
3375 * @see vehicle_enter_tile_proc
3377 static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int x, int y)
3379 /* this routine applies only to trains in depot tiles */
3380 if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
3382 Train *v = Train::From(u);
3384 /* depot direction */
3385 DiagDirection dir = GetRailDepotDirection(tile);
3387 /* Calculate the point where the following wagon should be activated. */
3388 int length = v->CalcNextVehicleOffset();
3390 byte fract_coord_leave =
3391 ((_fractcoords_enter[dir] & 0x0F) + // x
3392 (length + 1) * _deltacoord_leaveoffset[dir]) +
3393 (((_fractcoords_enter[dir] >> 4) + // y
3394 ((length + 1) * _deltacoord_leaveoffset[dir + 4])) << 4);
3396 byte fract_coord = (x & 0xF) + ((y & 0xF) << 4);
3398 if (_fractcoords_behind[dir] == fract_coord) {
3399 /* make sure a train is not entering the tile from behind */
3400 return VETSB_CANNOT_ENTER;
3401 } else if (_fractcoords_enter[dir] == fract_coord) {
3402 if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) {
3403 /* enter the depot */
3404 v->track = TRACK_BIT_DEPOT,
3405 v->vehstatus |= VS_HIDDEN; // hide it
3406 v->direction = ReverseDir(v->direction);
3407 if (v->Next() == nullptr) VehicleEnterDepot(v->First());
3408 v->tile = tile;
3410 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
3411 return VETSB_ENTERED_WORMHOLE;
3413 } else if (fract_coord_leave == fract_coord) {
3414 if (DiagDirToDir(dir) == v->direction) {
3415 /* leave the depot? */
3416 if ((v = v->Next()) != nullptr) {
3417 v->vehstatus &= ~VS_HIDDEN;
3418 v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
3423 return VETSB_CONTINUE;
3427 * Tests if autoslope is allowed.
3429 * @param tile The tile.
3430 * @param flags Terraform command flags.
3431 * @param z_old Old TileZ.
3432 * @param tileh_old Old TileSlope.
3433 * @param z_new New TileZ.
3434 * @param tileh_new New TileSlope.
3435 * @param rail_bits Trackbits.
3437 static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old, Slope tileh_old, int z_new, Slope tileh_new, TrackBits rail_bits)
3439 if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return CommandError(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3441 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
3442 if (CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile).Failed()) return CommandError(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3444 /* Get the slopes on top of the foundations */
3445 z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
3446 z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
3448 Corner track_corner;
3449 switch (rail_bits) {
3450 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
3451 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
3452 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
3453 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
3455 /* Surface slope must not be changed */
3456 default:
3457 if (z_old != z_new || tileh_old != tileh_new) return CommandError(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3458 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3461 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
3462 z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
3463 z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
3464 if (z_old != z_new) return CommandError(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
3466 CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3467 /* Make the ground dirty, if surface slope has changed */
3468 if (tileh_old != tileh_new) {
3469 /* If there is flat water on the lower halftile add the cost for clearing it */
3470 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price[PR_CLEAR_WATER]);
3471 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3473 return cost;
3477 * Test-procedure for HasVehicleOnPos to check for a ship.
3479 static Vehicle *EnsureNoShipProc(Vehicle *v, void *data)
3481 return v->type == VEH_SHIP ? v : nullptr;
3484 static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
3486 int z_old;
3487 Slope tileh_old = GetTileSlope(tile, &z_old);
3488 if (IsPlainRail(tile)) {
3489 TrackBits rail_bits = GetTrackBits(tile);
3490 /* Is there flat water on the lower halftile that must be cleared expensively? */
3491 bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
3493 /* Allow clearing the water only if there is no ship */
3494 if (was_water && HasVehicleOnPos(tile, nullptr, &EnsureNoShipProc)) return CommandError(STR_ERROR_SHIP_IN_THE_WAY);
3496 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
3497 CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
3499 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
3500 Corner allowed_corner;
3501 switch (rail_bits) {
3502 case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
3503 case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
3504 case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
3505 case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
3506 default: return autoslope_result;
3509 Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
3511 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3512 if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
3514 /* Everything is valid, which only changes allowed_corner */
3515 for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
3516 if (allowed_corner == corner) continue;
3517 if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
3520 /* Make the ground dirty */
3521 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3523 /* allow terraforming */
3524 return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0);
3525 } else if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() &&
3526 AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) {
3527 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3529 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3533 extern const TileTypeProcs _tile_type_rail_procs = {
3534 DrawTile_Track, // draw_tile_proc
3535 GetSlopePixelZ_Track, // get_slope_z_proc
3536 ClearTile_Track, // clear_tile_proc
3537 nullptr, // add_accepted_cargo_proc
3538 GetTileDesc_Track, // get_tile_desc_proc
3539 GetTileTrackStatus_Track, // get_tile_track_status_proc
3540 ClickTile_Track, // click_tile_proc
3541 nullptr, // animate_tile_proc
3542 TileLoop_Track, // tile_loop_proc
3543 ChangeTileOwner_Track, // change_tile_owner_proc
3544 nullptr, // add_produced_cargo_proc
3545 VehicleEnter_Track, // vehicle_enter_tile_proc
3546 GetFoundation_Track, // get_foundation_proc
3547 TerraformTile_Track, // terraform_tile_proc