(svn r27756) -Codechange: Add StringTab enum
[openttd.git] / src / rail_cmd.cpp
bloba5face14c53603b2e05912a33399af98de09cd61
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 "vehicle_func.h"
25 #include "sound_func.h"
26 #include "tunnelbridge.h"
27 #include "elrail_func.h"
28 #include "town.h"
29 #include "pbs.h"
30 #include "company_base.h"
31 #include "core/backup_type.hpp"
32 #include "date_func.h"
33 #include "strings_func.h"
34 #include "company_gui.h"
35 #include "object_map.h"
37 #include "table/strings.h"
38 #include "table/railtypes.h"
39 #include "table/track_land.h"
41 #include "safeguards.h"
43 /** Helper type for lists/vectors of trains */
44 typedef SmallVector<Train *, 16> TrainList;
46 RailtypeInfo _railtypes[RAILTYPE_END];
47 RailType _sorted_railtypes[RAILTYPE_END];
48 uint8 _sorted_railtypes_size;
50 /** Enum holding the signal offset in the sprite sheet according to the side it is representing. */
51 enum SignalOffsets {
52 SIGNAL_TO_SOUTHWEST,
53 SIGNAL_TO_NORTHEAST,
54 SIGNAL_TO_SOUTHEAST,
55 SIGNAL_TO_NORTHWEST,
56 SIGNAL_TO_EAST,
57 SIGNAL_TO_WEST,
58 SIGNAL_TO_SOUTH,
59 SIGNAL_TO_NORTH,
62 /**
63 * Reset all rail type information to its default values.
65 void ResetRailTypes()
67 assert_compile(lengthof(_original_railtypes) <= lengthof(_railtypes));
69 uint i = 0;
70 for (; i < lengthof(_original_railtypes); i++) _railtypes[i] = _original_railtypes[i];
72 static const RailtypeInfo empty_railtype = {
73 {0,0,0,0,0,0,0,0,0,0,0,0},
74 {0,0,0,0,0,0,0,0,{}},
75 {0,0,0,0,0,0,0,0},
76 {0,0,0,0,0,0},
77 0, RAILTYPES_NONE, RAILTYPES_NONE, 0, 0, 0, RTFB_NONE, 0, 0, 0, 0, 0,
78 RailTypeLabelList(), 0, 0, RAILTYPES_NONE, RAILTYPES_NONE, 0,
79 {}, {} };
80 for (; i < lengthof(_railtypes); i++) _railtypes[i] = empty_railtype;
83 void ResolveRailTypeGUISprites(RailtypeInfo *rti)
85 SpriteID cursors_base = GetCustomRailSprite(rti, INVALID_TILE, RTSG_CURSORS);
86 if (cursors_base != 0) {
87 rti->gui_sprites.build_ns_rail = cursors_base + 0;
88 rti->gui_sprites.build_x_rail = cursors_base + 1;
89 rti->gui_sprites.build_ew_rail = cursors_base + 2;
90 rti->gui_sprites.build_y_rail = cursors_base + 3;
91 rti->gui_sprites.auto_rail = cursors_base + 4;
92 rti->gui_sprites.build_depot = cursors_base + 5;
93 rti->gui_sprites.build_tunnel = cursors_base + 6;
94 rti->gui_sprites.convert_rail = cursors_base + 7;
95 rti->cursor.rail_ns = cursors_base + 8;
96 rti->cursor.rail_swne = cursors_base + 9;
97 rti->cursor.rail_ew = cursors_base + 10;
98 rti->cursor.rail_nwse = cursors_base + 11;
99 rti->cursor.autorail = cursors_base + 12;
100 rti->cursor.depot = cursors_base + 13;
101 rti->cursor.tunnel = cursors_base + 14;
102 rti->cursor.convert = cursors_base + 15;
105 /* Array of default GUI signal sprite numbers. */
106 const SpriteID _signal_lookup[2][SIGTYPE_END] = {
107 {SPR_IMG_SIGNAL_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_EXIT,
108 SPR_IMG_SIGNAL_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY},
110 {SPR_IMG_SIGNAL_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_EXIT,
111 SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY},
114 for (SignalType type = SIGTYPE_NORMAL; type < SIGTYPE_END; type = (SignalType)(type + 1)) {
115 for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) {
116 SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true);
117 SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true);
118 rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type];
119 rti->gui_sprites.signals[type][var][1] = (green != 0) ? green + SIGNAL_TO_SOUTH : _signal_lookup[var][type] + 1;
125 * Compare railtypes based on their sorting order.
126 * @param first The railtype to compare to.
127 * @param second The railtype to compare.
128 * @return True iff the first should be sorted before the second.
130 static int CDECL CompareRailTypes(const RailType *first, const RailType *second)
132 return GetRailTypeInfo(*first)->sorting_order - GetRailTypeInfo(*second)->sorting_order;
136 * Resolve sprites of custom rail types
138 void InitRailTypes()
140 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
141 RailtypeInfo *rti = &_railtypes[rt];
142 ResolveRailTypeGUISprites(rti);
145 _sorted_railtypes_size = 0;
146 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
147 if (_railtypes[rt].label != 0) {
148 _sorted_railtypes[_sorted_railtypes_size++] = rt;
151 QSortT(_sorted_railtypes, _sorted_railtypes_size, CompareRailTypes);
155 * Allocate a new rail type label
157 RailType AllocateRailType(RailTypeLabel label)
159 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
160 RailtypeInfo *rti = &_railtypes[rt];
162 if (rti->label == 0) {
163 /* Set up new rail type */
164 *rti = _original_railtypes[RAILTYPE_RAIL];
165 rti->label = label;
166 rti->alternate_labels.Clear();
168 /* Make us compatible with ourself. */
169 rti->powered_railtypes = (RailTypes)(1 << rt);
170 rti->compatible_railtypes = (RailTypes)(1 << rt);
172 /* We also introduce ourself. */
173 rti->introduces_railtypes = (RailTypes)(1 << rt);
175 /* Default sort order; order of allocation, but with some
176 * offsets so it's easier for NewGRF to pick a spot without
177 * changing the order of other (original) rail types.
178 * The << is so you can place other railtypes in between the
179 * other railtypes, the 7 is to be able to place something
180 * before the first (default) rail type. */
181 rti->sorting_order = rt << 4 | 7;
182 return rt;
186 return INVALID_RAILTYPE;
189 static const byte _track_sloped_sprites[14] = {
190 14, 15, 22, 13,
191 0, 21, 17, 12,
192 23, 0, 18, 20,
193 19, 16
197 /* 4
198 * ---------
199 * |\ /|
200 * | \ 1/ |
201 * | \ / |
202 * | \ / |
203 * 16| \ |32
204 * | / \2 |
205 * | / \ |
206 * | / \ |
207 * |/ \|
208 * ---------
214 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
215 * MAP3LO byte: abcd???? => Signal Exists?
216 * a and b are for diagonals, upper and left,
217 * one for each direction. (ie a == NE->SW, b ==
218 * SW->NE, or v.v., I don't know. b and c are
219 * similar for lower and right.
220 * MAP2 byte: ????abcd => Type of ground.
221 * MAP3LO byte: ????abcd => Type of rail.
222 * MAP5: 00abcdef => rail
223 * 01abcdef => rail w/ signals
224 * 10uuuuuu => unused
225 * 11uuuudd => rail depot
229 * Tests if a vehicle interacts with the specified track.
230 * All track bits interact except parallel #TRACK_BIT_HORZ or #TRACK_BIT_VERT.
232 * @param tile The tile.
233 * @param track The track.
234 * @return Succeeded command (no train found), or a failed command (a train was found).
236 static CommandCost EnsureNoTrainOnTrack(TileIndex tile, Track track)
238 TrackBits rail_bits = TrackToTrackBits(track);
239 return EnsureNoTrainOnTrackBits(tile, rail_bits);
243 * Check that the new track bits may be built.
244 * @param tile %Tile to build on.
245 * @param to_build New track bits.
246 * @param flags Flags of the operation.
247 * @return Succeeded or failed command.
249 static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
251 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
253 /* So, we have a tile with tracks on it (and possibly signals). Let's see
254 * what tracks first */
255 TrackBits current = GetTrackBits(tile); // The current track layout.
256 TrackBits future = current | to_build; // The track layout we want to build.
258 /* Are we really building something new? */
259 if (current == future) {
260 /* Nothing new is being built */
261 return_cmd_error(STR_ERROR_ALREADY_BUILT);
264 /* Let's see if we may build this */
265 if ((flags & DC_NO_RAIL_OVERLAP) || HasSignals(tile)) {
266 /* If we are not allowed to overlap (flag is on for ai companies or we have
267 * signals on the tile), check that */
268 if (future != TRACK_BIT_HORZ && future != TRACK_BIT_VERT) {
269 return_cmd_error((flags & DC_NO_RAIL_OVERLAP) ? STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION : STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
272 /* Normally, we may overlap and any combination is valid */
273 return CommandCost();
277 /** Valid TrackBits on a specific (non-steep)-slope without foundation */
278 static const TrackBits _valid_tracks_without_foundation[15] = {
279 TRACK_BIT_ALL,
280 TRACK_BIT_RIGHT,
281 TRACK_BIT_UPPER,
282 TRACK_BIT_X,
284 TRACK_BIT_LEFT,
285 TRACK_BIT_NONE,
286 TRACK_BIT_Y,
287 TRACK_BIT_LOWER,
289 TRACK_BIT_LOWER,
290 TRACK_BIT_Y,
291 TRACK_BIT_NONE,
292 TRACK_BIT_LEFT,
294 TRACK_BIT_X,
295 TRACK_BIT_UPPER,
296 TRACK_BIT_RIGHT,
299 /** Valid TrackBits on a specific (non-steep)-slope with leveled foundation */
300 static const TrackBits _valid_tracks_on_leveled_foundation[15] = {
301 TRACK_BIT_NONE,
302 TRACK_BIT_LEFT,
303 TRACK_BIT_LOWER,
304 TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
306 TRACK_BIT_RIGHT,
307 TRACK_BIT_ALL,
308 TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
309 TRACK_BIT_ALL,
311 TRACK_BIT_UPPER,
312 TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
313 TRACK_BIT_ALL,
314 TRACK_BIT_ALL,
316 TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
317 TRACK_BIT_ALL,
318 TRACK_BIT_ALL
322 * Checks if a track combination is valid on a specific slope and returns the needed foundation.
324 * @param tileh Tile slope.
325 * @param bits Trackbits.
326 * @return Needed foundation or FOUNDATION_INVALID if track/slope combination is not allowed.
328 Foundation GetRailFoundation(Slope tileh, TrackBits bits)
330 if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
332 if (IsSteepSlope(tileh)) {
333 /* Test for inclined foundations */
334 if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
335 if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
337 /* Get higher track */
338 Corner highest_corner = GetHighestSlopeCorner(tileh);
339 TrackBits higher_track = CornerToTrackBits(highest_corner);
341 /* Only higher track? */
342 if (bits == higher_track) return HalftileFoundation(highest_corner);
344 /* Overlap with higher track? */
345 if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
347 /* either lower track or both higher and lower track */
348 return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
349 } else {
350 if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
352 bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
354 Corner track_corner;
355 switch (bits) {
356 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
357 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
358 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
359 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
361 case TRACK_BIT_HORZ:
362 if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
363 if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
364 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
366 case TRACK_BIT_VERT:
367 if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
368 if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
369 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
371 case TRACK_BIT_X:
372 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_X;
373 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
375 case TRACK_BIT_Y:
376 if (IsSlopeWithOneCornerRaised(tileh)) return FOUNDATION_INCLINED_Y;
377 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
379 default:
380 return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
382 /* Single diagonal track */
384 /* Track must be at least valid on leveled foundation */
385 if (!valid_on_leveled) return FOUNDATION_INVALID;
387 /* If slope has three raised corners, build leveled foundation */
388 if (IsSlopeWithThreeCornersRaised(tileh)) return FOUNDATION_LEVELED;
390 /* If neighboured corners of track_corner are lowered, build halftile foundation */
391 if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
393 /* else special anti-zig-zag foundation */
394 return SpecialRailFoundation(track_corner);
400 * Tests if a track can be build on a tile.
402 * @param tileh Tile slope.
403 * @param rail_bits Tracks to build.
404 * @param existing Tracks already built.
405 * @param tile Tile (used for water test)
406 * @return Error message or cost for foundation building.
408 static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
410 /* don't allow building on the lower side of a coast */
411 if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
412 if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
415 Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
417 /* check track/slope combination */
418 if ((f_new == FOUNDATION_INVALID) ||
419 ((f_new != FOUNDATION_NONE) && (!_settings_game.construction.build_on_slopes))) {
420 return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
423 Foundation f_old = GetRailFoundation(tileh, existing);
424 return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
427 /* Validate functions for rail building */
428 static inline bool ValParamTrackOrientation(Track track)
430 return IsValidTrack(track);
434 * Build a single piece of rail
435 * @param tile tile to build on
436 * @param flags operation to perform
437 * @param p1 railtype of being built piece (normal, mono, maglev)
438 * @param p2 rail track to build
439 * @param text unused
440 * @return the cost of this operation or an error
442 CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
444 RailType railtype = Extract<RailType, 0, 4>(p1);
445 Track track = Extract<Track, 0, 3>(p2);
446 CommandCost cost(EXPENSES_CONSTRUCTION);
448 if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
450 Slope tileh = GetTileSlope(tile);
451 TrackBits trackbit = TrackToTrackBits(track);
453 switch (GetTileType(tile)) {
454 case MP_RAILWAY: {
455 CommandCost ret = CheckTileOwnership(tile);
456 if (ret.Failed()) return ret;
458 if (!IsPlainRail(tile)) return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); // just get appropriate error message
460 if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
462 ret = CheckTrackCombination(tile, trackbit, flags);
463 if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
464 if (ret.Failed()) return ret;
466 ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
467 if (ret.Failed()) return ret;
468 cost.AddCost(ret);
470 /* If the rail types don't match, try to convert only if engines of
471 * the new rail type are not powered on the present rail type and engines of
472 * the present rail type are powered on the new rail type. */
473 if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
474 if (HasPowerOnRail(GetRailType(tile), railtype)) {
475 ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
476 if (ret.Failed()) return ret;
477 cost.AddCost(ret);
478 } else {
479 return CMD_ERROR;
483 if (flags & DC_EXEC) {
484 SetRailGroundType(tile, RAIL_GROUND_BARREN);
485 TrackBits bits = GetTrackBits(tile);
486 SetTrackBits(tile, bits | trackbit);
487 /* Subtract old infrastructure count. */
488 uint pieces = CountBits(bits);
489 if (TracksOverlap(bits)) pieces *= pieces;
490 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
491 /* Add new infrastructure count. */
492 pieces = CountBits(bits | trackbit);
493 if (TracksOverlap(bits | trackbit)) pieces *= pieces;
494 Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
495 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
497 break;
500 case MP_ROAD: {
501 /* Level crossings may only be built on these slopes */
502 if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
504 CommandCost ret = EnsureNoVehicleOnGround(tile);
505 if (ret.Failed()) return ret;
507 if (IsNormalRoad(tile)) {
508 if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
510 if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
512 if (RailNoLevelCrossings(railtype)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
514 RoadTypes roadtypes = GetRoadTypes(tile);
515 RoadBits road = GetRoadBits(tile, ROADTYPE_ROAD);
516 RoadBits tram = GetRoadBits(tile, ROADTYPE_TRAM);
517 if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
518 (track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
519 Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
520 Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
521 /* Disallow breaking end-of-line of someone else
522 * so trams can still reverse on this tile. */
523 if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
524 CommandCost ret = CheckOwnership(tram_owner);
525 if (ret.Failed()) return ret;
527 /* Crossings must always have a road... */
528 uint num_new_road_pieces = 2 - CountBits(road);
529 if (road == ROAD_NONE) road_owner = _current_company;
530 roadtypes |= ROADTYPES_ROAD;
531 /* ...but tram is not required. */
532 uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
534 cost.AddCost((num_new_road_pieces + num_new_tram_pieces) * _price[PR_BUILD_ROAD]);
536 if (flags & DC_EXEC) {
537 MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtypes, GetTownIndex(tile));
538 UpdateLevelCrossing(tile, false);
539 Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
540 DirtyCompanyInfrastructureWindows(_current_company);
541 if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
542 Company::Get(road_owner)->infrastructure.road[ROADTYPE_ROAD] += num_new_road_pieces;
543 DirtyCompanyInfrastructureWindows(road_owner);
545 if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
546 Company::Get(tram_owner)->infrastructure.road[ROADTYPE_TRAM] += num_new_tram_pieces;
547 DirtyCompanyInfrastructureWindows(tram_owner);
550 break;
554 if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
555 return_cmd_error(STR_ERROR_ALREADY_BUILT);
557 /* FALL THROUGH */
560 default: {
561 /* Will there be flat water on the lower halftile? */
562 bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
564 CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
565 if (ret.Failed()) return ret;
566 cost.AddCost(ret);
568 ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
569 if (ret.Failed()) return ret;
570 cost.AddCost(ret);
572 if (water_ground) {
573 cost.AddCost(-_price[PR_CLEAR_WATER]);
574 cost.AddCost(_price[PR_CLEAR_ROUGH]);
577 if (flags & DC_EXEC) {
578 MakeRailNormal(tile, _current_company, trackbit, railtype);
579 if (water_ground) SetRailGroundType(tile, RAIL_GROUND_WATER);
580 Company::Get(_current_company)->infrastructure.rail[railtype]++;
581 DirtyCompanyInfrastructureWindows(_current_company);
583 break;
587 if (flags & DC_EXEC) {
588 MarkTileDirtyByTile(tile);
589 AddTrackToSignalBuffer(tile, track, _current_company);
590 YapfNotifyTrackLayoutChange(tile, track);
593 cost.AddCost(RailBuildCost(railtype));
594 return cost;
598 * Remove a single piece of track
599 * @param tile tile to remove track from
600 * @param flags operation to perform
601 * @param p1 unused
602 * @param p2 rail orientation
603 * @param text unused
604 * @return the cost of this operation or an error
606 CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
608 Track track = Extract<Track, 0, 3>(p2);
609 CommandCost cost(EXPENSES_CONSTRUCTION);
610 bool crossing = false;
612 if (!ValParamTrackOrientation(track)) return CMD_ERROR;
613 TrackBits trackbit = TrackToTrackBits(track);
615 /* Need to read tile owner now because it may change when the rail is removed
616 * Also, in case of floods, _current_company != owner
617 * There may be invalid tiletype even in exec run (when removing long track),
618 * so do not call GetTileOwner(tile) in any case here */
619 Owner owner = INVALID_OWNER;
621 Train *v = NULL;
623 switch (GetTileType(tile)) {
624 case MP_ROAD: {
625 if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
627 if (_current_company != OWNER_WATER) {
628 CommandCost ret = CheckTileOwnership(tile);
629 if (ret.Failed()) return ret;
632 if (!(flags & DC_BANKRUPT)) {
633 CommandCost ret = EnsureNoVehicleOnGround(tile);
634 if (ret.Failed()) return ret;
637 cost.AddCost(RailClearCost(GetRailType(tile)));
639 if (flags & DC_EXEC) {
640 if (HasReservedTracks(tile, trackbit)) {
641 v = GetTrainForReservation(tile, track);
642 if (v != NULL) FreeTrainTrackReservation(v);
644 owner = GetTileOwner(tile);
645 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
646 DirtyCompanyInfrastructureWindows(owner);
647 MakeRoadNormal(tile, GetCrossingRoadBits(tile), GetRoadTypes(tile), GetTownIndex(tile), GetRoadOwner(tile, ROADTYPE_ROAD), GetRoadOwner(tile, ROADTYPE_TRAM));
648 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
650 break;
653 case MP_RAILWAY: {
654 TrackBits present;
655 /* There are no rails present at depots. */
656 if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
658 if (_current_company != OWNER_WATER) {
659 CommandCost ret = CheckTileOwnership(tile);
660 if (ret.Failed()) return ret;
663 CommandCost ret = EnsureNoTrainOnTrack(tile, track);
664 if (ret.Failed()) return ret;
666 present = GetTrackBits(tile);
667 if ((present & trackbit) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
668 if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
670 cost.AddCost(RailClearCost(GetRailType(tile)));
672 /* Charge extra to remove signals on the track, if they are there */
673 if (HasSignalOnTrack(tile, track)) {
674 cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
677 if (flags & DC_EXEC) {
678 if (HasReservedTracks(tile, trackbit)) {
679 v = GetTrainForReservation(tile, track);
680 if (v != NULL) FreeTrainTrackReservation(v);
683 owner = GetTileOwner(tile);
685 /* Subtract old infrastructure count. */
686 uint pieces = CountBits(present);
687 if (TracksOverlap(present)) pieces *= pieces;
688 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
689 /* Add new infrastructure count. */
690 present ^= trackbit;
691 pieces = CountBits(present);
692 if (TracksOverlap(present)) pieces *= pieces;
693 Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
694 DirtyCompanyInfrastructureWindows(owner);
696 if (present == 0) {
697 Slope tileh = GetTileSlope(tile);
698 /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
699 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
700 MakeShore(tile);
701 } else {
702 DoClearSquare(tile);
704 DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
705 } else {
706 SetTrackBits(tile, present);
707 SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
710 break;
713 default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
716 if (flags & DC_EXEC) {
717 /* if we got that far, 'owner' variable is set correctly */
718 assert(Company::IsValidID(owner));
720 MarkTileDirtyByTile(tile);
721 if (crossing) {
722 /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
723 * are removing one of these pieces, we'll need to update signals for
724 * both directions explicitly, as after the track is removed it won't
725 * 'connect' with the other piece. */
726 AddTrackToSignalBuffer(tile, TRACK_X, owner);
727 AddTrackToSignalBuffer(tile, TRACK_Y, owner);
728 YapfNotifyTrackLayoutChange(tile, TRACK_X);
729 YapfNotifyTrackLayoutChange(tile, TRACK_Y);
730 } else {
731 AddTrackToSignalBuffer(tile, track, owner);
732 YapfNotifyTrackLayoutChange(tile, track);
735 if (v != NULL) TryPathReserve(v, true);
738 return cost;
743 * Called from water_cmd if a non-flat rail-tile gets flooded and should be converted to shore.
744 * The function floods the lower halftile, if the tile has a halftile foundation.
746 * @param t The tile to flood.
747 * @return true if something was flooded.
749 bool FloodHalftile(TileIndex t)
751 assert(IsPlainRailTile(t));
753 bool flooded = false;
754 if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
756 Slope tileh = GetTileSlope(t);
757 TrackBits rail_bits = GetTrackBits(t);
759 if (IsSlopeWithOneCornerRaised(tileh)) {
760 TrackBits lower_track = CornerToTrackBits(OppositeCorner(GetHighestSlopeCorner(tileh)));
762 TrackBits to_remove = lower_track & rail_bits;
763 if (to_remove != 0) {
764 Backup<CompanyByte> cur_company(_current_company, OWNER_WATER, FILE_LINE);
765 flooded = DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL).Succeeded();
766 cur_company.Restore();
767 if (!flooded) return flooded; // not yet floodable
768 rail_bits = rail_bits & ~to_remove;
769 if (rail_bits == 0) {
770 MakeShore(t);
771 MarkTileDirtyByTile(t);
772 return flooded;
776 if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
777 flooded = true;
778 SetRailGroundType(t, RAIL_GROUND_WATER);
779 MarkTileDirtyByTile(t);
781 } else {
782 /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
783 if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
784 if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
785 flooded = true;
786 SetRailGroundType(t, RAIL_GROUND_WATER);
787 MarkTileDirtyByTile(t);
791 return flooded;
794 static const TileIndexDiffC _trackdelta[] = {
795 { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
796 { 0, 0 },
797 { 0, 0 },
798 { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
799 { 0, 0 },
800 { 0, 0 }
804 static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
806 int x = TileX(start);
807 int y = TileY(start);
808 int ex = TileX(end);
809 int ey = TileY(end);
811 if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
813 /* calculate delta x,y from start to end tile */
814 int dx = ex - x;
815 int dy = ey - y;
817 /* calculate delta x,y for the first direction */
818 int trdx = _trackdelta[*trackdir].x;
819 int trdy = _trackdelta[*trackdir].y;
821 if (!IsDiagonalTrackdir(*trackdir)) {
822 trdx += _trackdelta[*trackdir ^ 1].x;
823 trdy += _trackdelta[*trackdir ^ 1].y;
826 /* validate the direction */
827 while ((trdx <= 0 && dx > 0) ||
828 (trdx >= 0 && dx < 0) ||
829 (trdy <= 0 && dy > 0) ||
830 (trdy >= 0 && dy < 0)) {
831 if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
832 SetBit(*trackdir, 3); // reverse the direction
833 trdx = -trdx;
834 trdy = -trdy;
835 } else { // other direction is invalid too, invalid drag
836 return CMD_ERROR;
840 /* (for diagonal tracks, this is already made sure of by above test), but:
841 * for non-diagonal tracks, check if the start and end tile are on 1 line */
842 if (!IsDiagonalTrackdir(*trackdir)) {
843 trdx = _trackdelta[*trackdir].x;
844 trdy = _trackdelta[*trackdir].y;
845 if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CMD_ERROR;
848 return CommandCost();
852 * Build or remove a stretch of railroad tracks.
853 * @param tile start tile of drag
854 * @param flags operation to perform
855 * @param p1 end tile of drag
856 * @param p2 various bitstuffed elements
857 * - p2 = (bit 0-3) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
858 * - p2 = (bit 4-6) - track-orientation, valid values: 0-5 (Track enum)
859 * - p2 = (bit 7) - 0 = build, 1 = remove tracks
860 * - p2 = (bit 8) - 0 = build up to an obstacle, 1 = fail if an obstacle is found (used for AIs).
861 * @param text unused
862 * @return the cost of this operation or an error
864 static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
866 CommandCost total_cost(EXPENSES_CONSTRUCTION);
867 Track track = Extract<Track, 4, 3>(p2);
868 bool remove = HasBit(p2, 7);
869 RailType railtype = Extract<RailType, 0, 4>(p2);
871 if ((!remove && !ValParamRailtype(railtype)) || !ValParamTrackOrientation(track)) return CMD_ERROR;
872 if (p1 >= MapSize()) return CMD_ERROR;
873 TileIndex end_tile = p1;
874 Trackdir trackdir = TrackToTrackdir(track);
876 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
877 if (ret.Failed()) return ret;
879 bool had_success = false;
880 CommandCost last_error = CMD_ERROR;
881 for (;;) {
882 CommandCost ret = DoCommand(tile, remove ? 0 : railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
884 if (ret.Failed()) {
885 last_error = ret;
886 if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
887 if (HasBit(p2, 8)) return last_error;
888 break;
891 /* Ownership errors are more important. */
892 if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
893 } else {
894 had_success = true;
895 total_cost.AddCost(ret);
898 if (tile == end_tile) break;
900 tile += ToTileIndexDiff(_trackdelta[trackdir]);
902 /* toggle railbit for the non-diagonal tracks */
903 if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
906 if (had_success) return total_cost;
907 return last_error;
911 * Build rail on a stretch of track.
912 * Stub for the unified rail builder/remover
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-3) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev)
918 * - p2 = (bit 4-6) - track-orientation, valid values: 0-5 (Track enum)
919 * - p2 = (bit 7) - 0 = build, 1 = remove tracks
920 * @param text unused
921 * @return the cost of this operation or an error
922 * @see CmdRailTrackHelper
924 CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
926 return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 7), text);
930 * Build rail on a stretch of track.
931 * Stub for the unified rail builder/remover
932 * @param tile start tile of drag
933 * @param flags operation to perform
934 * @param p1 end tile of drag
935 * @param p2 various bitstuffed elements
936 * - p2 = (bit 0-3) - railroad type normal/maglev (0 = normal, 1 = mono, 2 = maglev), only used for building
937 * - p2 = (bit 4-6) - track-orientation, valid values: 0-5 (Track enum)
938 * - p2 = (bit 7) - 0 = build, 1 = remove tracks
939 * @param text unused
940 * @return the cost of this operation or an error
941 * @see CmdRailTrackHelper
943 CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
945 return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 7), text);
949 * Build a train depot
950 * @param tile position of the train depot
951 * @param flags operation to perform
952 * @param p1 rail type
953 * @param p2 bit 0..1 entrance direction (DiagDirection)
954 * @param text unused
955 * @return the cost of this operation or an error
957 * @todo When checking for the tile slope,
958 * distinguish between "Flat land required" and "land sloped in wrong direction"
960 CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
962 /* check railtype and valid direction for depot (0 through 3), 4 in total */
963 RailType railtype = Extract<RailType, 0, 4>(p1);
964 if (!ValParamRailtype(railtype)) return CMD_ERROR;
966 Slope tileh = GetTileSlope(tile);
968 DiagDirection dir = Extract<DiagDirection, 0, 2>(p2);
970 /* Prohibit construction if
971 * The tile is non-flat AND
972 * 1) build-on-slopes is disabled
973 * 2) the tile is steep i.e. spans two height levels
974 * 3) the exit points in the wrong direction
977 if (tileh != SLOPE_FLAT && (
978 !_settings_game.construction.build_on_slopes ||
979 !CanBuildDepotByTileh(dir, tileh)
980 )) {
981 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
984 CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
985 if (cost.Failed()) return cost;
987 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
989 if (!Depot::CanAllocateItem()) return CMD_ERROR;
991 if (flags & DC_EXEC) {
992 Depot *d = new Depot(tile);
993 d->build_date = _date;
995 MakeRailDepot(tile, _current_company, d->index, dir, railtype);
996 MarkTileDirtyByTile(tile);
997 MakeDefaultName(d);
999 Company::Get(_current_company)->infrastructure.rail[railtype]++;
1000 DirtyCompanyInfrastructureWindows(_current_company);
1002 AddSideToSignalBuffer(tile, INVALID_DIAGDIR, _current_company);
1003 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1006 cost.AddCost(_price[PR_BUILD_DEPOT_TRAIN]);
1007 cost.AddCost(RailBuildCost(railtype));
1008 return cost;
1012 * Build signals, alternate between double/single, signal/semaphore,
1013 * pre/exit/combo-signals, and what-else not. If the rail piece does not
1014 * have any signals, bit 4 (cycle signal-type) is ignored
1015 * @param tile tile where to build the signals
1016 * @param flags operation to perform
1017 * @param p1 various bitstuffed elements
1018 * - p1 = (bit 0-2) - track-orientation, valid values: 0-5 (Track enum)
1019 * - p1 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal or (for bit 7) toggle variant (CTRL-toggle)
1020 * - p1 = (bit 4) - 0 = signals, 1 = semaphores
1021 * - p1 = (bit 5-7) - type of the signal, for valid values see enum SignalType in rail_map.h
1022 * - p1 = (bit 8) - convert the present signal type and variant
1023 * - p1 = (bit 9-11)- start cycle from this signal type
1024 * - p1 = (bit 12-14)-wrap around after this signal type
1025 * - p1 = (bit 15-16)-cycle the signal direction this many times
1026 * - p1 = (bit 17) - 1 = don't modify an existing signal but don't fail either, 0 = always set new signal type
1027 * @param p2 used for CmdBuildManySignals() to copy direction of first signal
1028 * @param text unused
1029 * @return the cost of this operation or an error
1030 * @todo p2 should be replaced by two bits for "along" and "against" the track.
1032 CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1034 Track track = Extract<Track, 0, 3>(p1);
1035 bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed
1036 SignalVariant sigvar = (ctrl_pressed ^ HasBit(p1, 4)) ? SIG_SEMAPHORE : SIG_ELECTRIC; // the signal variant of the new signal
1037 SignalType sigtype = Extract<SignalType, 5, 3>(p1); // the signal type of the new signal
1038 bool convert_signal = HasBit(p1, 8); // convert button pressed
1039 SignalType cycle_start = Extract<SignalType, 9, 3>(p1);
1040 SignalType cycle_stop = Extract<SignalType, 12, 3>(p1);
1041 uint num_dir_cycle = GB(p1, 15, 2);
1043 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1044 if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CMD_ERROR;
1046 /* You can only build signals on plain rail tiles, and the selected track must exist */
1047 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) ||
1048 !HasTrack(tile, track)) {
1049 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1051 /* Protect against invalid signal copying */
1052 if (p2 != 0 && (p2 & SignalOnTrack(track)) == 0) return CMD_ERROR;
1054 CommandCost ret = CheckTileOwnership(tile);
1055 if (ret.Failed()) return ret;
1057 /* See if this is a valid track combination for signals (no overlap) */
1058 if (TracksOverlap(GetTrackBits(tile))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
1060 /* In case we don't want to change an existing signal, return without error. */
1061 if (HasBit(p1, 17) && HasSignalOnTrack(tile, track)) return CommandCost();
1063 /* you can not convert a signal if no signal is on track */
1064 if (convert_signal && !HasSignalOnTrack(tile, track)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1066 CommandCost cost;
1067 if (!HasSignalOnTrack(tile, track)) {
1068 /* build new signals */
1069 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS]);
1070 } else {
1071 if (p2 != 0 && sigvar != GetSignalVariant(tile, track)) {
1072 /* convert signals <-> semaphores */
1073 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1075 } else if (convert_signal) {
1076 /* convert button pressed */
1077 if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
1078 /* convert electric <-> semaphore */
1079 cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1080 } else {
1081 /* it is free to change signal type: normal-pre-exit-combo */
1082 cost = CommandCost();
1085 } else {
1086 /* it is free to change orientation/pre-exit-combo signals */
1087 cost = CommandCost();
1091 if (flags & DC_EXEC) {
1092 Train *v = NULL;
1093 /* The new/changed signal could block our path. As this can lead to
1094 * stale reservations, we clear the path reservation here and try
1095 * to redo it later on. */
1096 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1097 v = GetTrainForReservation(tile, track);
1098 if (v != NULL) FreeTrainTrackReservation(v);
1101 if (!HasSignals(tile)) {
1102 /* there are no signals at all on this tile yet */
1103 SetHasSignals(tile, true);
1104 SetSignalStates(tile, 0xF); // all signals are on
1105 SetPresentSignals(tile, 0); // no signals built by default
1106 SetSignalType(tile, track, sigtype);
1107 SetSignalVariant(tile, track, sigvar);
1110 /* Subtract old signal infrastructure count. */
1111 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1113 if (p2 == 0) {
1114 if (!HasSignalOnTrack(tile, track)) {
1115 /* build new signals */
1116 SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
1117 SetSignalType(tile, track, sigtype);
1118 SetSignalVariant(tile, track, sigvar);
1119 while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
1120 } else {
1121 if (convert_signal) {
1122 /* convert signal button pressed */
1123 if (ctrl_pressed) {
1124 /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1125 SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1126 /* Query current signal type so the check for PBS signals below works. */
1127 sigtype = GetSignalType(tile, track);
1128 } else {
1129 /* convert the present signal to the chosen type and variant */
1130 SetSignalType(tile, track, sigtype);
1131 SetSignalVariant(tile, track, sigvar);
1132 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1133 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1137 } else if (ctrl_pressed) {
1138 /* cycle between cycle_start and cycle_end */
1139 sigtype = (SignalType)(GetSignalType(tile, track) + 1);
1141 if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
1143 SetSignalType(tile, track, sigtype);
1144 if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1145 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1147 } else {
1148 /* cycle the signal side: both -> left -> right -> both -> ... */
1149 CycleSignalSide(tile, track);
1150 /* Query current signal type so the check for PBS signals below works. */
1151 sigtype = GetSignalType(tile, track);
1154 } else {
1155 /* If CmdBuildManySignals is called with copying signals, just copy the
1156 * direction of the first signal given as parameter by CmdBuildManySignals */
1157 SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (p2 & SignalOnTrack(track)));
1158 SetSignalVariant(tile, track, sigvar);
1159 SetSignalType(tile, track, sigtype);
1162 /* Add new signal infrastructure count. */
1163 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1164 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1166 if (IsPbsSignal(sigtype)) {
1167 /* PBS signals should show red unless they are on reserved tiles without a train. */
1168 uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
1169 SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetRailReservationTrackBits(tile), track) && EnsureNoVehicleOnGround(tile).Succeeded() ? UINT_MAX : 0) & mask));
1171 MarkTileDirtyByTile(tile);
1172 AddTrackToSignalBuffer(tile, track, _current_company);
1173 YapfNotifyTrackLayoutChange(tile, track);
1174 if (v != NULL) {
1175 /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1176 if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
1177 !IsSafeWaitingPosition(v, v->tile, v->GetVehicleTrackdir(), true, _settings_game.pf.forbid_90_deg)) {
1178 TryPathReserve(v, true);
1183 return cost;
1186 static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal_ctr, bool remove)
1188 tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
1189 if (tile == INVALID_TILE) return false;
1191 /* Check for track bits on the new tile */
1192 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_RAIL, 0));
1194 if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
1195 trackdirbits &= TrackdirReachesTrackdirs(trackdir);
1197 /* No track bits, must stop */
1198 if (trackdirbits == TRACKDIR_BIT_NONE) return false;
1200 /* Get the first track dir */
1201 trackdir = RemoveFirstTrackdir(&trackdirbits);
1203 /* Any left? It's a junction so we stop */
1204 if (trackdirbits != TRACKDIR_BIT_NONE) return false;
1206 switch (GetTileType(tile)) {
1207 case MP_RAILWAY:
1208 if (IsRailDepot(tile)) return false;
1209 if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
1210 signal_ctr++;
1211 if (IsDiagonalTrackdir(trackdir)) {
1212 signal_ctr++;
1213 /* Ensure signal_ctr even so X and Y pieces get signals */
1214 ClrBit(signal_ctr, 0);
1216 return true;
1218 case MP_ROAD:
1219 if (!IsLevelCrossing(tile)) return false;
1220 signal_ctr += 2;
1221 return true;
1223 case MP_TUNNELBRIDGE: {
1224 TileIndex orig_tile = tile; // backup old value
1226 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
1227 if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
1229 /* Skip to end of tunnel or bridge
1230 * note that tile is a parameter by reference, so it must be updated */
1231 tile = GetOtherTunnelBridgeEnd(tile);
1233 signal_ctr += (GetTunnelBridgeLength(orig_tile, tile) + 2) * 2;
1234 return true;
1237 default: return false;
1242 * Build many signals by dragging; AutoSignals
1243 * @param tile start tile of drag
1244 * @param flags operation to perform
1245 * @param p1 end tile of drag
1246 * @param p2 various bitstuffed elements
1247 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1248 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1249 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1250 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1251 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1252 * - p2 = (bit 7- 9) - default signal type
1253 * - p2 = (bit 10) - 0 = keep fixed distance, 1 = minimise gaps between signals
1254 * - p2 = (bit 24-31) - user defined signals_density
1255 * @param text unused
1256 * @return the cost of this operation or an error
1258 static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1260 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1261 TileIndex start_tile = tile;
1263 Track track = Extract<Track, 0, 3>(p2);
1264 bool mode = HasBit(p2, 3);
1265 bool semaphores = HasBit(p2, 4);
1266 bool remove = HasBit(p2, 5);
1267 bool autofill = HasBit(p2, 6);
1268 bool minimise_gaps = HasBit(p2, 10);
1269 byte signal_density = GB(p2, 24, 8);
1271 if (p1 >= MapSize() || !ValParamTrackOrientation(track)) return CMD_ERROR;
1272 TileIndex end_tile = p1;
1273 if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
1275 if (!IsPlainRailTile(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1277 /* for vertical/horizontal tracks, double the given signals density
1278 * since the original amount will be too dense (shorter tracks) */
1279 signal_density *= 2;
1281 Trackdir trackdir = TrackToTrackdir(track);
1282 CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
1283 if (ret.Failed()) return ret;
1285 track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
1286 Trackdir start_trackdir = trackdir;
1288 /* Must start on a valid track to be able to avoid loops */
1289 if (!HasTrack(tile, track)) return CMD_ERROR;
1291 SignalType sigtype = (SignalType)GB(p2, 7, 3);
1292 if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1294 byte signals;
1295 /* copy the signal-style of the first rail-piece if existing */
1296 if (HasSignalOnTrack(tile, track)) {
1297 signals = GetPresentSignals(tile) & SignalOnTrack(track);
1298 assert(signals != 0);
1300 /* copy signal/semaphores style (independent of CTRL) */
1301 semaphores = GetSignalVariant(tile, track) != SIG_ELECTRIC;
1303 sigtype = GetSignalType(tile, track);
1304 /* Don't but copy entry or exit-signal type */
1305 if (sigtype == SIGTYPE_ENTRY || sigtype == SIGTYPE_EXIT) sigtype = SIGTYPE_NORMAL;
1306 } else { // no signals exist, drag a two-way signal stretch
1307 signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
1310 byte signal_dir = 0;
1311 if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
1312 if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
1314 /* signal_ctr - amount of tiles already processed
1315 * last_used_ctr - amount of tiles before previously placed signal
1316 * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1317 * last_suitable_ctr - amount of tiles before last possible signal place
1318 * last_suitable_tile - last tile where it is possible to place a signal
1319 * last_suitable_trackdir - trackdir of the last tile
1320 **********
1321 * trackdir - trackdir to build with autorail
1322 * semaphores - semaphores or signals
1323 * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1324 * and convert all others to semaphore/signal
1325 * remove - 1 remove signals, 0 build signals */
1326 int signal_ctr = 0;
1327 int last_used_ctr = INT_MIN; // initially INT_MIN to force building/removing at the first tile
1328 int last_suitable_ctr = 0;
1329 TileIndex last_suitable_tile = INVALID_TILE;
1330 Trackdir last_suitable_trackdir = INVALID_TRACKDIR;
1331 CommandCost last_error = CMD_ERROR;
1332 bool had_success = false;
1333 for (;;) {
1334 /* only build/remove signals with the specified density */
1335 if (remove || minimise_gaps || signal_ctr % signal_density == 0) {
1336 uint32 p1 = GB(TrackdirToTrack(trackdir), 0, 3);
1337 SB(p1, 3, 1, mode);
1338 SB(p1, 4, 1, semaphores);
1339 SB(p1, 5, 3, sigtype);
1340 if (!remove && signal_ctr == 0) SetBit(p1, 17);
1342 /* Pick the correct orientation for the track direction */
1343 signals = 0;
1344 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
1345 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
1347 /* Test tiles in between for suitability as well if minimising gaps. */
1348 bool test_only = !remove && minimise_gaps && signal_ctr < (last_used_ctr + signal_density);
1349 CommandCost ret = DoCommand(tile, p1, signals, test_only ? flags & ~DC_EXEC : flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1351 if (ret.Succeeded()) {
1352 /* Remember last track piece where we can place a signal. */
1353 last_suitable_ctr = signal_ctr;
1354 last_suitable_tile = tile;
1355 last_suitable_trackdir = trackdir;
1356 } else if (!test_only && last_suitable_tile != INVALID_TILE) {
1357 /* If a signal can't be placed, place it at the last possible position. */
1358 SB(p1, 0, 3, TrackdirToTrack(last_suitable_trackdir));
1359 ClrBit(p1, 17);
1361 /* Pick the correct orientation for the track direction. */
1362 signals = 0;
1363 if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(last_suitable_trackdir);
1364 if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(last_suitable_trackdir);
1366 ret = DoCommand(last_suitable_tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1369 /* Collect cost. */
1370 if (!test_only) {
1371 /* Be user-friendly and try placing signals as much as possible */
1372 if (ret.Succeeded()) {
1373 had_success = true;
1374 total_cost.AddCost(ret);
1375 last_used_ctr = last_suitable_ctr;
1376 last_suitable_tile = INVALID_TILE;
1377 } else {
1378 /* The "No railway" error is the least important one. */
1379 if (ret.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK ||
1380 last_error.GetErrorMessage() == INVALID_STRING_ID) {
1381 last_error = ret;
1387 if (autofill) {
1388 if (!CheckSignalAutoFill(tile, trackdir, signal_ctr, remove)) break;
1390 /* Prevent possible loops */
1391 if (tile == start_tile && trackdir == start_trackdir) break;
1392 } else {
1393 if (tile == end_tile) break;
1395 tile += ToTileIndexDiff(_trackdelta[trackdir]);
1396 signal_ctr++;
1398 /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1399 if (IsDiagonalTrackdir(trackdir)) {
1400 signal_ctr++;
1401 } else {
1402 ToggleBit(trackdir, 0);
1407 return had_success ? total_cost : last_error;
1411 * Build signals on a stretch of track.
1412 * Stub for the unified signal builder/remover
1413 * @param tile start tile of drag
1414 * @param flags operation to perform
1415 * @param p1 end tile of drag
1416 * @param p2 various bitstuffed elements
1417 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1418 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1419 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1420 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1421 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1422 * - p2 = (bit 7- 9) - default signal type
1423 * - p2 = (bit 24-31) - user defined signals_density
1424 * @param text unused
1425 * @return the cost of this operation or an error
1426 * @see CmdSignalTrackHelper
1428 CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1430 return CmdSignalTrackHelper(tile, flags, p1, p2, text);
1434 * Remove signals
1435 * @param tile coordinates where signal is being deleted from
1436 * @param flags operation to perform
1437 * @param p1 various bitstuffed elements, only track information is used
1438 * - (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1439 * - (bit 3) - override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1440 * - (bit 4) - 0 = signals, 1 = semaphores
1441 * @param p2 unused
1442 * @param text unused
1443 * @return the cost of this operation or an error
1445 CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1447 Track track = Extract<Track, 0, 3>(p1);
1449 if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1450 return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1452 if (!HasSignalOnTrack(tile, track)) {
1453 return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1456 /* Only water can remove signals from anyone */
1457 if (_current_company != OWNER_WATER) {
1458 CommandCost ret = CheckTileOwnership(tile);
1459 if (ret.Failed()) return ret;
1462 /* Do it? */
1463 if (flags & DC_EXEC) {
1464 Train *v = NULL;
1465 if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1466 v = GetTrainForReservation(tile, track);
1467 } else if (IsPbsSignal(GetSignalType(tile, track))) {
1468 /* PBS signal, might be the end of a path reservation. */
1469 Trackdir td = TrackToTrackdir(track);
1470 for (int i = 0; v == NULL && i < 2; i++, td = ReverseTrackdir(td)) {
1471 /* Only test the active signal side. */
1472 if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
1473 TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
1474 TrackBits tracks = TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(td));
1475 if (HasReservedTracks(next, tracks)) {
1476 v = GetTrainForReservation(next, TrackBitsToTrack(GetReservedTrackbits(next) & tracks));
1480 Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1481 SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
1482 Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1483 DirtyCompanyInfrastructureWindows(GetTileOwner(tile));
1485 /* removed last signal from tile? */
1486 if (GetPresentSignals(tile) == 0) {
1487 SetSignalStates(tile, 0);
1488 SetHasSignals(tile, false);
1489 SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
1492 AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
1493 YapfNotifyTrackLayoutChange(tile, track);
1494 if (v != NULL) TryPathReserve(v, false);
1496 MarkTileDirtyByTile(tile);
1499 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_SIGNALS]);
1503 * Remove signals on a stretch of track.
1504 * Stub for the unified signal builder/remover
1505 * @param tile start tile of drag
1506 * @param flags operation to perform
1507 * @param p1 end tile of drag
1508 * @param p2 various bitstuffed elements
1509 * - p2 = (bit 0- 2) - track-orientation, valid values: 0-5 (Track enum)
1510 * - p2 = (bit 3) - 1 = override signal/semaphore, or pre/exit/combo signal (CTRL-toggle)
1511 * - p2 = (bit 4) - 0 = signals, 1 = semaphores
1512 * - p2 = (bit 5) - 0 = build, 1 = remove signals
1513 * - p2 = (bit 6) - 0 = selected stretch, 1 = auto fill
1514 * - p2 = (bit 7- 9) - default signal type
1515 * - p2 = (bit 24-31) - user defined signals_density
1516 * @param text unused
1517 * @return the cost of this operation or an error
1518 * @see CmdSignalTrackHelper
1520 CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1522 return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
1525 /** Update power of train under which is the railtype being converted */
1526 static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
1528 if (v->type != VEH_TRAIN) return NULL;
1530 TrainList *affected_trains = static_cast<TrainList*>(data);
1531 affected_trains->Include(Train::From(v)->First());
1533 return NULL;
1537 * Convert one rail type to the other. You can convert normal rail to
1538 * monorail/maglev easily or vice-versa.
1539 * @param tile end tile of rail conversion drag
1540 * @param flags operation to perform
1541 * @param p1 start tile of drag
1542 * @param p2 various bitstuffed elements:
1543 * - p2 = (bit 0- 3) new railtype to convert to.
1544 * - p2 = (bit 4) build diagonally or not.
1545 * @param text unused
1546 * @return the cost of this operation or an error
1548 CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1550 RailType totype = Extract<RailType, 0, 4>(p2);
1551 TileIndex area_start = p1;
1552 TileIndex area_end = tile;
1553 bool diagonal = HasBit(p2, 4);
1555 if (!ValParamRailtype(totype)) return CMD_ERROR;
1556 if (area_start >= MapSize()) return CMD_ERROR;
1558 TrainList affected_trains;
1560 CommandCost cost(EXPENSES_CONSTRUCTION);
1561 CommandCost error = CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK); // by default, there is no track to convert.
1563 TileIterator *iter = diagonal ? (TileIterator *)new DiagonalTileIterator(area_start, area_end) : new OrthogonalTileIterator(area_start, area_end);
1564 for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
1565 TileType tt = GetTileType(tile);
1567 /* Check if there is any track on tile */
1568 switch (tt) {
1569 case MP_RAILWAY:
1570 break;
1571 case MP_STATION:
1572 if (!HasStationRail(tile)) continue;
1573 break;
1574 case MP_ROAD:
1575 if (!IsLevelCrossing(tile)) continue;
1576 if (RailNoLevelCrossings(totype)) {
1577 error.MakeError(STR_ERROR_CROSSING_DISALLOWED);
1578 continue;
1580 break;
1581 case MP_TUNNELBRIDGE:
1582 if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
1583 break;
1584 default: continue;
1587 /* Original railtype we are converting from */
1588 RailType type = GetRailType(tile);
1590 /* Converting to the same type or converting 'hidden' elrail -> rail */
1591 if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
1593 /* Trying to convert other's rail */
1594 CommandCost ret = CheckTileOwnership(tile);
1595 if (ret.Failed()) {
1596 error = ret;
1597 continue;
1600 SmallVector<Train *, 2> vehicles_affected;
1602 /* Vehicle on the tile when not converting Rail <-> ElRail
1603 * Tunnels and bridges have special check later */
1604 if (tt != MP_TUNNELBRIDGE) {
1605 if (!IsCompatibleRail(type, totype)) {
1606 CommandCost ret = EnsureNoVehicleOnGround(tile);
1607 if (ret.Failed()) {
1608 error = ret;
1609 continue;
1612 if (flags & DC_EXEC) { // we can safely convert, too
1613 TrackBits reserved = GetReservedTrackbits(tile);
1614 Track track;
1615 while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
1616 Train *v = GetTrainForReservation(tile, track);
1617 if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1618 /* No power on new rail type, reroute. */
1619 FreeTrainTrackReservation(v);
1620 *vehicles_affected.Append() = v;
1624 /* Update the company infrastructure counters. */
1625 if (!IsRailStationTile(tile) || !IsStationTileBlocked(tile)) {
1626 Company *c = Company::Get(GetTileOwner(tile));
1627 uint num_pieces = IsLevelCrossingTile(tile) ? LEVELCROSSING_TRACKBIT_FACTOR : 1;
1628 if (IsPlainRailTile(tile)) {
1629 TrackBits bits = GetTrackBits(tile);
1630 num_pieces = CountBits(bits);
1631 if (TracksOverlap(bits)) num_pieces *= num_pieces;
1633 c->infrastructure.rail[type] -= num_pieces;
1634 c->infrastructure.rail[totype] += num_pieces;
1635 DirtyCompanyInfrastructureWindows(c->index);
1638 SetRailType(tile, totype);
1639 MarkTileDirtyByTile(tile);
1640 /* update power of train on this tile */
1641 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1645 switch (tt) {
1646 case MP_RAILWAY:
1647 switch (GetRailTileType(tile)) {
1648 case RAIL_TILE_DEPOT:
1649 if (flags & DC_EXEC) {
1650 /* notify YAPF about the track layout change */
1651 YapfNotifyTrackLayoutChange(tile, GetRailDepotTrack(tile));
1653 /* Update build vehicle window related to this depot */
1654 InvalidateWindowData(WC_VEHICLE_DEPOT, tile);
1655 InvalidateWindowData(WC_BUILD_VEHICLE, tile);
1657 cost.AddCost(RailConvertCost(type, totype));
1658 break;
1660 default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1661 if (flags & DC_EXEC) {
1662 /* notify YAPF about the track layout change */
1663 TrackBits tracks = GetTrackBits(tile);
1664 while (tracks != TRACK_BIT_NONE) {
1665 YapfNotifyTrackLayoutChange(tile, RemoveFirstTrack(&tracks));
1668 cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
1669 break;
1671 break;
1673 case MP_TUNNELBRIDGE: {
1674 TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
1676 /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1677 * it would cause assert because of different test and exec runs */
1678 if (endtile < tile) {
1679 if (diagonal) {
1680 if (DiagonalTileArea(area_start, area_end).Contains(endtile)) continue;
1681 } else {
1682 if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
1686 /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1687 if (!IsCompatibleRail(GetRailType(tile), totype)) {
1688 CommandCost ret = TunnelBridgeIsFree(tile, endtile);
1689 if (ret.Failed()) {
1690 error = ret;
1691 continue;
1695 if (flags & DC_EXEC) {
1696 Track track = DiagDirToDiagTrack(GetTunnelBridgeDirection(tile));
1697 if (HasTunnelBridgeReservation(tile)) {
1698 Train *v = GetTrainForReservation(tile, track);
1699 if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1700 /* No power on new rail type, reroute. */
1701 FreeTrainTrackReservation(v);
1702 *vehicles_affected.Append() = v;
1706 /* Update the company infrastructure counters. */
1707 uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1708 Company *c = Company::Get(GetTileOwner(tile));
1709 c->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1710 c->infrastructure.rail[totype] += num_pieces;
1711 DirtyCompanyInfrastructureWindows(c->index);
1713 SetRailType(tile, totype);
1714 SetRailType(endtile, totype);
1716 FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1717 FindVehicleOnPos(endtile, &affected_trains, &UpdateTrainPowerProc);
1719 YapfNotifyTrackLayoutChange(tile, track);
1720 YapfNotifyTrackLayoutChange(endtile, track);
1722 if (IsBridge(tile)) {
1723 MarkBridgeDirty(tile);
1724 } else {
1725 MarkTileDirtyByTile(tile);
1726 MarkTileDirtyByTile(endtile);
1730 cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
1731 break;
1734 default: // MP_STATION, MP_ROAD
1735 if (flags & DC_EXEC) {
1736 Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
1737 YapfNotifyTrackLayoutChange(tile, track);
1740 cost.AddCost(RailConvertCost(type, totype));
1741 break;
1744 for (uint i = 0; i < vehicles_affected.Length(); ++i) {
1745 TryPathReserve(vehicles_affected[i], true);
1749 if (flags & DC_EXEC) {
1750 /* Railtype changed, update trains as when entering different track */
1751 for (Train **v = affected_trains.Begin(); v != affected_trains.End(); v++) {
1752 (*v)->ConsistChanged(CCF_TRACK);
1756 delete iter;
1757 return (cost.GetCost() == 0) ? error : cost;
1760 static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
1762 if (_current_company != OWNER_WATER) {
1763 CommandCost ret = CheckTileOwnership(tile);
1764 if (ret.Failed()) return ret;
1767 CommandCost ret = EnsureNoVehicleOnGround(tile);
1768 if (ret.Failed()) return ret;
1770 if (flags & DC_EXEC) {
1771 /* read variables before the depot is removed */
1772 DiagDirection dir = GetRailDepotDirection(tile);
1773 Owner owner = GetTileOwner(tile);
1774 Train *v = NULL;
1776 if (HasDepotReservation(tile)) {
1777 v = GetTrainForReservation(tile, DiagDirToDiagTrack(dir));
1778 if (v != NULL) FreeTrainTrackReservation(v);
1781 Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1782 DirtyCompanyInfrastructureWindows(owner);
1784 delete Depot::GetByTile(tile);
1785 DoClearSquare(tile);
1786 AddSideToSignalBuffer(tile, dir, owner);
1787 YapfNotifyTrackLayoutChange(tile, DiagDirToDiagTrack(dir));
1788 if (v != NULL) TryPathReserve(v, true);
1791 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
1794 static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
1796 CommandCost cost(EXPENSES_CONSTRUCTION);
1798 if (flags & DC_AUTO) {
1799 if (!IsTileOwner(tile, _current_company)) {
1800 return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
1803 if (IsPlainRail(tile)) {
1804 return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
1805 } else {
1806 return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1810 switch (GetRailTileType(tile)) {
1811 case RAIL_TILE_SIGNALS:
1812 case RAIL_TILE_NORMAL: {
1813 Slope tileh = GetTileSlope(tile);
1814 /* Is there flat water on the lower halftile that gets cleared expensively? */
1815 bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
1817 TrackBits tracks = GetTrackBits(tile);
1818 while (tracks != TRACK_BIT_NONE) {
1819 Track track = RemoveFirstTrack(&tracks);
1820 CommandCost ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
1821 if (ret.Failed()) return ret;
1822 cost.AddCost(ret);
1825 /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
1826 * Same holds for non-companies clearing the tile, e.g. disasters. */
1827 if (water_ground && !(flags & DC_BANKRUPT) && Company::IsValidID(_current_company)) {
1828 CommandCost ret = EnsureNoVehicleOnGround(tile);
1829 if (ret.Failed()) return ret;
1831 /* The track was removed, and left a coast tile. Now also clear the water. */
1832 if (flags & DC_EXEC) DoClearSquare(tile);
1833 cost.AddCost(_price[PR_CLEAR_WATER]);
1836 return cost;
1839 case RAIL_TILE_DEPOT:
1840 return RemoveTrainDepot(tile, flags);
1842 default:
1843 return CMD_ERROR;
1848 * Get surface height in point (x,y)
1849 * On tiles with halftile foundations move (x,y) to a safe point wrt. track
1851 static uint GetSaveSlopeZ(uint x, uint y, Track track)
1853 switch (track) {
1854 case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
1855 case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
1856 case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
1857 case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
1858 default: break;
1860 return GetSlopePixelZ(x, y);
1863 static void DrawSingleSignal(TileIndex tile, const RailtypeInfo *rti, Track track, SignalState condition, SignalOffsets image, uint pos)
1865 bool side;
1866 switch (_settings_game.construction.train_signal_side) {
1867 case 0: side = false; break; // left
1868 case 2: side = true; break; // right
1869 default: side = _settings_game.vehicle.road_side != 0; break; // driving side
1871 static const Point SignalPositions[2][12] = {
1872 { // Signals on the left side
1873 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1874 { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
1875 /* LOWER LOWER X X Y Y */
1876 {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1877 }, { // Signals on the right side
1878 /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1879 {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
1880 /* LOWER LOWER X X Y Y */
1881 {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1885 uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
1886 uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
1888 SignalType type = GetSignalType(tile, track);
1889 SignalVariant variant = GetSignalVariant(tile, track);
1891 SpriteID sprite = GetCustomSignalSprite(rti, tile, type, variant, condition);
1892 if (sprite != 0) {
1893 sprite += image;
1894 } else {
1895 /* Normal electric signals are stored in a different sprite block than all other signals. */
1896 sprite = (type == SIGTYPE_NORMAL && variant == SIG_ELECTRIC) ? SPR_ORIGINAL_SIGNALS_BASE : SPR_SIGNALS_BASE - 16;
1897 sprite += type * 16 + variant * 64 + image * 2 + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
1900 AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
1903 static uint32 _drawtile_track_palette;
1907 /** Offsets for drawing fences */
1908 struct FenceOffset {
1909 Corner height_ref; //!< Corner to use height offset from.
1910 int x_offs; //!< Bounding box X offset.
1911 int y_offs; //!< Bounding box Y offset.
1912 int x_size; //!< Bounding box X size.
1913 int y_size; //!< Bounding box Y size.
1916 /** Offsets for drawing fences */
1917 static FenceOffset _fence_offsets[] = {
1918 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
1919 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
1920 { CORNER_W, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
1921 { CORNER_N, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
1922 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
1923 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
1924 { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
1925 { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
1926 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
1927 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
1928 { CORNER_E, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
1929 { CORNER_S, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
1930 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
1931 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
1932 { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
1933 { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
1937 * Draw a track fence.
1938 * @param ti Tile drawing information.
1939 * @param base_image First fence sprite.
1940 * @param num_sprites Number of fence sprites.
1941 * @param rfo Fence to draw.
1943 static void DrawTrackFence(const TileInfo *ti, SpriteID base_image, uint num_sprites, RailFenceOffset rfo)
1945 int z = ti->z;
1946 if (_fence_offsets[rfo].height_ref != CORNER_INVALID) {
1947 z += GetSlopePixelZInCorner(RemoveHalftileSlope(ti->tileh), _fence_offsets[rfo].height_ref);
1949 AddSortableSpriteToDraw(base_image + (rfo % num_sprites), _drawtile_track_palette,
1950 ti->x + _fence_offsets[rfo].x_offs,
1951 ti->y + _fence_offsets[rfo].y_offs,
1952 _fence_offsets[rfo].x_size,
1953 _fence_offsets[rfo].y_size,
1954 4, z);
1958 * Draw fence at NW border matching the tile slope.
1960 static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1962 RailFenceOffset rfo = RFO_FLAT_X_NW;
1963 if (ti->tileh & SLOPE_NW) rfo = (ti->tileh & SLOPE_W) ? RFO_SLOPE_SW_NW : RFO_SLOPE_NE_NW;
1964 DrawTrackFence(ti, base_image, num_sprites, rfo);
1968 * Draw fence at SE border matching the tile slope.
1970 static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1972 RailFenceOffset rfo = RFO_FLAT_X_SE;
1973 if (ti->tileh & SLOPE_SE) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW_SE : RFO_SLOPE_NE_SE;
1974 DrawTrackFence(ti, base_image, num_sprites, rfo);
1978 * Draw fence at NE border matching the tile slope.
1980 static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1982 RailFenceOffset rfo = RFO_FLAT_Y_NE;
1983 if (ti->tileh & SLOPE_NE) rfo = (ti->tileh & SLOPE_E) ? RFO_SLOPE_SE_NE : RFO_SLOPE_NW_NE;
1984 DrawTrackFence(ti, base_image, num_sprites, rfo);
1988 * Draw fence at SW border matching the tile slope.
1990 static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1992 RailFenceOffset rfo = RFO_FLAT_Y_SW;
1993 if (ti->tileh & SLOPE_SW) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE_SW : RFO_SLOPE_NW_SW;
1994 DrawTrackFence(ti, base_image, num_sprites, rfo);
1998 * Draw track fences.
1999 * @param ti Tile drawing information.
2000 * @param rti Rail type information.
2002 static void DrawTrackDetails(const TileInfo *ti, const RailtypeInfo *rti)
2004 /* Base sprite for track fences.
2005 * Note: Halftile slopes only have fences on the upper part. */
2006 uint num_sprites = 0;
2007 SpriteID base_image = GetCustomRailSprite(rti, ti->tile, RTSG_FENCES, IsHalftileSlope(ti->tileh) ? TCX_UPPER_HALFTILE : TCX_NORMAL, &num_sprites);
2008 if (base_image == 0) {
2009 base_image = SPR_TRACK_FENCE_FLAT_X;
2010 num_sprites = 8;
2013 assert(num_sprites > 0);
2015 switch (GetRailGroundType(ti->tile)) {
2016 case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image, num_sprites); break;
2017 case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image, num_sprites); break;
2018 case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW(ti, base_image, num_sprites);
2019 DrawTrackFence_SE(ti, base_image, num_sprites); break;
2020 case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image, num_sprites); break;
2021 case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image, num_sprites); break;
2022 case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE(ti, base_image, num_sprites);
2023 DrawTrackFence_SW(ti, base_image, num_sprites); break;
2024 case RAIL_GROUND_FENCE_VERT1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2025 case RAIL_GROUND_FENCE_VERT2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2026 case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2027 case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2028 case RAIL_GROUND_WATER: {
2029 Corner track_corner;
2030 if (IsHalftileSlope(ti->tileh)) {
2031 /* Steep slope or one-corner-raised slope with halftile foundation */
2032 track_corner = GetHalftileSlopeCorner(ti->tileh);
2033 } else {
2034 /* Three-corner-raised slope */
2035 track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2037 switch (track_corner) {
2038 case CORNER_W: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2039 case CORNER_S: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2040 case CORNER_E: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2041 case CORNER_N: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2042 default: NOT_REACHED();
2044 break;
2046 default: break;
2050 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2051 static const int INF = 1000; // big number compared to tilesprite size
2052 static const SubSprite _halftile_sub_sprite[4] = {
2053 { -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
2054 { -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
2055 { -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
2056 { -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2059 static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
2061 DrawGroundSprite(sprite, pal, NULL, 0, (ti->tileh & s) ? -8 : 0);
2064 static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailtypeInfo *rti)
2066 RailGroundType rgt = GetRailGroundType(ti->tile);
2067 Foundation f = GetRailFoundation(ti->tileh, track);
2068 Corner halftile_corner = CORNER_INVALID;
2070 if (IsNonContinuousFoundation(f)) {
2071 /* Save halftile corner */
2072 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2073 /* Draw lower part first */
2074 track &= ~CornerToTrackBits(halftile_corner);
2075 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2078 DrawFoundation(ti, f);
2079 /* DrawFoundation modifies ti */
2081 /* Draw ground */
2082 if (rgt == RAIL_GROUND_WATER) {
2083 if (track != TRACK_BIT_NONE || IsSteepSlope(ti->tileh)) {
2084 /* three-corner-raised slope or steep slope with track on upper part */
2085 DrawShoreTile(ti->tileh);
2086 } else {
2087 /* single-corner-raised slope with track on upper part */
2088 DrawGroundSprite(SPR_FLAT_WATER_TILE, PAL_NONE);
2090 } else {
2091 SpriteID image;
2093 switch (rgt) {
2094 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2095 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2096 default: image = SPR_FLAT_GRASS_TILE; break;
2099 image += SlopeToSpriteOffset(ti->tileh);
2101 DrawGroundSprite(image, PAL_NONE);
2104 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2105 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2106 TrackBits pbs = _settings_client.gui.show_track_reservation ? GetRailReservationTrackBits(ti->tile) : TRACK_BIT_NONE;
2108 if (track == TRACK_BIT_NONE) {
2109 /* Half-tile foundation, no track here? */
2110 } else if (ti->tileh == SLOPE_NW && track == TRACK_BIT_Y) {
2111 DrawGroundSprite(ground + RTO_SLOPE_NW, PAL_NONE);
2112 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NW, PALETTE_CRASH);
2113 } else if (ti->tileh == SLOPE_NE && track == TRACK_BIT_X) {
2114 DrawGroundSprite(ground + RTO_SLOPE_NE, PAL_NONE);
2115 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_NE, PALETTE_CRASH);
2116 } else if (ti->tileh == SLOPE_SE && track == TRACK_BIT_Y) {
2117 DrawGroundSprite(ground + RTO_SLOPE_SE, PAL_NONE);
2118 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SE, PALETTE_CRASH);
2119 } else if (ti->tileh == SLOPE_SW && track == TRACK_BIT_X) {
2120 DrawGroundSprite(ground + RTO_SLOPE_SW, PAL_NONE);
2121 if (pbs != TRACK_BIT_NONE) DrawGroundSprite(overlay + RTO_SLOPE_SW, PALETTE_CRASH);
2122 } else {
2123 switch (track) {
2124 /* Draw single ground sprite when not overlapping. No track overlay
2125 * is necessary for these sprites. */
2126 case TRACK_BIT_X: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2127 case TRACK_BIT_Y: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2128 case TRACK_BIT_UPPER: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N); break;
2129 case TRACK_BIT_LOWER: DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2130 case TRACK_BIT_RIGHT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E); break;
2131 case TRACK_BIT_LEFT: DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2132 case TRACK_BIT_CROSS: DrawGroundSprite(ground + RTO_CROSSING_XY, PAL_NONE); break;
2133 case TRACK_BIT_HORZ: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N);
2134 DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2135 case TRACK_BIT_VERT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E);
2136 DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2138 default:
2139 /* We're drawing a junction tile */
2140 if ((track & TRACK_BIT_3WAY_NE) == 0) {
2141 DrawGroundSprite(ground + RTO_JUNCTION_SW, PAL_NONE);
2142 } else if ((track & TRACK_BIT_3WAY_SW) == 0) {
2143 DrawGroundSprite(ground + RTO_JUNCTION_NE, PAL_NONE);
2144 } else if ((track & TRACK_BIT_3WAY_NW) == 0) {
2145 DrawGroundSprite(ground + RTO_JUNCTION_SE, PAL_NONE);
2146 } else if ((track & TRACK_BIT_3WAY_SE) == 0) {
2147 DrawGroundSprite(ground + RTO_JUNCTION_NW, PAL_NONE);
2148 } else {
2149 DrawGroundSprite(ground + RTO_JUNCTION_NSEW, PAL_NONE);
2152 /* Mask out PBS bits as we shall draw them afterwards anyway. */
2153 track &= ~pbs;
2155 /* Draw regular track bits */
2156 if (track & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PAL_NONE);
2157 if (track & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PAL_NONE);
2158 if (track & TRACK_BIT_UPPER) DrawGroundSprite(overlay + RTO_N, PAL_NONE);
2159 if (track & TRACK_BIT_LOWER) DrawGroundSprite(overlay + RTO_S, PAL_NONE);
2160 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(overlay + RTO_E, PAL_NONE);
2161 if (track & TRACK_BIT_LEFT) DrawGroundSprite(overlay + RTO_W, PAL_NONE);
2164 /* Draw reserved track bits */
2165 if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2166 if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2167 if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2168 if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2169 if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2170 if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2173 if (IsValidCorner(halftile_corner)) {
2174 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2175 overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY, TCX_UPPER_HALFTILE);
2176 ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND, TCX_UPPER_HALFTILE);
2178 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2179 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2181 SpriteID image;
2182 switch (rgt) {
2183 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2184 case RAIL_GROUND_ICE_DESERT:
2185 case RAIL_GROUND_HALF_SNOW: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2186 default: image = SPR_FLAT_GRASS_TILE; break;
2189 image += SlopeToSpriteOffset(fake_slope);
2191 DrawGroundSprite(image, PAL_NONE, &(_halftile_sub_sprite[halftile_corner]));
2193 track = CornerToTrackBits(halftile_corner);
2195 int offset;
2196 switch (track) {
2197 default: NOT_REACHED();
2198 case TRACK_BIT_UPPER: offset = RTO_N; break;
2199 case TRACK_BIT_LOWER: offset = RTO_S; break;
2200 case TRACK_BIT_RIGHT: offset = RTO_E; break;
2201 case TRACK_BIT_LEFT: offset = RTO_W; break;
2204 DrawTrackSprite(ground + offset, PAL_NONE, ti, fake_slope);
2205 if (_settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, track)) {
2206 DrawTrackSprite(overlay + offset, PALETTE_CRASH, ti, fake_slope);
2212 * Draw ground sprite and track bits
2213 * @param ti TileInfo
2214 * @param track TrackBits to draw
2216 static void DrawTrackBits(TileInfo *ti, TrackBits track)
2218 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2220 if (rti->UsesOverlay()) {
2221 DrawTrackBitsOverlay(ti, track, rti);
2222 return;
2225 RailGroundType rgt = GetRailGroundType(ti->tile);
2226 Foundation f = GetRailFoundation(ti->tileh, track);
2227 Corner halftile_corner = CORNER_INVALID;
2229 if (IsNonContinuousFoundation(f)) {
2230 /* Save halftile corner */
2231 halftile_corner = (f == FOUNDATION_STEEP_BOTH ? GetHighestSlopeCorner(ti->tileh) : GetHalftileFoundationCorner(f));
2232 /* Draw lower part first */
2233 track &= ~CornerToTrackBits(halftile_corner);
2234 f = (f == FOUNDATION_STEEP_BOTH ? FOUNDATION_STEEP_LOWER : FOUNDATION_NONE);
2237 DrawFoundation(ti, f);
2238 /* DrawFoundation modifies ti */
2240 SpriteID image;
2241 PaletteID pal = PAL_NONE;
2242 const SubSprite *sub = NULL;
2243 bool junction = false;
2245 /* Select the sprite to use. */
2246 if (track == 0) {
2247 /* Clear ground (only track on halftile foundation) */
2248 if (rgt == RAIL_GROUND_WATER) {
2249 if (IsSteepSlope(ti->tileh)) {
2250 DrawShoreTile(ti->tileh);
2251 image = 0;
2252 } else {
2253 image = SPR_FLAT_WATER_TILE;
2255 } else {
2256 switch (rgt) {
2257 case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2258 case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2259 default: image = SPR_FLAT_GRASS_TILE; break;
2261 image += SlopeToSpriteOffset(ti->tileh);
2263 } else {
2264 if (ti->tileh != SLOPE_FLAT) {
2265 /* track on non-flat ground */
2266 image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
2267 } else {
2268 /* track on flat ground */
2269 (image = rti->base_sprites.track_y, track == TRACK_BIT_Y) ||
2270 (image++, track == TRACK_BIT_X) ||
2271 (image++, track == TRACK_BIT_UPPER) ||
2272 (image++, track == TRACK_BIT_LOWER) ||
2273 (image++, track == TRACK_BIT_RIGHT) ||
2274 (image++, track == TRACK_BIT_LEFT) ||
2275 (image++, track == TRACK_BIT_CROSS) ||
2277 (image = rti->base_sprites.track_ns, track == TRACK_BIT_HORZ) ||
2278 (image++, track == TRACK_BIT_VERT) ||
2280 (junction = true, false) ||
2281 (image = rti->base_sprites.ground, (track & TRACK_BIT_3WAY_NE) == 0) ||
2282 (image++, (track & TRACK_BIT_3WAY_SW) == 0) ||
2283 (image++, (track & TRACK_BIT_3WAY_NW) == 0) ||
2284 (image++, (track & TRACK_BIT_3WAY_SE) == 0) ||
2285 (image++, true);
2288 switch (rgt) {
2289 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2290 case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
2291 case RAIL_GROUND_WATER: {
2292 /* three-corner-raised slope */
2293 DrawShoreTile(ti->tileh);
2294 Corner track_corner = OppositeCorner(GetHighestSlopeCorner(ComplementSlope(ti->tileh)));
2295 sub = &(_halftile_sub_sprite[track_corner]);
2296 break;
2298 default: break;
2302 if (image != 0) DrawGroundSprite(image, pal, sub);
2304 /* Draw track pieces individually for junction tiles */
2305 if (junction) {
2306 if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
2307 if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
2308 if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
2309 if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
2310 if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
2311 if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
2314 /* PBS debugging, draw reserved tracks darker */
2315 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
2316 /* Get reservation, but mask track on halftile slope */
2317 TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
2318 if (pbs & TRACK_BIT_X) {
2319 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2320 DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH);
2321 } else {
2322 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2325 if (pbs & TRACK_BIT_Y) {
2326 if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2327 DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH);
2328 } else {
2329 DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2332 if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
2333 if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
2334 if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
2335 if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
2338 if (IsValidCorner(halftile_corner)) {
2339 DrawFoundation(ti, HalftileFoundation(halftile_corner));
2341 /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2342 Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2343 image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
2344 pal = PAL_NONE;
2345 switch (rgt) {
2346 case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2347 case RAIL_GROUND_ICE_DESERT:
2348 case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
2349 default: break;
2351 DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
2353 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
2354 static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
2355 DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, -(int)TILE_HEIGHT);
2360 static void DrawSignals(TileIndex tile, TrackBits rails, const RailtypeInfo *rti)
2362 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2364 if (!(rails & TRACK_BIT_Y)) {
2365 if (!(rails & TRACK_BIT_X)) {
2366 if (rails & TRACK_BIT_LEFT) {
2367 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
2368 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
2370 if (rails & TRACK_BIT_RIGHT) {
2371 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
2372 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
2374 if (rails & TRACK_BIT_UPPER) {
2375 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
2376 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
2378 if (rails & TRACK_BIT_LOWER) {
2379 MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
2380 MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
2382 } else {
2383 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
2384 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
2386 } else {
2387 MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
2388 MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
2392 static void DrawTile_Track(TileInfo *ti)
2394 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2396 _drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
2398 if (IsPlainRail(ti->tile)) {
2399 TrackBits rails = GetTrackBits(ti->tile);
2401 DrawTrackBits(ti, rails);
2403 if (HasBit(_display_opt, DO_FULL_DETAIL)) DrawTrackDetails(ti, rti);
2405 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2407 if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails, rti);
2408 } else {
2409 /* draw depot */
2410 const DrawTileSprites *dts;
2411 PaletteID pal = PAL_NONE;
2412 SpriteID relocation;
2414 if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
2416 if (IsInvisibilitySet(TO_BUILDINGS)) {
2417 /* Draw rail instead of depot */
2418 dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
2419 } else {
2420 dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
2423 SpriteID image;
2424 if (rti->UsesOverlay()) {
2425 image = SPR_FLAT_GRASS_TILE;
2426 } else {
2427 image = dts->ground.sprite;
2428 if (image != SPR_FLAT_GRASS_TILE) image += rti->GetRailtypeSpriteOffset();
2431 /* adjust ground tile for desert
2432 * don't adjust for snow, because snow in depots looks weird */
2433 if (IsSnowRailGround(ti->tile) && _settings_game.game_creation.landscape == LT_TROPIC) {
2434 if (image != SPR_FLAT_GRASS_TILE) {
2435 image += rti->snow_offset; // tile with tracks
2436 } else {
2437 image = SPR_FLAT_SNOW_DESERT_TILE; // flat ground
2441 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
2443 if (rti->UsesOverlay()) {
2444 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2446 switch (GetRailDepotDirection(ti->tile)) {
2447 case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2448 case DIAGDIR_SW: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2449 case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2450 case DIAGDIR_SE: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2451 default: break;
2454 if (_settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2455 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2457 switch (GetRailDepotDirection(ti->tile)) {
2458 case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2459 case DIAGDIR_SW: DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH); break;
2460 case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2461 case DIAGDIR_SE: DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH); break;
2462 default: break;
2465 } else {
2466 /* PBS debugging, draw reserved tracks darker */
2467 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2468 switch (GetRailDepotDirection(ti->tile)) {
2469 case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2470 case DIAGDIR_SW: DrawGroundSprite(rti->base_sprites.single_x, PALETTE_CRASH); break;
2471 case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2472 case DIAGDIR_SE: DrawGroundSprite(rti->base_sprites.single_y, PALETTE_CRASH); break;
2473 default: break;
2477 int depot_sprite = GetCustomRailSprite(rti, ti->tile, RTSG_DEPOT);
2478 relocation = depot_sprite != 0 ? depot_sprite - SPR_RAIL_DEPOT_SE_1 : rti->GetRailtypeSpriteOffset();
2480 if (HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2482 DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, _drawtile_track_palette);
2484 DrawBridgeMiddle(ti);
2487 void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
2489 const DrawTileSprites *dts = &_depot_gfx_table[dir];
2490 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
2491 SpriteID image = rti->UsesOverlay() ? SPR_FLAT_GRASS_TILE : dts->ground.sprite;
2492 uint32 offset = rti->GetRailtypeSpriteOffset();
2494 if (image != SPR_FLAT_GRASS_TILE) image += offset;
2495 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
2497 DrawSprite(image, PAL_NONE, x, y);
2499 if (rti->UsesOverlay()) {
2500 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
2502 switch (dir) {
2503 case DIAGDIR_SW: DrawSprite(ground + RTO_X, PAL_NONE, x, y); break;
2504 case DIAGDIR_SE: DrawSprite(ground + RTO_Y, PAL_NONE, x, y); break;
2505 default: break;
2508 int depot_sprite = GetCustomRailSprite(rti, INVALID_TILE, RTSG_DEPOT);
2509 if (depot_sprite != 0) offset = depot_sprite - SPR_RAIL_DEPOT_SE_1;
2511 DrawRailTileSeqInGUI(x, y, dts, offset, 0, palette);
2514 static int GetSlopePixelZ_Track(TileIndex tile, uint x, uint y)
2516 if (IsPlainRail(tile)) {
2517 int z;
2518 Slope tileh = GetTilePixelSlope(tile, &z);
2519 if (tileh == SLOPE_FLAT) return z;
2521 z += ApplyPixelFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
2522 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2523 } else {
2524 return GetTileMaxPixelZ(tile);
2528 static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
2530 return IsPlainRail(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
2533 static void TileLoop_Track(TileIndex tile)
2535 RailGroundType old_ground = GetRailGroundType(tile);
2536 RailGroundType new_ground;
2538 if (old_ground == RAIL_GROUND_WATER) {
2539 TileLoop_Water(tile);
2540 return;
2543 switch (_settings_game.game_creation.landscape) {
2544 case LT_ARCTIC: {
2545 int z;
2546 Slope slope = GetTileSlope(tile, &z);
2547 bool half = false;
2549 /* for non-flat track, use lower part of track
2550 * in other cases, use the highest part with track */
2551 if (IsPlainRail(tile)) {
2552 TrackBits track = GetTrackBits(tile);
2553 Foundation f = GetRailFoundation(slope, track);
2555 switch (f) {
2556 case FOUNDATION_NONE:
2557 /* no foundation - is the track on the upper side of three corners raised tile? */
2558 if (IsSlopeWithThreeCornersRaised(slope)) z++;
2559 break;
2561 case FOUNDATION_INCLINED_X:
2562 case FOUNDATION_INCLINED_Y:
2563 /* sloped track - is it on a steep slope? */
2564 if (IsSteepSlope(slope)) z++;
2565 break;
2567 case FOUNDATION_STEEP_LOWER:
2568 /* only lower part of steep slope */
2569 z++;
2570 break;
2572 default:
2573 /* if it is a steep slope, then there is a track on higher part */
2574 if (IsSteepSlope(slope)) z++;
2575 z++;
2576 break;
2579 half = IsInsideMM(f, FOUNDATION_STEEP_BOTH, FOUNDATION_HALFTILE_N + 1);
2580 } else {
2581 /* is the depot on a non-flat tile? */
2582 if (slope != SLOPE_FLAT) z++;
2585 /* 'z' is now the lowest part of the highest track bit -
2586 * for sloped track, it is 'z' of lower part
2587 * for two track bits, it is 'z' of higher track bit
2588 * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2589 if (z > GetSnowLine()) {
2590 if (half && z - GetSnowLine() == 1) {
2591 /* track on non-continuous foundation, lower part is not under snow */
2592 new_ground = RAIL_GROUND_HALF_SNOW;
2593 } else {
2594 new_ground = RAIL_GROUND_ICE_DESERT;
2596 goto set_ground;
2598 break;
2601 case LT_TROPIC:
2602 if (GetTropicZone(tile) == TROPICZONE_DESERT) {
2603 new_ground = RAIL_GROUND_ICE_DESERT;
2604 goto set_ground;
2606 break;
2609 new_ground = RAIL_GROUND_GRASS;
2611 if (IsPlainRail(tile) && old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
2612 /* determine direction of fence */
2613 TrackBits rail = GetTrackBits(tile);
2615 Owner owner = GetTileOwner(tile);
2616 byte fences = 0;
2618 for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
2619 static const TrackBits dir_to_trackbits[DIAGDIR_END] = {TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW};
2621 /* Track bit on this edge => no fence. */
2622 if ((rail & dir_to_trackbits[d]) != TRACK_BIT_NONE) continue;
2624 TileIndex tile2 = tile + TileOffsByDiagDir(d);
2626 /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
2627 if (!IsValidTile(tile2) || IsTileType(tile2, MP_HOUSE) || IsTileType(tile2, MP_INDUSTRY) ||
2628 IsTileType(tile2, MP_ROAD) || (IsTileType(tile2, MP_OBJECT) && !IsObjectType(tile2, OBJECT_OWNED_LAND)) || IsTileType(tile2, MP_TUNNELBRIDGE) || !IsTileOwner(tile2, owner)) {
2629 fences |= 1 << d;
2633 switch (fences) {
2634 case 0: break;
2635 case (1 << DIAGDIR_NE): new_ground = RAIL_GROUND_FENCE_NE; break;
2636 case (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_SE; break;
2637 case (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_SW; break;
2638 case (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_NW; break;
2639 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_NESW; break;
2640 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_SENW; break;
2641 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_VERT1; break;
2642 case (1 << DIAGDIR_NE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
2643 case (1 << DIAGDIR_SE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
2644 case (1 << DIAGDIR_SW) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_VERT2; break;
2645 default: NOT_REACHED();
2649 set_ground:
2650 if (old_ground != new_ground) {
2651 SetRailGroundType(tile, new_ground);
2652 MarkTileDirtyByTile(tile);
2657 static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
2659 /* Case of half tile slope with water. */
2660 if (mode == TRANSPORT_WATER && IsPlainRail(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
2661 TrackBits tb = GetTrackBits(tile);
2662 switch (tb) {
2663 default: NOT_REACHED();
2664 case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
2665 case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
2666 case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
2667 case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
2669 return CombineTrackStatus(TrackBitsToTrackdirBits(tb), TRACKDIR_BIT_NONE);
2672 if (mode != TRANSPORT_RAIL) return 0;
2674 TrackBits trackbits = TRACK_BIT_NONE;
2675 TrackdirBits red_signals = TRACKDIR_BIT_NONE;
2677 switch (GetRailTileType(tile)) {
2678 default: NOT_REACHED();
2679 case RAIL_TILE_NORMAL:
2680 trackbits = GetTrackBits(tile);
2681 break;
2683 case RAIL_TILE_SIGNALS: {
2684 trackbits = GetTrackBits(tile);
2685 byte a = GetPresentSignals(tile);
2686 uint b = GetSignalStates(tile);
2688 b &= a;
2690 /* When signals are not present (in neither direction),
2691 * we pretend them to be green. Otherwise, it depends on
2692 * the signal type. For signals that are only active from
2693 * one side, we set the missing signals explicitly to
2694 * `green'. Otherwise, they implicitly become `red'. */
2695 if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
2696 if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
2698 if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
2699 if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
2700 if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
2701 if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
2703 break;
2706 case RAIL_TILE_DEPOT: {
2707 DiagDirection dir = GetRailDepotDirection(tile);
2709 if (side != INVALID_DIAGDIR && side != dir) break;
2711 trackbits = DiagDirToDiagTrackBits(dir);
2712 break;
2716 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
2719 static bool ClickTile_Track(TileIndex tile)
2721 if (!IsRailDepot(tile)) return false;
2723 ShowDepotWindow(tile, VEH_TRAIN);
2724 return true;
2727 static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
2729 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2730 td->rail_speed = rti->max_speed;
2731 td->railtype = rti->strings.name;
2732 td->owner[0] = GetTileOwner(tile);
2733 switch (GetRailTileType(tile)) {
2734 case RAIL_TILE_NORMAL:
2735 td->str = STR_LAI_RAIL_DESCRIPTION_TRACK;
2736 break;
2738 case RAIL_TILE_SIGNALS: {
2739 static const StringID signal_type[6][6] = {
2741 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS,
2742 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2743 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2744 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2745 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2746 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
2749 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2750 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS,
2751 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2752 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2753 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2754 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
2757 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2758 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2759 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS,
2760 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2761 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2762 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
2765 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2766 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2767 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2768 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS,
2769 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2770 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
2773 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2774 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2775 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2776 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2777 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS,
2778 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
2781 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
2782 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
2783 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
2784 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
2785 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
2786 STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS
2790 SignalType primary_signal;
2791 SignalType secondary_signal;
2792 if (HasSignalOnTrack(tile, TRACK_UPPER)) {
2793 primary_signal = GetSignalType(tile, TRACK_UPPER);
2794 secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
2795 } else {
2796 secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
2799 td->str = signal_type[secondary_signal][primary_signal];
2800 break;
2803 case RAIL_TILE_DEPOT:
2804 td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
2805 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
2806 if (td->rail_speed > 0) {
2807 td->rail_speed = min(td->rail_speed, 61);
2808 } else {
2809 td->rail_speed = 61;
2812 td->build_date = Depot::GetByTile(tile)->build_date;
2813 break;
2815 default:
2816 NOT_REACHED();
2820 static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
2822 if (!IsTileOwner(tile, old_owner)) return;
2824 if (new_owner != INVALID_OWNER) {
2825 /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2826 uint num_pieces = 1;
2827 if (IsPlainRail(tile)) {
2828 TrackBits bits = GetTrackBits(tile);
2829 num_pieces = CountBits(bits);
2830 if (TracksOverlap(bits)) num_pieces *= num_pieces;
2832 RailType rt = GetRailType(tile);
2833 Company::Get(old_owner)->infrastructure.rail[rt] -= num_pieces;
2834 Company::Get(new_owner)->infrastructure.rail[rt] += num_pieces;
2836 if (HasSignals(tile)) {
2837 uint num_sigs = CountBits(GetPresentSignals(tile));
2838 Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2839 Company::Get(new_owner)->infrastructure.signal += num_sigs;
2842 SetTileOwner(tile, new_owner);
2843 } else {
2844 DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2848 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
2849 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
2850 static const int8 _deltacoord_leaveoffset[8] = {
2851 -1, 0, 1, 0, /* x */
2852 0, 1, 0, -1 /* y */
2857 * Compute number of ticks when next wagon will leave a depot.
2858 * Negative means next wagon should have left depot n ticks before.
2859 * @param v vehicle outside (leaving) the depot
2860 * @return number of ticks when the next wagon will leave
2862 int TicksToLeaveDepot(const Train *v)
2864 DiagDirection dir = GetRailDepotDirection(v->tile);
2865 int length = v->CalcNextVehicleOffset();
2867 switch (dir) {
2868 case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
2869 case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
2870 case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
2871 default:
2872 case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
2875 return 0; // make compilers happy
2879 * Tile callback routine when vehicle enters tile
2880 * @see vehicle_enter_tile_proc
2882 static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int x, int y)
2884 /* this routine applies only to trains in depot tiles */
2885 if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
2887 Train *v = Train::From(u);
2889 /* depot direction */
2890 DiagDirection dir = GetRailDepotDirection(tile);
2892 /* Calculate the point where the following wagon should be activated. */
2893 int length = v->CalcNextVehicleOffset();
2895 byte fract_coord_leave =
2896 ((_fractcoords_enter[dir] & 0x0F) + // x
2897 (length + 1) * _deltacoord_leaveoffset[dir]) +
2898 (((_fractcoords_enter[dir] >> 4) + // y
2899 ((length + 1) * _deltacoord_leaveoffset[dir + 4])) << 4);
2901 byte fract_coord = (x & 0xF) + ((y & 0xF) << 4);
2903 if (_fractcoords_behind[dir] == fract_coord) {
2904 /* make sure a train is not entering the tile from behind */
2905 return VETSB_CANNOT_ENTER;
2906 } else if (_fractcoords_enter[dir] == fract_coord) {
2907 if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) {
2908 /* enter the depot */
2909 v->track = TRACK_BIT_DEPOT,
2910 v->vehstatus |= VS_HIDDEN; // hide it
2911 v->direction = ReverseDir(v->direction);
2912 if (v->Next() == NULL) VehicleEnterDepot(v->First());
2913 v->tile = tile;
2915 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2916 return VETSB_ENTERED_WORMHOLE;
2918 } else if (fract_coord_leave == fract_coord) {
2919 if (DiagDirToDir(dir) == v->direction) {
2920 /* leave the depot? */
2921 if ((v = v->Next()) != NULL) {
2922 v->vehstatus &= ~VS_HIDDEN;
2923 v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
2928 return VETSB_CONTINUE;
2932 * Tests if autoslope is allowed.
2934 * @param tile The tile.
2935 * @param flags Terraform command flags.
2936 * @param z_old Old TileZ.
2937 * @param tileh_old Old TileSlope.
2938 * @param z_new New TileZ.
2939 * @param tileh_new New TileSlope.
2940 * @param rail_bits Trackbits.
2942 static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old, Slope tileh_old, int z_new, Slope tileh_new, TrackBits rail_bits)
2944 if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2946 /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
2947 if (CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2949 /* Get the slopes on top of the foundations */
2950 z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
2951 z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
2953 Corner track_corner;
2954 switch (rail_bits) {
2955 case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
2956 case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
2957 case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
2958 case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
2960 /* Surface slope must not be changed */
2961 default:
2962 if (z_old != z_new || tileh_old != tileh_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2963 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2966 /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
2967 z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
2968 z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
2969 if (z_old != z_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2971 CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2972 /* Make the ground dirty, if surface slope has changed */
2973 if (tileh_old != tileh_new) {
2974 /* If there is flat water on the lower halftile add the cost for clearing it */
2975 if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price[PR_CLEAR_WATER]);
2976 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
2978 return cost;
2982 * Test-procedure for HasVehicleOnPos to check for a ship.
2984 static Vehicle *EnsureNoShipProc(Vehicle *v, void *data)
2986 return v->type == VEH_SHIP ? v : NULL;
2989 static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2991 int z_old;
2992 Slope tileh_old = GetTileSlope(tile, &z_old);
2993 if (IsPlainRail(tile)) {
2994 TrackBits rail_bits = GetTrackBits(tile);
2995 /* Is there flat water on the lower halftile that must be cleared expensively? */
2996 bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
2998 /* Allow clearing the water only if there is no ship */
2999 if (was_water && HasVehicleOnPos(tile, NULL, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
3001 /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
3002 CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
3004 /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
3005 Corner allowed_corner;
3006 switch (rail_bits) {
3007 case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
3008 case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
3009 case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
3010 case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
3011 default: return autoslope_result;
3014 Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
3016 /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3017 if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
3019 /* Everything is valid, which only changes allowed_corner */
3020 for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
3021 if (allowed_corner == corner) continue;
3022 if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
3025 /* Make the ground dirty */
3026 if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3028 /* allow terraforming */
3029 return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0);
3030 } else if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() &&
3031 AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) {
3032 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3034 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3038 extern const TileTypeProcs _tile_type_rail_procs = {
3039 DrawTile_Track, // draw_tile_proc
3040 GetSlopePixelZ_Track, // get_slope_z_proc
3041 ClearTile_Track, // clear_tile_proc
3042 NULL, // add_accepted_cargo_proc
3043 GetTileDesc_Track, // get_tile_desc_proc
3044 GetTileTrackStatus_Track, // get_tile_track_status_proc
3045 ClickTile_Track, // click_tile_proc
3046 NULL, // animate_tile_proc
3047 TileLoop_Track, // tile_loop_proc
3048 ChangeTileOwner_Track, // change_tile_owner_proc
3049 NULL, // add_produced_cargo_proc
3050 VehicleEnter_Track, // vehicle_enter_tile_proc
3051 GetFoundation_Track, // get_foundation_proc
3052 TerraformTile_Track, // terraform_tile_proc