OpenTTD
rail_cmd.cpp
Go to the documentation of this file.
1 /* $Id: rail_cmd.cpp 27427 2015-10-30 17:24:30Z frosch $ */
2 
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  */
9 
12 #include "stdafx.h"
13 #include "cmd_helper.h"
14 #include "viewport_func.h"
15 #include "command_func.h"
16 #include "depot_base.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"
36 
37 #include "table/strings.h"
38 #include "table/railtypes.h"
39 #include "table/track_land.h"
40 
41 #include "safeguards.h"
42 
45 
46 RailtypeInfo _railtypes[RAILTYPE_END];
47 RailType _sorted_railtypes[RAILTYPE_END];
48 uint8 _sorted_railtypes_size;
49 
50 assert_compile(sizeof(_original_railtypes) <= sizeof(_railtypes));
51 
54  SIGNAL_TO_SOUTHWEST,
55  SIGNAL_TO_NORTHEAST,
56  SIGNAL_TO_SOUTHEAST,
57  SIGNAL_TO_NORTHWEST,
58  SIGNAL_TO_EAST,
59  SIGNAL_TO_WEST,
60  SIGNAL_TO_SOUTH,
61  SIGNAL_TO_NORTH,
62 };
63 
68 {
69  memset(_railtypes, 0, sizeof(_railtypes));
70  memcpy(_railtypes, _original_railtypes, sizeof(_original_railtypes));
71 }
72 
73 void ResolveRailTypeGUISprites(RailtypeInfo *rti)
74 {
76  if (cursors_base != 0) {
77  rti->gui_sprites.build_ns_rail = cursors_base + 0;
78  rti->gui_sprites.build_x_rail = cursors_base + 1;
79  rti->gui_sprites.build_ew_rail = cursors_base + 2;
80  rti->gui_sprites.build_y_rail = cursors_base + 3;
81  rti->gui_sprites.auto_rail = cursors_base + 4;
82  rti->gui_sprites.build_depot = cursors_base + 5;
83  rti->gui_sprites.build_tunnel = cursors_base + 6;
84  rti->gui_sprites.convert_rail = cursors_base + 7;
85  rti->cursor.rail_ns = cursors_base + 8;
86  rti->cursor.rail_swne = cursors_base + 9;
87  rti->cursor.rail_ew = cursors_base + 10;
88  rti->cursor.rail_nwse = cursors_base + 11;
89  rti->cursor.autorail = cursors_base + 12;
90  rti->cursor.depot = cursors_base + 13;
91  rti->cursor.tunnel = cursors_base + 14;
92  rti->cursor.convert = cursors_base + 15;
93  }
94 
95  /* Array of default GUI signal sprite numbers. */
96  const SpriteID _signal_lookup[2][SIGTYPE_END] = {
97  {SPR_IMG_SIGNAL_ELECTRIC_NORM, SPR_IMG_SIGNAL_ELECTRIC_ENTRY, SPR_IMG_SIGNAL_ELECTRIC_EXIT,
98  SPR_IMG_SIGNAL_ELECTRIC_COMBO, SPR_IMG_SIGNAL_ELECTRIC_PBS, SPR_IMG_SIGNAL_ELECTRIC_PBS_OWAY},
99 
100  {SPR_IMG_SIGNAL_SEMAPHORE_NORM, SPR_IMG_SIGNAL_SEMAPHORE_ENTRY, SPR_IMG_SIGNAL_SEMAPHORE_EXIT,
101  SPR_IMG_SIGNAL_SEMAPHORE_COMBO, SPR_IMG_SIGNAL_SEMAPHORE_PBS, SPR_IMG_SIGNAL_SEMAPHORE_PBS_OWAY},
102  };
103 
104  for (SignalType type = SIGTYPE_NORMAL; type < SIGTYPE_END; type = (SignalType)(type + 1)) {
105  for (SignalVariant var = SIG_ELECTRIC; var <= SIG_SEMAPHORE; var = (SignalVariant)(var + 1)) {
106  SpriteID red = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_RED, true);
107  SpriteID green = GetCustomSignalSprite(rti, INVALID_TILE, type, var, SIGNAL_STATE_GREEN, true);
108  rti->gui_sprites.signals[type][var][0] = (red != 0) ? red + SIGNAL_TO_SOUTH : _signal_lookup[var][type];
109  rti->gui_sprites.signals[type][var][1] = (green != 0) ? green + SIGNAL_TO_SOUTH : _signal_lookup[var][type] + 1;
110  }
111  }
112 }
113 
120 static int CDECL CompareRailTypes(const RailType *first, const RailType *second)
121 {
122  return GetRailTypeInfo(*first)->sorting_order - GetRailTypeInfo(*second)->sorting_order;
123 }
124 
129 {
130  for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
131  RailtypeInfo *rti = &_railtypes[rt];
132  ResolveRailTypeGUISprites(rti);
133  }
134 
135  _sorted_railtypes_size = 0;
136  for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
137  if (_railtypes[rt].label != 0) {
138  _sorted_railtypes[_sorted_railtypes_size++] = rt;
139  }
140  }
141  QSortT(_sorted_railtypes, _sorted_railtypes_size, CompareRailTypes);
142 }
143 
147 RailType AllocateRailType(RailTypeLabel label)
148 {
149  for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
150  RailtypeInfo *rti = &_railtypes[rt];
151 
152  if (rti->label == 0) {
153  /* Set up new rail type */
154  memcpy(rti, &_railtypes[RAILTYPE_RAIL], sizeof(*rti));
155  rti->label = label;
156  /* Clear alternate label list. Can't use Reset() here as that would free
157  * the data pointer of RAILTYPE_RAIL and not our new rail type. */
159 
160  /* Make us compatible with ourself. */
161  rti->powered_railtypes = (RailTypes)(1 << rt);
162  rti->compatible_railtypes = (RailTypes)(1 << rt);
163 
164  /* We also introduce ourself. */
165  rti->introduces_railtypes = (RailTypes)(1 << rt);
166 
167  /* Default sort order; order of allocation, but with some
168  * offsets so it's easier for NewGRF to pick a spot without
169  * changing the order of other (original) rail types.
170  * The << is so you can place other railtypes in between the
171  * other railtypes, the 7 is to be able to place something
172  * before the first (default) rail type. */
173  rti->sorting_order = rt << 4 | 7;
174  return rt;
175  }
176  }
177 
178  return INVALID_RAILTYPE;
179 }
180 
181 static const byte _track_sloped_sprites[14] = {
182  14, 15, 22, 13,
183  0, 21, 17, 12,
184  23, 0, 18, 20,
185  19, 16
186 };
187 
188 
189 /* 4
190  * ---------
191  * |\ /|
192  * | \ 1/ |
193  * | \ / |
194  * | \ / |
195  * 16| \ |32
196  * | / \2 |
197  * | / \ |
198  * | / \ |
199  * |/ \|
200  * ---------
201  * 8
202  */
203 
204 
205 
206 /* MAP2 byte: abcd???? => Signal On? Same coding as map3lo
207  * MAP3LO byte: abcd???? => Signal Exists?
208  * a and b are for diagonals, upper and left,
209  * one for each direction. (ie a == NE->SW, b ==
210  * SW->NE, or v.v., I don't know. b and c are
211  * similar for lower and right.
212  * MAP2 byte: ????abcd => Type of ground.
213  * MAP3LO byte: ????abcd => Type of rail.
214  * MAP5: 00abcdef => rail
215  * 01abcdef => rail w/ signals
216  * 10uuuuuu => unused
217  * 11uuuudd => rail depot
218  */
219 
229 {
230  TrackBits rail_bits = TrackToTrackBits(track);
231  return EnsureNoTrainOnTrackBits(tile, rail_bits);
232 }
233 
241 static CommandCost CheckTrackCombination(TileIndex tile, TrackBits to_build, uint flags)
242 {
243  if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
244 
245  /* So, we have a tile with tracks on it (and possibly signals). Let's see
246  * what tracks first */
247  TrackBits current = GetTrackBits(tile); // The current track layout.
248  TrackBits future = current | to_build; // The track layout we want to build.
249 
250  /* Are we really building something new? */
251  if (current == future) {
252  /* Nothing new is being built */
253  return_cmd_error(STR_ERROR_ALREADY_BUILT);
254  }
255 
256  /* Let's see if we may build this */
257  if ((flags & DC_NO_RAIL_OVERLAP) || HasSignals(tile)) {
258  /* If we are not allowed to overlap (flag is on for ai companies or we have
259  * signals on the tile), check that */
260  if (future != TRACK_BIT_HORZ && future != TRACK_BIT_VERT) {
261  return_cmd_error((flags & DC_NO_RAIL_OVERLAP) ? STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION : STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
262  }
263  }
264  /* Normally, we may overlap and any combination is valid */
265  return CommandCost();
266 }
267 
268 
274  TRACK_BIT_X,
275 
278  TRACK_BIT_Y,
280 
282  TRACK_BIT_Y,
285 
286  TRACK_BIT_X,
289 };
290 
296  TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_LEFT,
297 
300  TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_RIGHT,
302 
304  TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_LEFT,
307 
308  TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_RIGHT,
310  TRACK_BIT_ALL
311 };
312 
321 {
322  if (bits == TRACK_BIT_NONE) return FOUNDATION_NONE;
323 
324  if (IsSteepSlope(tileh)) {
325  /* Test for inclined foundations */
326  if (bits == TRACK_BIT_X) return FOUNDATION_INCLINED_X;
327  if (bits == TRACK_BIT_Y) return FOUNDATION_INCLINED_Y;
328 
329  /* Get higher track */
330  Corner highest_corner = GetHighestSlopeCorner(tileh);
331  TrackBits higher_track = CornerToTrackBits(highest_corner);
332 
333  /* Only higher track? */
334  if (bits == higher_track) return HalftileFoundation(highest_corner);
335 
336  /* Overlap with higher track? */
337  if (TracksOverlap(bits | higher_track)) return FOUNDATION_INVALID;
338 
339  /* either lower track or both higher and lower track */
340  return ((bits & higher_track) != 0 ? FOUNDATION_STEEP_BOTH : FOUNDATION_STEEP_LOWER);
341  } else {
342  if ((~_valid_tracks_without_foundation[tileh] & bits) == 0) return FOUNDATION_NONE;
343 
344  bool valid_on_leveled = ((~_valid_tracks_on_leveled_foundation[tileh] & bits) == 0);
345 
346  Corner track_corner;
347  switch (bits) {
348  case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
349  case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
350  case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
351  case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
352 
353  case TRACK_BIT_HORZ:
354  if (tileh == SLOPE_N) return HalftileFoundation(CORNER_N);
355  if (tileh == SLOPE_S) return HalftileFoundation(CORNER_S);
356  return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
357 
358  case TRACK_BIT_VERT:
359  if (tileh == SLOPE_W) return HalftileFoundation(CORNER_W);
360  if (tileh == SLOPE_E) return HalftileFoundation(CORNER_E);
361  return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
362 
363  case TRACK_BIT_X:
365  return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
366 
367  case TRACK_BIT_Y:
369  return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
370 
371  default:
372  return (valid_on_leveled ? FOUNDATION_LEVELED : FOUNDATION_INVALID);
373  }
374  /* Single diagonal track */
375 
376  /* Track must be at least valid on leveled foundation */
377  if (!valid_on_leveled) return FOUNDATION_INVALID;
378 
379  /* If slope has three raised corners, build leveled foundation */
381 
382  /* If neighboured corners of track_corner are lowered, build halftile foundation */
383  if ((tileh & SlopeWithThreeCornersRaised(OppositeCorner(track_corner))) == SlopeWithOneCornerRaised(track_corner)) return HalftileFoundation(track_corner);
384 
385  /* else special anti-zig-zag foundation */
386  return SpecialRailFoundation(track_corner);
387  }
388 }
389 
390 
400 static CommandCost CheckRailSlope(Slope tileh, TrackBits rail_bits, TrackBits existing, TileIndex tile)
401 {
402  /* don't allow building on the lower side of a coast */
403  if (GetFloodingBehaviour(tile) != FLOOD_NONE) {
404  if (!IsSteepSlope(tileh) && ((~_valid_tracks_on_leveled_foundation[tileh] & (rail_bits | existing)) != 0)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
405  }
406 
407  Foundation f_new = GetRailFoundation(tileh, rail_bits | existing);
408 
409  /* check track/slope combination */
410  if ((f_new == FOUNDATION_INVALID) ||
412  return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
413  }
414 
415  Foundation f_old = GetRailFoundation(tileh, existing);
416  return CommandCost(EXPENSES_CONSTRUCTION, f_new != f_old ? _price[PR_BUILD_FOUNDATION] : (Money)0);
417 }
418 
419 /* Validate functions for rail building */
420 static inline bool ValParamTrackOrientation(Track track)
421 {
422  return IsValidTrack(track);
423 }
424 
434 CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
435 {
436  RailType railtype = Extract<RailType, 0, 4>(p1);
437  Track track = Extract<Track, 0, 3>(p2);
439 
440  if (!ValParamRailtype(railtype) || !ValParamTrackOrientation(track)) return CMD_ERROR;
441 
442  Slope tileh = GetTileSlope(tile);
443  TrackBits trackbit = TrackToTrackBits(track);
444 
445  switch (GetTileType(tile)) {
446  case MP_RAILWAY: {
447  CommandCost ret = CheckTileOwnership(tile);
448  if (ret.Failed()) return ret;
449 
450  if (!IsPlainRail(tile)) return CMD_ERROR;
451 
452  if (!IsCompatibleRail(GetRailType(tile), railtype)) return_cmd_error(STR_ERROR_IMPOSSIBLE_TRACK_COMBINATION);
453 
454  ret = CheckTrackCombination(tile, trackbit, flags);
455  if (ret.Succeeded()) ret = EnsureNoTrainOnTrack(tile, track);
456  if (ret.Failed()) return ret;
457 
458  ret = CheckRailSlope(tileh, trackbit, GetTrackBits(tile), tile);
459  if (ret.Failed()) return ret;
460  cost.AddCost(ret);
461 
462  /* If the rail types don't match, try to convert only if engines of
463  * the new rail type are not powered on the present rail type and engines of
464  * the present rail type are powered on the new rail type. */
465  if (GetRailType(tile) != railtype && !HasPowerOnRail(railtype, GetRailType(tile))) {
466  if (HasPowerOnRail(GetRailType(tile), railtype)) {
467  ret = DoCommand(tile, tile, railtype, flags, CMD_CONVERT_RAIL);
468  if (ret.Failed()) return ret;
469  cost.AddCost(ret);
470  } else {
471  return CMD_ERROR;
472  }
473  }
474 
475  if (flags & DC_EXEC) {
476  SetRailGroundType(tile, RAIL_GROUND_BARREN);
477  TrackBits bits = GetTrackBits(tile);
478  SetTrackBits(tile, bits | trackbit);
479  /* Subtract old infrastructure count. */
480  uint pieces = CountBits(bits);
481  if (TracksOverlap(bits)) pieces *= pieces;
482  Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] -= pieces;
483  /* Add new infrastructure count. */
484  pieces = CountBits(bits | trackbit);
485  if (TracksOverlap(bits | trackbit)) pieces *= pieces;
486  Company::Get(GetTileOwner(tile))->infrastructure.rail[GetRailType(tile)] += pieces;
488  }
489  break;
490  }
491 
492  case MP_ROAD: {
493  /* Level crossings may only be built on these slopes */
494  if (!HasBit(VALID_LEVEL_CROSSING_SLOPES, tileh)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
495 
497  if (ret.Failed()) return ret;
498 
499  if (IsNormalRoad(tile)) {
500  if (HasRoadWorks(tile)) return_cmd_error(STR_ERROR_ROAD_WORKS_IN_PROGRESS);
501 
502  if (GetDisallowedRoadDirections(tile) != DRD_NONE) return_cmd_error(STR_ERROR_CROSSING_ON_ONEWAY_ROAD);
503 
504  if (RailNoLevelCrossings(railtype)) return_cmd_error(STR_ERROR_CROSSING_DISALLOWED);
505 
506  RoadTypes roadtypes = GetRoadTypes(tile);
507  RoadBits road = GetRoadBits(tile, ROADTYPE_ROAD);
508  RoadBits tram = GetRoadBits(tile, ROADTYPE_TRAM);
509  if ((track == TRACK_X && ((road | tram) & ROAD_X) == 0) ||
510  (track == TRACK_Y && ((road | tram) & ROAD_Y) == 0)) {
511  Owner road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
512  Owner tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
513  /* Disallow breaking end-of-line of someone else
514  * so trams can still reverse on this tile. */
515  if (Company::IsValidID(tram_owner) && HasExactlyOneBit(tram)) {
516  CommandCost ret = CheckOwnership(tram_owner);
517  if (ret.Failed()) return ret;
518  }
519  /* Crossings must always have a road... */
520  uint num_new_road_pieces = 2 - CountBits(road);
521  if (road == ROAD_NONE) road_owner = _current_company;
522  roadtypes |= ROADTYPES_ROAD;
523  /* ...but tram is not required. */
524  uint num_new_tram_pieces = (tram != ROAD_NONE) ? 2 - CountBits(tram) : 0;
525 
526  cost.AddCost((num_new_road_pieces + num_new_tram_pieces) * _price[PR_BUILD_ROAD]);
527 
528  if (flags & DC_EXEC) {
529  MakeRoadCrossing(tile, road_owner, tram_owner, _current_company, (track == TRACK_X ? AXIS_Y : AXIS_X), railtype, roadtypes, GetTownIndex(tile));
530  UpdateLevelCrossing(tile, false);
531  Company::Get(_current_company)->infrastructure.rail[railtype] += LEVELCROSSING_TRACKBIT_FACTOR;
533  if (num_new_road_pieces > 0 && Company::IsValidID(road_owner)) {
534  Company::Get(road_owner)->infrastructure.road[ROADTYPE_ROAD] += num_new_road_pieces;
536  }
537  if (num_new_tram_pieces > 0 && Company::IsValidID(tram_owner)) {
538  Company::Get(tram_owner)->infrastructure.road[ROADTYPE_TRAM] += num_new_tram_pieces;
540  }
541  }
542  break;
543  }
544  }
545 
546  if (IsLevelCrossing(tile) && GetCrossingRailBits(tile) == trackbit) {
547  return_cmd_error(STR_ERROR_ALREADY_BUILT);
548  }
549  /* FALL THROUGH */
550  }
551 
552  default: {
553  /* Will there be flat water on the lower halftile? */
554  bool water_ground = IsTileType(tile, MP_WATER) && IsSlopeWithOneCornerRaised(tileh);
555 
556  CommandCost ret = CheckRailSlope(tileh, trackbit, TRACK_BIT_NONE, tile);
557  if (ret.Failed()) return ret;
558  cost.AddCost(ret);
559 
560  ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
561  if (ret.Failed()) return ret;
562  cost.AddCost(ret);
563 
564  if (water_ground) {
565  cost.AddCost(-_price[PR_CLEAR_WATER]);
566  cost.AddCost(_price[PR_CLEAR_ROUGH]);
567  }
568 
569  if (flags & DC_EXEC) {
570  MakeRailNormal(tile, _current_company, trackbit, railtype);
571  if (water_ground) SetRailGroundType(tile, RAIL_GROUND_WATER);
572  Company::Get(_current_company)->infrastructure.rail[railtype]++;
574  }
575  break;
576  }
577  }
578 
579  if (flags & DC_EXEC) {
580  MarkTileDirtyByTile(tile);
582  YapfNotifyTrackLayoutChange(tile, track);
583  }
584 
585  cost.AddCost(RailBuildCost(railtype));
586  return cost;
587 }
588 
598 CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
599 {
600  Track track = Extract<Track, 0, 3>(p2);
602  bool crossing = false;
603 
604  if (!ValParamTrackOrientation(track)) return CMD_ERROR;
605  TrackBits trackbit = TrackToTrackBits(track);
606 
607  /* Need to read tile owner now because it may change when the rail is removed
608  * Also, in case of floods, _current_company != owner
609  * There may be invalid tiletype even in exec run (when removing long track),
610  * so do not call GetTileOwner(tile) in any case here */
611  Owner owner = INVALID_OWNER;
612 
613  Train *v = NULL;
614 
615  switch (GetTileType(tile)) {
616  case MP_ROAD: {
617  if (!IsLevelCrossing(tile) || GetCrossingRailBits(tile) != trackbit) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
618 
619  if (_current_company != OWNER_WATER) {
620  CommandCost ret = CheckTileOwnership(tile);
621  if (ret.Failed()) return ret;
622  }
623 
624  if (!(flags & DC_BANKRUPT)) {
626  if (ret.Failed()) return ret;
627  }
628 
629  cost.AddCost(RailClearCost(GetRailType(tile)));
630 
631  if (flags & DC_EXEC) {
632  if (HasReservedTracks(tile, trackbit)) {
633  v = GetTrainForReservation(tile, track);
634  if (v != NULL) FreeTrainTrackReservation(v);
635  }
636  owner = GetTileOwner(tile);
637  Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= LEVELCROSSING_TRACKBIT_FACTOR;
640  DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
641  }
642  break;
643  }
644 
645  case MP_RAILWAY: {
646  TrackBits present;
647  /* There are no rails present at depots. */
648  if (!IsPlainRail(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
649 
650  if (_current_company != OWNER_WATER) {
651  CommandCost ret = CheckTileOwnership(tile);
652  if (ret.Failed()) return ret;
653  }
654 
655  CommandCost ret = EnsureNoTrainOnTrack(tile, track);
656  if (ret.Failed()) return ret;
657 
658  present = GetTrackBits(tile);
659  if ((present & trackbit) == 0) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
660  if (present == (TRACK_BIT_X | TRACK_BIT_Y)) crossing = true;
661 
662  cost.AddCost(RailClearCost(GetRailType(tile)));
663 
664  /* Charge extra to remove signals on the track, if they are there */
665  if (HasSignalOnTrack(tile, track)) {
666  cost.AddCost(DoCommand(tile, track, 0, flags, CMD_REMOVE_SIGNALS));
667  }
668 
669  if (flags & DC_EXEC) {
670  if (HasReservedTracks(tile, trackbit)) {
671  v = GetTrainForReservation(tile, track);
672  if (v != NULL) FreeTrainTrackReservation(v);
673  }
674 
675  owner = GetTileOwner(tile);
676 
677  /* Subtract old infrastructure count. */
678  uint pieces = CountBits(present);
679  if (TracksOverlap(present)) pieces *= pieces;
680  Company::Get(owner)->infrastructure.rail[GetRailType(tile)] -= pieces;
681  /* Add new infrastructure count. */
682  present ^= trackbit;
683  pieces = CountBits(present);
684  if (TracksOverlap(present)) pieces *= pieces;
685  Company::Get(owner)->infrastructure.rail[GetRailType(tile)] += pieces;
687 
688  if (present == 0) {
689  Slope tileh = GetTileSlope(tile);
690  /* If there is flat water on the lower halftile, convert the tile to shore so the water remains */
691  if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh)) {
692  MakeShore(tile);
693  } else {
694  DoClearSquare(tile);
695  }
696  DeleteNewGRFInspectWindow(GSF_RAILTYPES, tile);
697  } else {
698  SetTrackBits(tile, present);
699  SetTrackReservation(tile, GetRailReservationTrackBits(tile) & present);
700  }
701  }
702  break;
703  }
704 
705  default: return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
706  }
707 
708  if (flags & DC_EXEC) {
709  /* if we got that far, 'owner' variable is set correctly */
710  assert(Company::IsValidID(owner));
711 
712  MarkTileDirtyByTile(tile);
713  if (crossing) {
714  /* crossing is set when only TRACK_BIT_X and TRACK_BIT_Y are set. As we
715  * are removing one of these pieces, we'll need to update signals for
716  * both directions explicitly, as after the track is removed it won't
717  * 'connect' with the other piece. */
718  AddTrackToSignalBuffer(tile, TRACK_X, owner);
719  AddTrackToSignalBuffer(tile, TRACK_Y, owner);
722  } else {
723  AddTrackToSignalBuffer(tile, track, owner);
724  YapfNotifyTrackLayoutChange(tile, track);
725  }
726 
727  if (v != NULL) TryPathReserve(v, true);
728  }
729 
730  return cost;
731 }
732 
733 
742 {
743  assert(IsPlainRailTile(t));
744 
745  bool flooded = false;
746  if (GetRailGroundType(t) == RAIL_GROUND_WATER) return flooded;
747 
748  Slope tileh = GetTileSlope(t);
749  TrackBits rail_bits = GetTrackBits(t);
750 
751  if (IsSlopeWithOneCornerRaised(tileh)) {
753 
754  TrackBits to_remove = lower_track & rail_bits;
755  if (to_remove != 0) {
756  Backup<CompanyByte> cur_company(_current_company, OWNER_WATER, FILE_LINE);
757  flooded = DoCommand(t, 0, FIND_FIRST_BIT(to_remove), DC_EXEC, CMD_REMOVE_SINGLE_RAIL).Succeeded();
758  cur_company.Restore();
759  if (!flooded) return flooded; // not yet floodable
760  rail_bits = rail_bits & ~to_remove;
761  if (rail_bits == 0) {
762  MakeShore(t);
764  return flooded;
765  }
766  }
767 
768  if (IsNonContinuousFoundation(GetRailFoundation(tileh, rail_bits))) {
769  flooded = true;
770  SetRailGroundType(t, RAIL_GROUND_WATER);
772  }
773  } else {
774  /* Make shore on steep slopes and 'three-corners-raised'-slopes. */
775  if (ApplyFoundationToSlope(GetRailFoundation(tileh, rail_bits), &tileh) == 0) {
776  if (IsSteepSlope(tileh) || IsSlopeWithThreeCornersRaised(tileh)) {
777  flooded = true;
778  SetRailGroundType(t, RAIL_GROUND_WATER);
780  }
781  }
782  }
783  return flooded;
784 }
785 
786 static const TileIndexDiffC _trackdelta[] = {
787  { -1, 0 }, { 0, 1 }, { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, 1 },
788  { 0, 0 },
789  { 0, 0 },
790  { 1, 0 }, { 0, -1 }, { 0, -1 }, { 1, 0 }, { 0, -1 }, { -1, 0 },
791  { 0, 0 },
792  { 0, 0 }
793 };
794 
795 
796 static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileIndex end)
797 {
798  int x = TileX(start);
799  int y = TileY(start);
800  int ex = TileX(end);
801  int ey = TileY(end);
802 
803  if (!ValParamTrackOrientation(TrackdirToTrack(*trackdir))) return CMD_ERROR;
804 
805  /* calculate delta x,y from start to end tile */
806  int dx = ex - x;
807  int dy = ey - y;
808 
809  /* calculate delta x,y for the first direction */
810  int trdx = _trackdelta[*trackdir].x;
811  int trdy = _trackdelta[*trackdir].y;
812 
813  if (!IsDiagonalTrackdir(*trackdir)) {
814  trdx += _trackdelta[*trackdir ^ 1].x;
815  trdy += _trackdelta[*trackdir ^ 1].y;
816  }
817 
818  /* validate the direction */
819  while ((trdx <= 0 && dx > 0) ||
820  (trdx >= 0 && dx < 0) ||
821  (trdy <= 0 && dy > 0) ||
822  (trdy >= 0 && dy < 0)) {
823  if (!HasBit(*trackdir, 3)) { // first direction is invalid, try the other
824  SetBit(*trackdir, 3); // reverse the direction
825  trdx = -trdx;
826  trdy = -trdy;
827  } else { // other direction is invalid too, invalid drag
828  return CMD_ERROR;
829  }
830  }
831 
832  /* (for diagonal tracks, this is already made sure of by above test), but:
833  * for non-diagonal tracks, check if the start and end tile are on 1 line */
834  if (!IsDiagonalTrackdir(*trackdir)) {
835  trdx = _trackdelta[*trackdir].x;
836  trdy = _trackdelta[*trackdir].y;
837  if (abs(dx) != abs(dy) && abs(dx) + abs(trdy) != abs(dy) + abs(trdx)) return CMD_ERROR;
838  }
839 
840  return CommandCost();
841 }
842 
856 static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
857 {
859  Track track = Extract<Track, 4, 3>(p2);
860  bool remove = HasBit(p2, 7);
861  RailType railtype = Extract<RailType, 0, 4>(p2);
862 
863  if ((!remove && !ValParamRailtype(railtype)) || !ValParamTrackOrientation(track)) return CMD_ERROR;
864  if (p1 >= MapSize()) return CMD_ERROR;
865  TileIndex end_tile = p1;
866  Trackdir trackdir = TrackToTrackdir(track);
867 
868  CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
869  if (ret.Failed()) return ret;
870 
871  bool had_success = false;
872  CommandCost last_error = CMD_ERROR;
873  for (;;) {
874  CommandCost ret = DoCommand(tile, remove ? 0 : railtype, TrackdirToTrack(trackdir), flags, remove ? CMD_REMOVE_SINGLE_RAIL : CMD_BUILD_SINGLE_RAIL);
875 
876  if (ret.Failed()) {
877  last_error = ret;
878  if (last_error.GetErrorMessage() != STR_ERROR_ALREADY_BUILT && !remove) {
879  if (HasBit(p2, 8)) return last_error;
880  break;
881  }
882 
883  /* Ownership errors are more important. */
884  if (last_error.GetErrorMessage() == STR_ERROR_OWNED_BY && remove) break;
885  } else {
886  had_success = true;
887  total_cost.AddCost(ret);
888  }
889 
890  if (tile == end_tile) break;
891 
892  tile += ToTileIndexDiff(_trackdelta[trackdir]);
893 
894  /* toggle railbit for the non-diagonal tracks */
895  if (!IsDiagonalTrackdir(trackdir)) ToggleBit(trackdir, 0);
896  }
897 
898  if (had_success) return total_cost;
899  return last_error;
900 }
901 
916 CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
917 {
918  return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 7), text);
919 }
920 
935 CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
936 {
937  return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 7), text);
938 }
939 
952 CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
953 {
954  /* check railtype and valid direction for depot (0 through 3), 4 in total */
955  RailType railtype = Extract<RailType, 0, 4>(p1);
956  if (!ValParamRailtype(railtype)) return CMD_ERROR;
957 
958  Slope tileh = GetTileSlope(tile);
959 
960  DiagDirection dir = Extract<DiagDirection, 0, 2>(p2);
961 
962  /* Prohibit construction if
963  * The tile is non-flat AND
964  * 1) build-on-slopes is disabled
965  * 2) the tile is steep i.e. spans two height levels
966  * 3) the exit points in the wrong direction
967  */
968 
969  if (tileh != SLOPE_FLAT && (
971  !CanBuildDepotByTileh(dir, tileh)
972  )) {
973  return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
974  }
975 
976  CommandCost cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
977  if (cost.Failed()) return cost;
978 
979  if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
980 
981  if (!Depot::CanAllocateItem()) return CMD_ERROR;
982 
983  if (flags & DC_EXEC) {
984  Depot *d = new Depot(tile);
985  d->build_date = _date;
986 
987  MakeRailDepot(tile, _current_company, d->index, dir, railtype);
988  MarkTileDirtyByTile(tile);
989  MakeDefaultName(d);
990 
991  Company::Get(_current_company)->infrastructure.rail[railtype]++;
993 
996  }
997 
998  cost.AddCost(_price[PR_BUILD_DEPOT_TRAIN]);
999  cost.AddCost(RailBuildCost(railtype));
1000  return cost;
1001 }
1002 
1024 CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1025 {
1026  Track track = Extract<Track, 0, 3>(p1);
1027  bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed
1028  SignalVariant sigvar = (ctrl_pressed ^ HasBit(p1, 4)) ? SIG_SEMAPHORE : SIG_ELECTRIC; // the signal variant of the new signal
1029  SignalType sigtype = Extract<SignalType, 5, 3>(p1); // the signal type of the new signal
1030  bool convert_signal = HasBit(p1, 8); // convert button pressed
1031  SignalType cycle_start = Extract<SignalType, 9, 3>(p1);
1032  SignalType cycle_stop = Extract<SignalType, 12, 3>(p1);
1033  uint num_dir_cycle = GB(p1, 15, 2);
1034 
1035  if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1036  if (cycle_start > cycle_stop || cycle_stop > SIGTYPE_LAST) return CMD_ERROR;
1037 
1038  /* You can only build signals on plain rail tiles, and the selected track must exist */
1039  if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) ||
1040  !HasTrack(tile, track)) {
1041  return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1042  }
1043  /* Protect against invalid signal copying */
1044  if (p2 != 0 && (p2 & SignalOnTrack(track)) == 0) return CMD_ERROR;
1045 
1046  CommandCost ret = CheckTileOwnership(tile);
1047  if (ret.Failed()) return ret;
1048 
1049  /* See if this is a valid track combination for signals (no overlap) */
1050  if (TracksOverlap(GetTrackBits(tile))) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
1051 
1052  /* In case we don't want to change an existing signal, return without error. */
1053  if (HasBit(p1, 17) && HasSignalOnTrack(tile, track)) return CommandCost();
1054 
1055  /* you can not convert a signal if no signal is on track */
1056  if (convert_signal && !HasSignalOnTrack(tile, track)) return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1057 
1058  CommandCost cost;
1059  if (!HasSignalOnTrack(tile, track)) {
1060  /* build new signals */
1061  cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS]);
1062  } else {
1063  if (p2 != 0 && sigvar != GetSignalVariant(tile, track)) {
1064  /* convert signals <-> semaphores */
1065  cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1066 
1067  } else if (convert_signal) {
1068  /* convert button pressed */
1069  if (ctrl_pressed || GetSignalVariant(tile, track) != sigvar) {
1070  /* convert electric <-> semaphore */
1071  cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_SIGNALS] + _price[PR_CLEAR_SIGNALS]);
1072  } else {
1073  /* it is free to change signal type: normal-pre-exit-combo */
1074  cost = CommandCost();
1075  }
1076 
1077  } else {
1078  /* it is free to change orientation/pre-exit-combo signals */
1079  cost = CommandCost();
1080  }
1081  }
1082 
1083  if (flags & DC_EXEC) {
1084  Train *v = NULL;
1085  /* The new/changed signal could block our path. As this can lead to
1086  * stale reservations, we clear the path reservation here and try
1087  * to redo it later on. */
1088  if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1089  v = GetTrainForReservation(tile, track);
1090  if (v != NULL) FreeTrainTrackReservation(v);
1091  }
1092 
1093  if (!HasSignals(tile)) {
1094  /* there are no signals at all on this tile yet */
1095  SetHasSignals(tile, true);
1096  SetSignalStates(tile, 0xF); // all signals are on
1097  SetPresentSignals(tile, 0); // no signals built by default
1098  SetSignalType(tile, track, sigtype);
1099  SetSignalVariant(tile, track, sigvar);
1100  }
1101 
1102  /* Subtract old signal infrastructure count. */
1103  Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1104 
1105  if (p2 == 0) {
1106  if (!HasSignalOnTrack(tile, track)) {
1107  /* build new signals */
1108  SetPresentSignals(tile, GetPresentSignals(tile) | (IsPbsSignal(sigtype) ? KillFirstBit(SignalOnTrack(track)) : SignalOnTrack(track)));
1109  SetSignalType(tile, track, sigtype);
1110  SetSignalVariant(tile, track, sigvar);
1111  while (num_dir_cycle-- > 0) CycleSignalSide(tile, track);
1112  } else {
1113  if (convert_signal) {
1114  /* convert signal button pressed */
1115  if (ctrl_pressed) {
1116  /* toggle the present signal variant: SIG_ELECTRIC <-> SIG_SEMAPHORE */
1117  SetSignalVariant(tile, track, (GetSignalVariant(tile, track) == SIG_ELECTRIC) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1118  /* Query current signal type so the check for PBS signals below works. */
1119  sigtype = GetSignalType(tile, track);
1120  } else {
1121  /* convert the present signal to the chosen type and variant */
1122  SetSignalType(tile, track, sigtype);
1123  SetSignalVariant(tile, track, sigvar);
1124  if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1125  SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1126  }
1127  }
1128 
1129  } else if (ctrl_pressed) {
1130  /* cycle between cycle_start and cycle_end */
1131  sigtype = (SignalType)(GetSignalType(tile, track) + 1);
1132 
1133  if (sigtype < cycle_start || sigtype > cycle_stop) sigtype = cycle_start;
1134 
1135  SetSignalType(tile, track, sigtype);
1136  if (IsPbsSignal(sigtype) && (GetPresentSignals(tile) & SignalOnTrack(track)) == SignalOnTrack(track)) {
1137  SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | KillFirstBit(SignalOnTrack(track)));
1138  }
1139  } else {
1140  /* cycle the signal side: both -> left -> right -> both -> ... */
1141  CycleSignalSide(tile, track);
1142  /* Query current signal type so the check for PBS signals below works. */
1143  sigtype = GetSignalType(tile, track);
1144  }
1145  }
1146  } else {
1147  /* If CmdBuildManySignals is called with copying signals, just copy the
1148  * direction of the first signal given as parameter by CmdBuildManySignals */
1149  SetPresentSignals(tile, (GetPresentSignals(tile) & ~SignalOnTrack(track)) | (p2 & SignalOnTrack(track)));
1150  SetSignalVariant(tile, track, sigvar);
1151  SetSignalType(tile, track, sigtype);
1152  }
1153 
1154  /* Add new signal infrastructure count. */
1155  Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1157 
1158  if (IsPbsSignal(sigtype)) {
1159  /* PBS signals should show red unless they are on reserved tiles without a train. */
1160  uint mask = GetPresentSignals(tile) & SignalOnTrack(track);
1161  SetSignalStates(tile, (GetSignalStates(tile) & ~mask) | ((HasBit(GetRailReservationTrackBits(tile), track) && EnsureNoVehicleOnGround(tile).Succeeded() ? UINT_MAX : 0) & mask));
1162  }
1163  MarkTileDirtyByTile(tile);
1165  YapfNotifyTrackLayoutChange(tile, track);
1166  if (v != NULL) {
1167  /* Extend the train's path if it's not stopped or loading, or not at a safe position. */
1168  if (!(((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) || v->current_order.IsType(OT_LOADING)) ||
1170  TryPathReserve(v, true);
1171  }
1172  }
1173  }
1174 
1175  return cost;
1176 }
1177 
1178 static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal_ctr, bool remove)
1179 {
1180  tile = AddTileIndexDiffCWrap(tile, _trackdelta[trackdir]);
1181  if (tile == INVALID_TILE) return false;
1182 
1183  /* Check for track bits on the new tile */
1185 
1186  if (TracksOverlap(TrackdirBitsToTrackBits(trackdirbits))) return false;
1187  trackdirbits &= TrackdirReachesTrackdirs(trackdir);
1188 
1189  /* No track bits, must stop */
1190  if (trackdirbits == TRACKDIR_BIT_NONE) return false;
1191 
1192  /* Get the first track dir */
1193  trackdir = RemoveFirstTrackdir(&trackdirbits);
1194 
1195  /* Any left? It's a junction so we stop */
1196  if (trackdirbits != TRACKDIR_BIT_NONE) return false;
1197 
1198  switch (GetTileType(tile)) {
1199  case MP_RAILWAY:
1200  if (IsRailDepot(tile)) return false;
1201  if (!remove && HasSignalOnTrack(tile, TrackdirToTrack(trackdir))) return false;
1202  signal_ctr++;
1203  if (IsDiagonalTrackdir(trackdir)) {
1204  signal_ctr++;
1205  /* Ensure signal_ctr even so X and Y pieces get signals */
1206  ClrBit(signal_ctr, 0);
1207  }
1208  return true;
1209 
1210  case MP_ROAD:
1211  if (!IsLevelCrossing(tile)) return false;
1212  signal_ctr += 2;
1213  return true;
1214 
1215  case MP_TUNNELBRIDGE: {
1216  TileIndex orig_tile = tile; // backup old value
1217 
1218  if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) return false;
1219  if (GetTunnelBridgeDirection(tile) != TrackdirToExitdir(trackdir)) return false;
1220 
1221  /* Skip to end of tunnel or bridge
1222  * note that tile is a parameter by reference, so it must be updated */
1223  tile = GetOtherTunnelBridgeEnd(tile);
1224 
1225  signal_ctr += (GetTunnelBridgeLength(orig_tile, tile) + 2) * 2;
1226  return true;
1227  }
1228 
1229  default: return false;
1230  }
1231 }
1232 
1250 static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1251 {
1252  CommandCost total_cost(EXPENSES_CONSTRUCTION);
1253  TileIndex start_tile = tile;
1254 
1255  Track track = Extract<Track, 0, 3>(p2);
1256  bool mode = HasBit(p2, 3);
1257  bool semaphores = HasBit(p2, 4);
1258  bool remove = HasBit(p2, 5);
1259  bool autofill = HasBit(p2, 6);
1260  bool minimise_gaps = HasBit(p2, 10);
1261  byte signal_density = GB(p2, 24, 8);
1262 
1263  if (p1 >= MapSize() || !ValParamTrackOrientation(track)) return CMD_ERROR;
1264  TileIndex end_tile = p1;
1265  if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
1266 
1267  if (!IsPlainRailTile(tile)) return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1268 
1269  /* for vertical/horizontal tracks, double the given signals density
1270  * since the original amount will be too dense (shorter tracks) */
1271  signal_density *= 2;
1272 
1273  Trackdir trackdir = TrackToTrackdir(track);
1274  CommandCost ret = ValidateAutoDrag(&trackdir, tile, end_tile);
1275  if (ret.Failed()) return ret;
1276 
1277  track = TrackdirToTrack(trackdir); // trackdir might have changed, keep track in sync
1278  Trackdir start_trackdir = trackdir;
1279 
1280  /* Must start on a valid track to be able to avoid loops */
1281  if (!HasTrack(tile, track)) return CMD_ERROR;
1282 
1283  SignalType sigtype = (SignalType)GB(p2, 7, 3);
1284  if (sigtype > SIGTYPE_LAST) return CMD_ERROR;
1285 
1286  byte signals;
1287  /* copy the signal-style of the first rail-piece if existing */
1288  if (HasSignalOnTrack(tile, track)) {
1289  signals = GetPresentSignals(tile) & SignalOnTrack(track);
1290  assert(signals != 0);
1291 
1292  /* copy signal/semaphores style (independent of CTRL) */
1293  semaphores = GetSignalVariant(tile, track) != SIG_ELECTRIC;
1294 
1295  sigtype = GetSignalType(tile, track);
1296  /* Don't but copy entry or exit-signal type */
1297  if (sigtype == SIGTYPE_ENTRY || sigtype == SIGTYPE_EXIT) sigtype = SIGTYPE_NORMAL;
1298  } else { // no signals exist, drag a two-way signal stretch
1299  signals = IsPbsSignal(sigtype) ? SignalAlongTrackdir(trackdir) : SignalOnTrack(track);
1300  }
1301 
1302  byte signal_dir = 0;
1303  if (signals & SignalAlongTrackdir(trackdir)) SetBit(signal_dir, 0);
1304  if (signals & SignalAgainstTrackdir(trackdir)) SetBit(signal_dir, 1);
1305 
1306  /* signal_ctr - amount of tiles already processed
1307  * last_used_ctr - amount of tiles before previously placed signal
1308  * signals_density - setting to put signal on every Nth tile (double space on |, -- tracks)
1309  * last_suitable_ctr - amount of tiles before last possible signal place
1310  * last_suitable_tile - last tile where it is possible to place a signal
1311  * last_suitable_trackdir - trackdir of the last tile
1312  **********
1313  * trackdir - trackdir to build with autorail
1314  * semaphores - semaphores or signals
1315  * signals - is there a signal/semaphore on the first tile, copy its style (two-way/single-way)
1316  * and convert all others to semaphore/signal
1317  * remove - 1 remove signals, 0 build signals */
1318  int signal_ctr = 0;
1319  int last_used_ctr = INT_MIN; // initially INT_MIN to force building/removing at the first tile
1320  int last_suitable_ctr = 0;
1321  TileIndex last_suitable_tile = INVALID_TILE;
1322  Trackdir last_suitable_trackdir = INVALID_TRACKDIR;
1323  CommandCost last_error = CMD_ERROR;
1324  bool had_success = false;
1325  for (;;) {
1326  /* only build/remove signals with the specified density */
1327  if (remove || minimise_gaps || signal_ctr % signal_density == 0) {
1328  uint32 p1 = GB(TrackdirToTrack(trackdir), 0, 3);
1329  SB(p1, 3, 1, mode);
1330  SB(p1, 4, 1, semaphores);
1331  SB(p1, 5, 3, sigtype);
1332  if (!remove && signal_ctr == 0) SetBit(p1, 17);
1333 
1334  /* Pick the correct orientation for the track direction */
1335  signals = 0;
1336  if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(trackdir);
1337  if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(trackdir);
1338 
1339  /* Test tiles in between for suitability as well if minimising gaps. */
1340  bool test_only = !remove && minimise_gaps && signal_ctr < (last_used_ctr + signal_density);
1341  CommandCost ret = DoCommand(tile, p1, signals, test_only ? flags & ~DC_EXEC : flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1342 
1343  if (ret.Succeeded()) {
1344  /* Remember last track piece where we can place a signal. */
1345  last_suitable_ctr = signal_ctr;
1346  last_suitable_tile = tile;
1347  last_suitable_trackdir = trackdir;
1348  } else if (!test_only && last_suitable_tile != INVALID_TILE) {
1349  /* If a signal can't be placed, place it at the last possible position. */
1350  SB(p1, 0, 3, TrackdirToTrack(last_suitable_trackdir));
1351  ClrBit(p1, 17);
1352 
1353  /* Pick the correct orientation for the track direction. */
1354  signals = 0;
1355  if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(last_suitable_trackdir);
1356  if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(last_suitable_trackdir);
1357 
1358  ret = DoCommand(last_suitable_tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS);
1359  }
1360 
1361  /* Collect cost. */
1362  if (!test_only) {
1363  /* Be user-friendly and try placing signals as much as possible */
1364  if (ret.Succeeded()) {
1365  had_success = true;
1366  total_cost.AddCost(ret);
1367  last_used_ctr = last_suitable_ctr;
1368  last_suitable_tile = INVALID_TILE;
1369  } else {
1370  /* The "No railway" error is the least important one. */
1371  if (ret.GetErrorMessage() != STR_ERROR_THERE_IS_NO_RAILROAD_TRACK ||
1372  last_error.GetErrorMessage() == INVALID_STRING_ID) {
1373  last_error = ret;
1374  }
1375  }
1376  }
1377  }
1378 
1379  if (autofill) {
1380  if (!CheckSignalAutoFill(tile, trackdir, signal_ctr, remove)) break;
1381 
1382  /* Prevent possible loops */
1383  if (tile == start_tile && trackdir == start_trackdir) break;
1384  } else {
1385  if (tile == end_tile) break;
1386 
1387  tile += ToTileIndexDiff(_trackdelta[trackdir]);
1388  signal_ctr++;
1389 
1390  /* toggle railbit for the non-diagonal tracks (|, -- tracks) */
1391  if (IsDiagonalTrackdir(trackdir)) {
1392  signal_ctr++;
1393  } else {
1394  ToggleBit(trackdir, 0);
1395  }
1396  }
1397  }
1398 
1399  return had_success ? total_cost : last_error;
1400 }
1401 
1420 CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1421 {
1422  return CmdSignalTrackHelper(tile, flags, p1, p2, text);
1423 }
1424 
1437 CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1438 {
1439  Track track = Extract<Track, 0, 3>(p1);
1440 
1441  if (!ValParamTrackOrientation(track) || !IsPlainRailTile(tile) || !HasTrack(tile, track)) {
1442  return_cmd_error(STR_ERROR_THERE_IS_NO_RAILROAD_TRACK);
1443  }
1444  if (!HasSignalOnTrack(tile, track)) {
1445  return_cmd_error(STR_ERROR_THERE_ARE_NO_SIGNALS);
1446  }
1447 
1448  /* Only water can remove signals from anyone */
1449  if (_current_company != OWNER_WATER) {
1450  CommandCost ret = CheckTileOwnership(tile);
1451  if (ret.Failed()) return ret;
1452  }
1453 
1454  /* Do it? */
1455  if (flags & DC_EXEC) {
1456  Train *v = NULL;
1457  if (HasReservedTracks(tile, TrackToTrackBits(track))) {
1458  v = GetTrainForReservation(tile, track);
1459  } else if (IsPbsSignal(GetSignalType(tile, track))) {
1460  /* PBS signal, might be the end of a path reservation. */
1461  Trackdir td = TrackToTrackdir(track);
1462  for (int i = 0; v == NULL && i < 2; i++, td = ReverseTrackdir(td)) {
1463  /* Only test the active signal side. */
1464  if (!HasSignalOnTrackdir(tile, ReverseTrackdir(td))) continue;
1465  TileIndex next = TileAddByDiagDir(tile, TrackdirToExitdir(td));
1467  if (HasReservedTracks(next, tracks)) {
1469  }
1470  }
1471  }
1472  Company::Get(GetTileOwner(tile))->infrastructure.signal -= CountBits(GetPresentSignals(tile));
1473  SetPresentSignals(tile, GetPresentSignals(tile) & ~SignalOnTrack(track));
1474  Company::Get(GetTileOwner(tile))->infrastructure.signal += CountBits(GetPresentSignals(tile));
1476 
1477  /* removed last signal from tile? */
1478  if (GetPresentSignals(tile) == 0) {
1479  SetSignalStates(tile, 0);
1480  SetHasSignals(tile, false);
1481  SetSignalVariant(tile, INVALID_TRACK, SIG_ELECTRIC); // remove any possible semaphores
1482  }
1483 
1484  AddTrackToSignalBuffer(tile, track, GetTileOwner(tile));
1485  YapfNotifyTrackLayoutChange(tile, track);
1486  if (v != NULL) TryPathReserve(v, false);
1487 
1488  MarkTileDirtyByTile(tile);
1489  }
1490 
1491  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_SIGNALS]);
1492 }
1493 
1512 CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1513 {
1514  return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
1515 }
1516 
1518 static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
1519 {
1520  if (v->type != VEH_TRAIN) return NULL;
1521 
1522  TrainList *affected_trains = static_cast<TrainList*>(data);
1523  affected_trains->Include(Train::From(v)->First());
1524 
1525  return NULL;
1526 }
1527 
1540 CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1541 {
1542  RailType totype = Extract<RailType, 0, 4>(p2);
1543  TileIndex area_start = p1;
1544  TileIndex area_end = tile;
1545  bool diagonal = HasBit(p2, 4);
1546 
1547  if (!ValParamRailtype(totype)) return CMD_ERROR;
1548  if (area_start >= MapSize()) return CMD_ERROR;
1549 
1550  TrainList affected_trains;
1551 
1553  CommandCost error = CommandCost(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK); // by default, there is no track to convert.
1554 
1555  TileIterator *iter = diagonal ? (TileIterator *)new DiagonalTileIterator(area_start, area_end) : new OrthogonalTileIterator(area_start, area_end);
1556  for (; (tile = *iter) != INVALID_TILE; ++(*iter)) {
1557  TileType tt = GetTileType(tile);
1558 
1559  /* Check if there is any track on tile */
1560  switch (tt) {
1561  case MP_RAILWAY:
1562  break;
1563  case MP_STATION:
1564  if (!HasStationRail(tile)) continue;
1565  break;
1566  case MP_ROAD:
1567  if (!IsLevelCrossing(tile)) continue;
1568  if (RailNoLevelCrossings(totype)) {
1569  error.MakeError(STR_ERROR_CROSSING_DISALLOWED);
1570  continue;
1571  }
1572  break;
1573  case MP_TUNNELBRIDGE:
1574  if (GetTunnelBridgeTransportType(tile) != TRANSPORT_RAIL) continue;
1575  break;
1576  default: continue;
1577  }
1578 
1579  /* Original railtype we are converting from */
1580  RailType type = GetRailType(tile);
1581 
1582  /* Converting to the same type or converting 'hidden' elrail -> rail */
1583  if (type == totype || (_settings_game.vehicle.disable_elrails && totype == RAILTYPE_RAIL && type == RAILTYPE_ELECTRIC)) continue;
1584 
1585  /* Trying to convert other's rail */
1586  CommandCost ret = CheckTileOwnership(tile);
1587  if (ret.Failed()) {
1588  error = ret;
1589  continue;
1590  }
1591 
1592  SmallVector<Train *, 2> vehicles_affected;
1593 
1594  /* Vehicle on the tile when not converting Rail <-> ElRail
1595  * Tunnels and bridges have special check later */
1596  if (tt != MP_TUNNELBRIDGE) {
1597  if (!IsCompatibleRail(type, totype)) {
1599  if (ret.Failed()) {
1600  error = ret;
1601  continue;
1602  }
1603  }
1604  if (flags & DC_EXEC) { // we can safely convert, too
1605  TrackBits reserved = GetReservedTrackbits(tile);
1606  Track track;
1607  while ((track = RemoveFirstTrack(&reserved)) != INVALID_TRACK) {
1608  Train *v = GetTrainForReservation(tile, track);
1609  if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1610  /* No power on new rail type, reroute. */
1612  *vehicles_affected.Append() = v;
1613  }
1614  }
1615 
1616  /* Update the company infrastructure counters. */
1617  if (!IsRailStationTile(tile) || !IsStationTileBlocked(tile)) {
1618  Company *c = Company::Get(GetTileOwner(tile));
1619  uint num_pieces = IsLevelCrossingTile(tile) ? LEVELCROSSING_TRACKBIT_FACTOR : 1;
1620  if (IsPlainRailTile(tile)) {
1621  TrackBits bits = GetTrackBits(tile);
1622  num_pieces = CountBits(bits);
1623  if (TracksOverlap(bits)) num_pieces *= num_pieces;
1624  }
1625  c->infrastructure.rail[type] -= num_pieces;
1626  c->infrastructure.rail[totype] += num_pieces;
1628  }
1629 
1630  SetRailType(tile, totype);
1631  MarkTileDirtyByTile(tile);
1632  /* update power of train on this tile */
1633  FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1634  }
1635  }
1636 
1637  switch (tt) {
1638  case MP_RAILWAY:
1639  switch (GetRailTileType(tile)) {
1640  case RAIL_TILE_DEPOT:
1641  if (flags & DC_EXEC) {
1642  /* notify YAPF about the track layout change */
1644 
1645  /* Update build vehicle window related to this depot */
1648  }
1649  cost.AddCost(RailConvertCost(type, totype));
1650  break;
1651 
1652  default: // RAIL_TILE_NORMAL, RAIL_TILE_SIGNALS
1653  if (flags & DC_EXEC) {
1654  /* notify YAPF about the track layout change */
1655  TrackBits tracks = GetTrackBits(tile);
1656  while (tracks != TRACK_BIT_NONE) {
1658  }
1659  }
1660  cost.AddCost(RailConvertCost(type, totype) * CountBits(GetTrackBits(tile)));
1661  break;
1662  }
1663  break;
1664 
1665  case MP_TUNNELBRIDGE: {
1666  TileIndex endtile = GetOtherTunnelBridgeEnd(tile);
1667 
1668  /* If both ends of tunnel/bridge are in the range, do not try to convert twice -
1669  * it would cause assert because of different test and exec runs */
1670  if (endtile < tile) {
1671  if (diagonal) {
1672  if (DiagonalTileArea(area_start, area_end).Contains(endtile)) continue;
1673  } else {
1674  if (OrthogonalTileArea(area_start, area_end).Contains(endtile)) continue;
1675  }
1676  }
1677 
1678  /* When not converting rail <-> el. rail, any vehicle cannot be in tunnel/bridge */
1679  if (!IsCompatibleRail(GetRailType(tile), totype)) {
1680  CommandCost ret = TunnelBridgeIsFree(tile, endtile);
1681  if (ret.Failed()) {
1682  error = ret;
1683  continue;
1684  }
1685  }
1686 
1687  if (flags & DC_EXEC) {
1689  if (HasTunnelBridgeReservation(tile)) {
1690  Train *v = GetTrainForReservation(tile, track);
1691  if (v != NULL && !HasPowerOnRail(v->railtype, totype)) {
1692  /* No power on new rail type, reroute. */
1694  *vehicles_affected.Append() = v;
1695  }
1696  }
1697 
1698  /* Update the company infrastructure counters. */
1699  uint num_pieces = (GetTunnelBridgeLength(tile, endtile) + 2) * TUNNELBRIDGE_TRACKBIT_FACTOR;
1700  Company *c = Company::Get(GetTileOwner(tile));
1701  c->infrastructure.rail[GetRailType(tile)] -= num_pieces;
1702  c->infrastructure.rail[totype] += num_pieces;
1704 
1705  SetRailType(tile, totype);
1706  SetRailType(endtile, totype);
1707 
1708  FindVehicleOnPos(tile, &affected_trains, &UpdateTrainPowerProc);
1709  FindVehicleOnPos(endtile, &affected_trains, &UpdateTrainPowerProc);
1710 
1711  YapfNotifyTrackLayoutChange(tile, track);
1712  YapfNotifyTrackLayoutChange(endtile, track);
1713 
1714  if (IsBridge(tile)) {
1715  MarkBridgeDirty(tile);
1716  } else {
1717  MarkTileDirtyByTile(tile);
1718  MarkTileDirtyByTile(endtile);
1719  }
1720  }
1721 
1722  cost.AddCost((GetTunnelBridgeLength(tile, endtile) + 2) * RailConvertCost(type, totype));
1723  break;
1724  }
1725 
1726  default: // MP_STATION, MP_ROAD
1727  if (flags & DC_EXEC) {
1728  Track track = ((tt == MP_STATION) ? GetRailStationTrack(tile) : GetCrossingRailTrack(tile));
1729  YapfNotifyTrackLayoutChange(tile, track);
1730  }
1731 
1732  cost.AddCost(RailConvertCost(type, totype));
1733  break;
1734  }
1735 
1736  for (uint i = 0; i < vehicles_affected.Length(); ++i) {
1737  TryPathReserve(vehicles_affected[i], true);
1738  }
1739  }
1740 
1741  if (flags & DC_EXEC) {
1742  /* Railtype changed, update trains as when entering different track */
1743  for (Train **v = affected_trains.Begin(); v != affected_trains.End(); v++) {
1744  (*v)->ConsistChanged(CCF_TRACK);
1745  }
1746  }
1747 
1748  delete iter;
1749  return (cost.GetCost() == 0) ? error : cost;
1750 }
1751 
1752 static CommandCost RemoveTrainDepot(TileIndex tile, DoCommandFlag flags)
1753 {
1754  if (_current_company != OWNER_WATER) {
1755  CommandCost ret = CheckTileOwnership(tile);
1756  if (ret.Failed()) return ret;
1757  }
1758 
1760  if (ret.Failed()) return ret;
1761 
1762  if (flags & DC_EXEC) {
1763  /* read variables before the depot is removed */
1765  Owner owner = GetTileOwner(tile);
1766  Train *v = NULL;
1767 
1768  if (HasDepotReservation(tile)) {
1770  if (v != NULL) FreeTrainTrackReservation(v);
1771  }
1772 
1773  Company::Get(owner)->infrastructure.rail[GetRailType(tile)]--;
1775 
1776  delete Depot::GetByTile(tile);
1777  DoClearSquare(tile);
1778  AddSideToSignalBuffer(tile, dir, owner);
1780  if (v != NULL) TryPathReserve(v, true);
1781  }
1782 
1783  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_DEPOT_TRAIN]);
1784 }
1785 
1786 static CommandCost ClearTile_Track(TileIndex tile, DoCommandFlag flags)
1787 {
1789 
1790  if (flags & DC_AUTO) {
1791  if (!IsTileOwner(tile, _current_company)) {
1792  return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
1793  }
1794 
1795  if (IsPlainRail(tile)) {
1796  return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
1797  } else {
1798  return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
1799  }
1800  }
1801 
1802  switch (GetRailTileType(tile)) {
1803  case RAIL_TILE_SIGNALS:
1804  case RAIL_TILE_NORMAL: {
1805  Slope tileh = GetTileSlope(tile);
1806  /* Is there flat water on the lower halftile that gets cleared expensively? */
1807  bool water_ground = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh));
1808 
1809  TrackBits tracks = GetTrackBits(tile);
1810  while (tracks != TRACK_BIT_NONE) {
1811  Track track = RemoveFirstTrack(&tracks);
1812  CommandCost ret = DoCommand(tile, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
1813  if (ret.Failed()) return ret;
1814  cost.AddCost(ret);
1815  }
1816 
1817  /* When bankrupting, don't make water dirty, there could be a ship on lower halftile.
1818  * Same holds for non-companies clearing the tile, e.g. disasters. */
1819  if (water_ground && !(flags & DC_BANKRUPT) && Company::IsValidID(_current_company)) {
1821  if (ret.Failed()) return ret;
1822 
1823  /* The track was removed, and left a coast tile. Now also clear the water. */
1824  if (flags & DC_EXEC) DoClearSquare(tile);
1825  cost.AddCost(_price[PR_CLEAR_WATER]);
1826  }
1827 
1828  return cost;
1829  }
1830 
1831  case RAIL_TILE_DEPOT:
1832  return RemoveTrainDepot(tile, flags);
1833 
1834  default:
1835  return CMD_ERROR;
1836  }
1837 }
1838 
1843 static uint GetSaveSlopeZ(uint x, uint y, Track track)
1844 {
1845  switch (track) {
1846  case TRACK_UPPER: x &= ~0xF; y &= ~0xF; break;
1847  case TRACK_LOWER: x |= 0xF; y |= 0xF; break;
1848  case TRACK_LEFT: x |= 0xF; y &= ~0xF; break;
1849  case TRACK_RIGHT: x &= ~0xF; y |= 0xF; break;
1850  default: break;
1851  }
1852  return GetSlopePixelZ(x, y);
1853 }
1854 
1855 static void DrawSingleSignal(TileIndex tile, const RailtypeInfo *rti, Track track, SignalState condition, SignalOffsets image, uint pos)
1856 {
1857  bool side;
1859  case 0: side = false; break; // left
1860  case 2: side = true; break; // right
1861  default: side = _settings_game.vehicle.road_side != 0; break; // driving side
1862  }
1863  static const Point SignalPositions[2][12] = {
1864  { // Signals on the left side
1865  /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1866  { 8, 5}, {14, 1}, { 1, 14}, { 9, 11}, { 1, 0}, { 3, 10},
1867  /* LOWER LOWER X X Y Y */
1868  {11, 4}, {14, 14}, {11, 3}, { 4, 13}, { 3, 4}, {11, 13}
1869  }, { // Signals on the right side
1870  /* LEFT LEFT RIGHT RIGHT UPPER UPPER */
1871  {14, 1}, {12, 10}, { 4, 6}, { 1, 14}, {10, 4}, { 0, 1},
1872  /* LOWER LOWER X X Y Y */
1873  {14, 14}, { 5, 12}, {11, 13}, { 4, 3}, {13, 4}, { 3, 11}
1874  }
1875  };
1876 
1877  uint x = TileX(tile) * TILE_SIZE + SignalPositions[side][pos].x;
1878  uint y = TileY(tile) * TILE_SIZE + SignalPositions[side][pos].y;
1879 
1880  SignalType type = GetSignalType(tile, track);
1881  SignalVariant variant = GetSignalVariant(tile, track);
1882 
1883  SpriteID sprite = GetCustomSignalSprite(rti, tile, type, variant, condition);
1884  if (sprite != 0) {
1885  sprite += image;
1886  } else {
1887  /* Normal electric signals are stored in a different sprite block than all other signals. */
1888  sprite = (type == SIGTYPE_NORMAL && variant == SIG_ELECTRIC) ? SPR_ORIGINAL_SIGNALS_BASE : SPR_SIGNALS_BASE - 16;
1889  sprite += type * 16 + variant * 64 + image * 2 + condition + (type > SIGTYPE_LAST_NOPBS ? 64 : 0);
1890  }
1891 
1892  AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSaveSlopeZ(x, y, track));
1893 }
1894 
1895 static uint32 _drawtile_track_palette;
1896 
1897 
1898 
1900 struct FenceOffset {
1902  int x_offs;
1903  int y_offs;
1904  int x_size;
1905  int y_size;
1906 };
1907 
1910  { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_FLAT_X_NW
1911  { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_FLAT_Y_NE
1912  { CORNER_W, 8, 8, 1, 1 }, // RFO_FLAT_LEFT
1913  { CORNER_N, 8, 8, 1, 1 }, // RFO_FLAT_UPPER
1914  { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_SW_NW
1915  { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_SE_NE
1916  { CORNER_INVALID, 0, 1, 16, 1 }, // RFO_SLOPE_NE_NW
1917  { CORNER_INVALID, 1, 0, 1, 16 }, // RFO_SLOPE_NW_NE
1918  { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_FLAT_X_SE
1919  { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_FLAT_Y_SW
1920  { CORNER_E, 8, 8, 1, 1 }, // RFO_FLAT_RIGHT
1921  { CORNER_S, 8, 8, 1, 1 }, // RFO_FLAT_LOWER
1922  { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_SW_SE
1923  { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_SE_SW
1924  { CORNER_INVALID, 0, 15, 16, 1 }, // RFO_SLOPE_NE_SE
1925  { CORNER_INVALID, 15, 0, 1, 16 }, // RFO_SLOPE_NW_SW
1926 };
1927 
1935 static void DrawTrackFence(const TileInfo *ti, SpriteID base_image, uint num_sprites, RailFenceOffset rfo)
1936 {
1937  int z = ti->z;
1938  if (_fence_offsets[rfo].height_ref != CORNER_INVALID) {
1939  z += GetSlopePixelZInCorner(RemoveHalftileSlope(ti->tileh), _fence_offsets[rfo].height_ref);
1940  }
1941  AddSortableSpriteToDraw(base_image + (rfo % num_sprites), _drawtile_track_palette,
1942  ti->x + _fence_offsets[rfo].x_offs,
1943  ti->y + _fence_offsets[rfo].y_offs,
1944  _fence_offsets[rfo].x_size,
1945  _fence_offsets[rfo].y_size,
1946  4, z);
1947 }
1948 
1952 static void DrawTrackFence_NW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1953 {
1955  if (ti->tileh & SLOPE_NW) rfo = (ti->tileh & SLOPE_W) ? RFO_SLOPE_SW_NW : RFO_SLOPE_NE_NW;
1956  DrawTrackFence(ti, base_image, num_sprites, rfo);
1957 }
1958 
1962 static void DrawTrackFence_SE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1963 {
1965  if (ti->tileh & SLOPE_SE) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SW_SE : RFO_SLOPE_NE_SE;
1966  DrawTrackFence(ti, base_image, num_sprites, rfo);
1967 }
1968 
1972 static void DrawTrackFence_NE(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1973 {
1975  if (ti->tileh & SLOPE_NE) rfo = (ti->tileh & SLOPE_E) ? RFO_SLOPE_SE_NE : RFO_SLOPE_NW_NE;
1976  DrawTrackFence(ti, base_image, num_sprites, rfo);
1977 }
1978 
1982 static void DrawTrackFence_SW(const TileInfo *ti, SpriteID base_image, uint num_sprites)
1983 {
1985  if (ti->tileh & SLOPE_SW) rfo = (ti->tileh & SLOPE_S) ? RFO_SLOPE_SE_SW : RFO_SLOPE_NW_SW;
1986  DrawTrackFence(ti, base_image, num_sprites, rfo);
1987 }
1988 
1994 static void DrawTrackDetails(const TileInfo *ti, const RailtypeInfo *rti)
1995 {
1996  /* Base sprite for track fences.
1997  * Note: Halftile slopes only have fences on the upper part. */
1998  uint num_sprites = 0;
1999  SpriteID base_image = GetCustomRailSprite(rti, ti->tile, RTSG_FENCES, IsHalftileSlope(ti->tileh) ? TCX_UPPER_HALFTILE : TCX_NORMAL, &num_sprites);
2000  if (base_image == 0) {
2001  base_image = SPR_TRACK_FENCE_FLAT_X;
2002  num_sprites = 8;
2003  }
2004 
2005  assert(num_sprites > 0);
2006 
2007  switch (GetRailGroundType(ti->tile)) {
2008  case RAIL_GROUND_FENCE_NW: DrawTrackFence_NW(ti, base_image, num_sprites); break;
2009  case RAIL_GROUND_FENCE_SE: DrawTrackFence_SE(ti, base_image, num_sprites); break;
2010  case RAIL_GROUND_FENCE_SENW: DrawTrackFence_NW(ti, base_image, num_sprites);
2011  DrawTrackFence_SE(ti, base_image, num_sprites); break;
2012  case RAIL_GROUND_FENCE_NE: DrawTrackFence_NE(ti, base_image, num_sprites); break;
2013  case RAIL_GROUND_FENCE_SW: DrawTrackFence_SW(ti, base_image, num_sprites); break;
2014  case RAIL_GROUND_FENCE_NESW: DrawTrackFence_NE(ti, base_image, num_sprites);
2015  DrawTrackFence_SW(ti, base_image, num_sprites); break;
2016  case RAIL_GROUND_FENCE_VERT1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2017  case RAIL_GROUND_FENCE_VERT2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2018  case RAIL_GROUND_FENCE_HORIZ1: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2019  case RAIL_GROUND_FENCE_HORIZ2: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2020  case RAIL_GROUND_WATER: {
2021  Corner track_corner;
2022  if (IsHalftileSlope(ti->tileh)) {
2023  /* Steep slope or one-corner-raised slope with halftile foundation */
2024  track_corner = GetHalftileSlopeCorner(ti->tileh);
2025  } else {
2026  /* Three-corner-raised slope */
2028  }
2029  switch (track_corner) {
2030  case CORNER_W: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LEFT); break;
2031  case CORNER_S: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_LOWER); break;
2032  case CORNER_E: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_RIGHT); break;
2033  case CORNER_N: DrawTrackFence(ti, base_image, num_sprites, RFO_FLAT_UPPER); break;
2034  default: NOT_REACHED();
2035  }
2036  break;
2037  }
2038  default: break;
2039  }
2040 }
2041 
2042 /* SubSprite for drawing the track halftile of 'three-corners-raised'-sloped rail sprites. */
2043 static const int INF = 1000; // big number compared to tilesprite size
2044 static const SubSprite _halftile_sub_sprite[4] = {
2045  { -INF , -INF , 32 - 33, INF }, // CORNER_W, clip 33 pixels from right
2046  { -INF , 0 + 7, INF , INF }, // CORNER_S, clip 7 pixels from top
2047  { -31 + 33, -INF , INF , INF }, // CORNER_E, clip 33 pixels from left
2048  { -INF , -INF , INF , 30 - 23 } // CORNER_N, clip 23 pixels from bottom
2049 };
2050 
2051 static inline void DrawTrackSprite(SpriteID sprite, PaletteID pal, const TileInfo *ti, Slope s)
2052 {
2053  DrawGroundSprite(sprite, pal, NULL, 0, (ti->tileh & s) ? -8 : 0);
2054 }
2055 
2056 static void DrawTrackBitsOverlay(TileInfo *ti, TrackBits track, const RailtypeInfo *rti)
2057 {
2058  RailGroundType rgt = GetRailGroundType(ti->tile);
2059  Foundation f = GetRailFoundation(ti->tileh, track);
2060  Corner halftile_corner = CORNER_INVALID;
2061 
2062  if (IsNonContinuousFoundation(f)) {
2063  /* Save halftile corner */
2065  /* Draw lower part first */
2066  track &= ~CornerToTrackBits(halftile_corner);
2068  }
2069 
2070  DrawFoundation(ti, f);
2071  /* DrawFoundation modifies ti */
2072 
2073  /* Draw ground */
2074  if (rgt == RAIL_GROUND_WATER) {
2075  if (track != TRACK_BIT_NONE || IsSteepSlope(ti->tileh)) {
2076  /* three-corner-raised slope or steep slope with track on upper part */
2077  DrawShoreTile(ti->tileh);
2078  } else {
2079  /* single-corner-raised slope with track on upper part */
2080  DrawGroundSprite(SPR_FLAT_WATER_TILE, PAL_NONE);
2081  }
2082  } else {
2083  SpriteID image;
2084 
2085  switch (rgt) {
2086  case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2087  case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2088  default: image = SPR_FLAT_GRASS_TILE; break;
2089  }
2090 
2091  image += SlopeToSpriteOffset(ti->tileh);
2092 
2093  DrawGroundSprite(image, PAL_NONE);
2094  }
2095 
2096  SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2097  SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2099 
2100  if (track == TRACK_BIT_NONE) {
2101  /* Half-tile foundation, no track here? */
2102  } else if (ti->tileh == SLOPE_NW && track == TRACK_BIT_Y) {
2103  DrawGroundSprite(ground + RTO_SLOPE_NW, PAL_NONE);
2105  } else if (ti->tileh == SLOPE_NE && track == TRACK_BIT_X) {
2106  DrawGroundSprite(ground + RTO_SLOPE_NE, PAL_NONE);
2108  } else if (ti->tileh == SLOPE_SE && track == TRACK_BIT_Y) {
2109  DrawGroundSprite(ground + RTO_SLOPE_SE, PAL_NONE);
2111  } else if (ti->tileh == SLOPE_SW && track == TRACK_BIT_X) {
2112  DrawGroundSprite(ground + RTO_SLOPE_SW, PAL_NONE);
2114  } else {
2115  switch (track) {
2116  /* Draw single ground sprite when not overlapping. No track overlay
2117  * is necessary for these sprites. */
2118  case TRACK_BIT_X: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2119  case TRACK_BIT_Y: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2120  case TRACK_BIT_UPPER: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N); break;
2121  case TRACK_BIT_LOWER: DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2122  case TRACK_BIT_RIGHT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E); break;
2123  case TRACK_BIT_LEFT: DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2124  case TRACK_BIT_CROSS: DrawGroundSprite(ground + RTO_CROSSING_XY, PAL_NONE); break;
2125  case TRACK_BIT_HORZ: DrawTrackSprite(ground + RTO_N, PAL_NONE, ti, SLOPE_N);
2126  DrawTrackSprite(ground + RTO_S, PAL_NONE, ti, SLOPE_S); break;
2127  case TRACK_BIT_VERT: DrawTrackSprite(ground + RTO_E, PAL_NONE, ti, SLOPE_E);
2128  DrawTrackSprite(ground + RTO_W, PAL_NONE, ti, SLOPE_W); break;
2129 
2130  default:
2131  /* We're drawing a junction tile */
2132  if ((track & TRACK_BIT_3WAY_NE) == 0) {
2133  DrawGroundSprite(ground + RTO_JUNCTION_SW, PAL_NONE);
2134  } else if ((track & TRACK_BIT_3WAY_SW) == 0) {
2135  DrawGroundSprite(ground + RTO_JUNCTION_NE, PAL_NONE);
2136  } else if ((track & TRACK_BIT_3WAY_NW) == 0) {
2137  DrawGroundSprite(ground + RTO_JUNCTION_SE, PAL_NONE);
2138  } else if ((track & TRACK_BIT_3WAY_SE) == 0) {
2139  DrawGroundSprite(ground + RTO_JUNCTION_NW, PAL_NONE);
2140  } else {
2141  DrawGroundSprite(ground + RTO_JUNCTION_NSEW, PAL_NONE);
2142  }
2143 
2144  /* Mask out PBS bits as we shall draw them afterwards anyway. */
2145  track &= ~pbs;
2146 
2147  /* Draw regular track bits */
2148  if (track & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PAL_NONE);
2149  if (track & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PAL_NONE);
2150  if (track & TRACK_BIT_UPPER) DrawGroundSprite(overlay + RTO_N, PAL_NONE);
2151  if (track & TRACK_BIT_LOWER) DrawGroundSprite(overlay + RTO_S, PAL_NONE);
2152  if (track & TRACK_BIT_RIGHT) DrawGroundSprite(overlay + RTO_E, PAL_NONE);
2153  if (track & TRACK_BIT_LEFT) DrawGroundSprite(overlay + RTO_W, PAL_NONE);
2154  }
2155 
2156  /* Draw reserved track bits */
2157  if (pbs & TRACK_BIT_X) DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH);
2158  if (pbs & TRACK_BIT_Y) DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH);
2159  if (pbs & TRACK_BIT_UPPER) DrawTrackSprite(overlay + RTO_N, PALETTE_CRASH, ti, SLOPE_N);
2160  if (pbs & TRACK_BIT_LOWER) DrawTrackSprite(overlay + RTO_S, PALETTE_CRASH, ti, SLOPE_S);
2161  if (pbs & TRACK_BIT_RIGHT) DrawTrackSprite(overlay + RTO_E, PALETTE_CRASH, ti, SLOPE_E);
2162  if (pbs & TRACK_BIT_LEFT) DrawTrackSprite(overlay + RTO_W, PALETTE_CRASH, ti, SLOPE_W);
2163  }
2164 
2165  if (IsValidCorner(halftile_corner)) {
2166  DrawFoundation(ti, HalftileFoundation(halftile_corner));
2169 
2170  /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2171  Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2172 
2173  SpriteID image;
2174  switch (rgt) {
2175  case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2177  case RAIL_GROUND_HALF_SNOW: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2178  default: image = SPR_FLAT_GRASS_TILE; break;
2179  }
2180 
2181  image += SlopeToSpriteOffset(fake_slope);
2182 
2183  DrawGroundSprite(image, PAL_NONE, &(_halftile_sub_sprite[halftile_corner]));
2184 
2185  track = CornerToTrackBits(halftile_corner);
2186 
2187  int offset;
2188  switch (track) {
2189  default: NOT_REACHED();
2190  case TRACK_BIT_UPPER: offset = RTO_N; break;
2191  case TRACK_BIT_LOWER: offset = RTO_S; break;
2192  case TRACK_BIT_RIGHT: offset = RTO_E; break;
2193  case TRACK_BIT_LEFT: offset = RTO_W; break;
2194  }
2195 
2196  DrawTrackSprite(ground + offset, PAL_NONE, ti, fake_slope);
2198  DrawTrackSprite(overlay + offset, PALETTE_CRASH, ti, fake_slope);
2199  }
2200  }
2201 }
2202 
2208 static void DrawTrackBits(TileInfo *ti, TrackBits track)
2209 {
2210  const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2211 
2212  if (rti->UsesOverlay()) {
2213  DrawTrackBitsOverlay(ti, track, rti);
2214  return;
2215  }
2216 
2217  RailGroundType rgt = GetRailGroundType(ti->tile);
2218  Foundation f = GetRailFoundation(ti->tileh, track);
2219  Corner halftile_corner = CORNER_INVALID;
2220 
2221  if (IsNonContinuousFoundation(f)) {
2222  /* Save halftile corner */
2224  /* Draw lower part first */
2225  track &= ~CornerToTrackBits(halftile_corner);
2227  }
2228 
2229  DrawFoundation(ti, f);
2230  /* DrawFoundation modifies ti */
2231 
2232  SpriteID image;
2233  PaletteID pal = PAL_NONE;
2234  const SubSprite *sub = NULL;
2235  bool junction = false;
2236 
2237  /* Select the sprite to use. */
2238  if (track == 0) {
2239  /* Clear ground (only track on halftile foundation) */
2240  if (rgt == RAIL_GROUND_WATER) {
2241  if (IsSteepSlope(ti->tileh)) {
2242  DrawShoreTile(ti->tileh);
2243  image = 0;
2244  } else {
2245  image = SPR_FLAT_WATER_TILE;
2246  }
2247  } else {
2248  switch (rgt) {
2249  case RAIL_GROUND_BARREN: image = SPR_FLAT_BARE_LAND; break;
2250  case RAIL_GROUND_ICE_DESERT: image = SPR_FLAT_SNOW_DESERT_TILE; break;
2251  default: image = SPR_FLAT_GRASS_TILE; break;
2252  }
2253  image += SlopeToSpriteOffset(ti->tileh);
2254  }
2255  } else {
2256  if (ti->tileh != SLOPE_FLAT) {
2257  /* track on non-flat ground */
2258  image = _track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.track_y;
2259  } else {
2260  /* track on flat ground */
2261  (image = rti->base_sprites.track_y, track == TRACK_BIT_Y) ||
2262  (image++, track == TRACK_BIT_X) ||
2263  (image++, track == TRACK_BIT_UPPER) ||
2264  (image++, track == TRACK_BIT_LOWER) ||
2265  (image++, track == TRACK_BIT_RIGHT) ||
2266  (image++, track == TRACK_BIT_LEFT) ||
2267  (image++, track == TRACK_BIT_CROSS) ||
2268 
2269  (image = rti->base_sprites.track_ns, track == TRACK_BIT_HORZ) ||
2270  (image++, track == TRACK_BIT_VERT) ||
2271 
2272  (junction = true, false) ||
2273  (image = rti->base_sprites.ground, (track & TRACK_BIT_3WAY_NE) == 0) ||
2274  (image++, (track & TRACK_BIT_3WAY_SW) == 0) ||
2275  (image++, (track & TRACK_BIT_3WAY_NW) == 0) ||
2276  (image++, (track & TRACK_BIT_3WAY_SE) == 0) ||
2277  (image++, true);
2278  }
2279 
2280  switch (rgt) {
2281  case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2282  case RAIL_GROUND_ICE_DESERT: image += rti->snow_offset; break;
2283  case RAIL_GROUND_WATER: {
2284  /* three-corner-raised slope */
2285  DrawShoreTile(ti->tileh);
2287  sub = &(_halftile_sub_sprite[track_corner]);
2288  break;
2289  }
2290  default: break;
2291  }
2292  }
2293 
2294  if (image != 0) DrawGroundSprite(image, pal, sub);
2295 
2296  /* Draw track pieces individually for junction tiles */
2297  if (junction) {
2298  if (track & TRACK_BIT_X) DrawGroundSprite(rti->base_sprites.single_x, PAL_NONE);
2299  if (track & TRACK_BIT_Y) DrawGroundSprite(rti->base_sprites.single_y, PAL_NONE);
2300  if (track & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PAL_NONE);
2301  if (track & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PAL_NONE);
2302  if (track & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PAL_NONE);
2303  if (track & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PAL_NONE);
2304  }
2305 
2306  /* PBS debugging, draw reserved tracks darker */
2307  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation) {
2308  /* Get reservation, but mask track on halftile slope */
2309  TrackBits pbs = GetRailReservationTrackBits(ti->tile) & track;
2310  if (pbs & TRACK_BIT_X) {
2311  if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2313  } else {
2314  DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2315  }
2316  }
2317  if (pbs & TRACK_BIT_Y) {
2318  if (ti->tileh == SLOPE_FLAT || ti->tileh == SLOPE_ELEVATED) {
2320  } else {
2321  DrawGroundSprite(_track_sloped_sprites[ti->tileh - 1] + rti->base_sprites.single_sloped - 20, PALETTE_CRASH);
2322  }
2323  }
2324  if (pbs & TRACK_BIT_UPPER) DrawGroundSprite(rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_N ? -(int)TILE_HEIGHT : 0);
2325  if (pbs & TRACK_BIT_LOWER) DrawGroundSprite(rti->base_sprites.single_s, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_S ? -(int)TILE_HEIGHT : 0);
2326  if (pbs & TRACK_BIT_LEFT) DrawGroundSprite(rti->base_sprites.single_w, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_W ? -(int)TILE_HEIGHT : 0);
2327  if (pbs & TRACK_BIT_RIGHT) DrawGroundSprite(rti->base_sprites.single_e, PALETTE_CRASH, NULL, 0, ti->tileh & SLOPE_E ? -(int)TILE_HEIGHT : 0);
2328  }
2329 
2330  if (IsValidCorner(halftile_corner)) {
2331  DrawFoundation(ti, HalftileFoundation(halftile_corner));
2332 
2333  /* Draw higher halftile-overlay: Use the sloped sprites with three corners raised. They probably best fit the lightning. */
2334  Slope fake_slope = SlopeWithThreeCornersRaised(OppositeCorner(halftile_corner));
2335  image = _track_sloped_sprites[fake_slope - 1] + rti->base_sprites.track_y;
2336  pal = PAL_NONE;
2337  switch (rgt) {
2338  case RAIL_GROUND_BARREN: pal = PALETTE_TO_BARE_LAND; break;
2340  case RAIL_GROUND_HALF_SNOW: image += rti->snow_offset; break; // higher part has snow in this case too
2341  default: break;
2342  }
2343  DrawGroundSprite(image, pal, &(_halftile_sub_sprite[halftile_corner]));
2344 
2345  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasReservedTracks(ti->tile, CornerToTrackBits(halftile_corner))) {
2346  static const byte _corner_to_track_sprite[] = {3, 1, 2, 0};
2347  DrawGroundSprite(_corner_to_track_sprite[halftile_corner] + rti->base_sprites.single_n, PALETTE_CRASH, NULL, 0, -(int)TILE_HEIGHT);
2348  }
2349  }
2350 }
2351 
2352 static void DrawSignals(TileIndex tile, TrackBits rails, const RailtypeInfo *rti)
2353 {
2354 #define MAYBE_DRAW_SIGNAL(x, y, z, t) if (IsSignalPresent(tile, x)) DrawSingleSignal(tile, rti, t, GetSingleSignalState(tile, x), y, z)
2355 
2356  if (!(rails & TRACK_BIT_Y)) {
2357  if (!(rails & TRACK_BIT_X)) {
2358  if (rails & TRACK_BIT_LEFT) {
2359  MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTH, 0, TRACK_LEFT);
2360  MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTH, 1, TRACK_LEFT);
2361  }
2362  if (rails & TRACK_BIT_RIGHT) {
2363  MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_NORTH, 2, TRACK_RIGHT);
2364  MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_SOUTH, 3, TRACK_RIGHT);
2365  }
2366  if (rails & TRACK_BIT_UPPER) {
2367  MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_WEST, 4, TRACK_UPPER);
2368  MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_EAST, 5, TRACK_UPPER);
2369  }
2370  if (rails & TRACK_BIT_LOWER) {
2371  MAYBE_DRAW_SIGNAL(1, SIGNAL_TO_WEST, 6, TRACK_LOWER);
2372  MAYBE_DRAW_SIGNAL(0, SIGNAL_TO_EAST, 7, TRACK_LOWER);
2373  }
2374  } else {
2375  MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHWEST, 8, TRACK_X);
2376  MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHEAST, 9, TRACK_X);
2377  }
2378  } else {
2379  MAYBE_DRAW_SIGNAL(3, SIGNAL_TO_SOUTHEAST, 10, TRACK_Y);
2380  MAYBE_DRAW_SIGNAL(2, SIGNAL_TO_NORTHWEST, 11, TRACK_Y);
2381  }
2382 }
2383 
2384 static void DrawTile_Track(TileInfo *ti)
2385 {
2386  const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2387 
2388  _drawtile_track_palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
2389 
2390  if (IsPlainRail(ti->tile)) {
2391  TrackBits rails = GetTrackBits(ti->tile);
2392 
2393  DrawTrackBits(ti, rails);
2394 
2396 
2398 
2399  if (HasSignals(ti->tile)) DrawSignals(ti->tile, rails, rti);
2400  } else {
2401  /* draw depot */
2402  const DrawTileSprites *dts;
2403  PaletteID pal = PAL_NONE;
2404  SpriteID relocation;
2405 
2407 
2409  /* Draw rail instead of depot */
2410  dts = &_depot_invisible_gfx_table[GetRailDepotDirection(ti->tile)];
2411  } else {
2412  dts = &_depot_gfx_table[GetRailDepotDirection(ti->tile)];
2413  }
2414 
2415  SpriteID image;
2416  if (rti->UsesOverlay()) {
2417  image = SPR_FLAT_GRASS_TILE;
2418  } else {
2419  image = dts->ground.sprite;
2420  if (image != SPR_FLAT_GRASS_TILE) image += rti->GetRailtypeSpriteOffset();
2421  }
2422 
2423  /* adjust ground tile for desert
2424  * don't adjust for snow, because snow in depots looks weird */
2425  if (IsSnowRailGround(ti->tile) && _settings_game.game_creation.landscape == LT_TROPIC) {
2426  if (image != SPR_FLAT_GRASS_TILE) {
2427  image += rti->snow_offset; // tile with tracks
2428  } else {
2429  image = SPR_FLAT_SNOW_DESERT_TILE; // flat ground
2430  }
2431  }
2432 
2433  DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, _drawtile_track_palette));
2434 
2435  if (rti->UsesOverlay()) {
2436  SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2437 
2438  switch (GetRailDepotDirection(ti->tile)) {
2439  case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2440  case DIAGDIR_SW: DrawGroundSprite(ground + RTO_X, PAL_NONE); break;
2441  case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2442  case DIAGDIR_SE: DrawGroundSprite(ground + RTO_Y, PAL_NONE); break;
2443  default: break;
2444  }
2445 
2447  SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2448 
2449  switch (GetRailDepotDirection(ti->tile)) {
2450  case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2451  case DIAGDIR_SW: DrawGroundSprite(overlay + RTO_X, PALETTE_CRASH); break;
2452  case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2453  case DIAGDIR_SE: DrawGroundSprite(overlay + RTO_Y, PALETTE_CRASH); break;
2454  default: break;
2455  }
2456  }
2457  } else {
2458  /* PBS debugging, draw reserved tracks darker */
2459  if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasDepotReservation(ti->tile)) {
2460  switch (GetRailDepotDirection(ti->tile)) {
2461  case DIAGDIR_NE: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2463  case DIAGDIR_NW: if (!IsInvisibilitySet(TO_BUILDINGS)) break; // else FALL THROUGH
2465  default: break;
2466  }
2467  }
2468  }
2469  int depot_sprite = GetCustomRailSprite(rti, ti->tile, RTSG_DEPOT);
2470  relocation = depot_sprite != 0 ? depot_sprite - SPR_RAIL_DEPOT_SE_1 : rti->GetRailtypeSpriteOffset();
2471 
2473 
2474  DrawRailTileSeq(ti, dts, TO_BUILDINGS, relocation, 0, _drawtile_track_palette);
2475  }
2476  DrawBridgeMiddle(ti);
2477 }
2478 
2479 void DrawTrainDepotSprite(int x, int y, int dir, RailType railtype)
2480 {
2481  const DrawTileSprites *dts = &_depot_gfx_table[dir];
2482  const RailtypeInfo *rti = GetRailTypeInfo(railtype);
2483  SpriteID image = rti->UsesOverlay() ? SPR_FLAT_GRASS_TILE : dts->ground.sprite;
2484  uint32 offset = rti->GetRailtypeSpriteOffset();
2485 
2486  if (image != SPR_FLAT_GRASS_TILE) image += offset;
2487  PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
2488 
2489  DrawSprite(image, PAL_NONE, x, y);
2490 
2491  if (rti->UsesOverlay()) {
2493 
2494  switch (dir) {
2495  case DIAGDIR_SW: DrawSprite(ground + RTO_X, PAL_NONE, x, y); break;
2496  case DIAGDIR_SE: DrawSprite(ground + RTO_Y, PAL_NONE, x, y); break;
2497  default: break;
2498  }
2499  }
2500  int depot_sprite = GetCustomRailSprite(rti, INVALID_TILE, RTSG_DEPOT);
2501  if (depot_sprite != 0) offset = depot_sprite - SPR_RAIL_DEPOT_SE_1;
2502 
2503  DrawRailTileSeqInGUI(x, y, dts, offset, 0, palette);
2504 }
2505 
2506 static int GetSlopePixelZ_Track(TileIndex tile, uint x, uint y)
2507 {
2508  if (IsPlainRail(tile)) {
2509  int z;
2510  Slope tileh = GetTilePixelSlope(tile, &z);
2511  if (tileh == SLOPE_FLAT) return z;
2512 
2513  z += ApplyPixelFoundationToSlope(GetRailFoundation(tileh, GetTrackBits(tile)), &tileh);
2514  return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
2515  } else {
2516  return GetTileMaxPixelZ(tile);
2517  }
2518 }
2519 
2520 static Foundation GetFoundation_Track(TileIndex tile, Slope tileh)
2521 {
2522  return IsPlainRail(tile) ? GetRailFoundation(tileh, GetTrackBits(tile)) : FlatteningFoundation(tileh);
2523 }
2524 
2525 static void TileLoop_Track(TileIndex tile)
2526 {
2527  RailGroundType old_ground = GetRailGroundType(tile);
2528  RailGroundType new_ground;
2529 
2530  if (old_ground == RAIL_GROUND_WATER) {
2531  TileLoop_Water(tile);
2532  return;
2533  }
2534 
2536  case LT_ARCTIC: {
2537  int z;
2538  Slope slope = GetTileSlope(tile, &z);
2539  bool half = false;
2540 
2541  /* for non-flat track, use lower part of track
2542  * in other cases, use the highest part with track */
2543  if (IsPlainRail(tile)) {
2544  TrackBits track = GetTrackBits(tile);
2545  Foundation f = GetRailFoundation(slope, track);
2546 
2547  switch (f) {
2548  case FOUNDATION_NONE:
2549  /* no foundation - is the track on the upper side of three corners raised tile? */
2550  if (IsSlopeWithThreeCornersRaised(slope)) z++;
2551  break;
2552 
2553  case FOUNDATION_INCLINED_X:
2554  case FOUNDATION_INCLINED_Y:
2555  /* sloped track - is it on a steep slope? */
2556  if (IsSteepSlope(slope)) z++;
2557  break;
2558 
2560  /* only lower part of steep slope */
2561  z++;
2562  break;
2563 
2564  default:
2565  /* if it is a steep slope, then there is a track on higher part */
2566  if (IsSteepSlope(slope)) z++;
2567  z++;
2568  break;
2569  }
2570 
2572  } else {
2573  /* is the depot on a non-flat tile? */
2574  if (slope != SLOPE_FLAT) z++;
2575  }
2576 
2577  /* 'z' is now the lowest part of the highest track bit -
2578  * for sloped track, it is 'z' of lower part
2579  * for two track bits, it is 'z' of higher track bit
2580  * For non-continuous foundations (and STEEP_BOTH), 'half' is set */
2581  if (z > GetSnowLine()) {
2582  if (half && z - GetSnowLine() == 1) {
2583  /* track on non-continuous foundation, lower part is not under snow */
2584  new_ground = RAIL_GROUND_HALF_SNOW;
2585  } else {
2586  new_ground = RAIL_GROUND_ICE_DESERT;
2587  }
2588  goto set_ground;
2589  }
2590  break;
2591  }
2592 
2593  case LT_TROPIC:
2594  if (GetTropicZone(tile) == TROPICZONE_DESERT) {
2595  new_ground = RAIL_GROUND_ICE_DESERT;
2596  goto set_ground;
2597  }
2598  break;
2599  }
2600 
2601  new_ground = RAIL_GROUND_GRASS;
2602 
2603  if (IsPlainRail(tile) && old_ground != RAIL_GROUND_BARREN) { // wait until bottom is green
2604  /* determine direction of fence */
2605  TrackBits rail = GetTrackBits(tile);
2606 
2607  Owner owner = GetTileOwner(tile);
2608  byte fences = 0;
2609 
2610  for (DiagDirection d = DIAGDIR_BEGIN; d < DIAGDIR_END; d++) {
2611  static const TrackBits dir_to_trackbits[DIAGDIR_END] = {TRACK_BIT_3WAY_NE, TRACK_BIT_3WAY_SE, TRACK_BIT_3WAY_SW, TRACK_BIT_3WAY_NW};
2612 
2613  /* Track bit on this edge => no fence. */
2614  if ((rail & dir_to_trackbits[d]) != TRACK_BIT_NONE) continue;
2615 
2616  TileIndex tile2 = tile + TileOffsByDiagDir(d);
2617 
2618  /* Show fences if it's a house, industry, object, road, tunnelbridge or not owned by us. */
2619  if (!IsValidTile(tile2) || IsTileType(tile2, MP_HOUSE) || IsTileType(tile2, MP_INDUSTRY) ||
2620  IsTileType(tile2, MP_ROAD) || (IsTileType(tile2, MP_OBJECT) && !IsObjectType(tile2, OBJECT_OWNED_LAND)) || IsTileType(tile2, MP_TUNNELBRIDGE) || !IsTileOwner(tile2, owner)) {
2621  fences |= 1 << d;
2622  }
2623  }
2624 
2625  switch (fences) {
2626  case 0: break;
2627  case (1 << DIAGDIR_NE): new_ground = RAIL_GROUND_FENCE_NE; break;
2628  case (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_SE; break;
2629  case (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_SW; break;
2630  case (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_NW; break;
2631  case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_NESW; break;
2632  case (1 << DIAGDIR_SE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_SENW; break;
2633  case (1 << DIAGDIR_NE) | (1 << DIAGDIR_SE): new_ground = RAIL_GROUND_FENCE_VERT1; break;
2634  case (1 << DIAGDIR_NE) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_HORIZ2; break;
2635  case (1 << DIAGDIR_SE) | (1 << DIAGDIR_SW): new_ground = RAIL_GROUND_FENCE_HORIZ1; break;
2636  case (1 << DIAGDIR_SW) | (1 << DIAGDIR_NW): new_ground = RAIL_GROUND_FENCE_VERT2; break;
2637  default: NOT_REACHED();
2638  }
2639  }
2640 
2641 set_ground:
2642  if (old_ground != new_ground) {
2643  SetRailGroundType(tile, new_ground);
2644  MarkTileDirtyByTile(tile);
2645  }
2646 }
2647 
2648 
2649 static TrackStatus GetTileTrackStatus_Track(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
2650 {
2651  /* Case of half tile slope with water. */
2652  if (mode == TRANSPORT_WATER && IsPlainRail(tile) && GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
2653  TrackBits tb = GetTrackBits(tile);
2654  switch (tb) {
2655  default: NOT_REACHED();
2656  case TRACK_BIT_UPPER: tb = TRACK_BIT_LOWER; break;
2657  case TRACK_BIT_LOWER: tb = TRACK_BIT_UPPER; break;
2658  case TRACK_BIT_LEFT: tb = TRACK_BIT_RIGHT; break;
2659  case TRACK_BIT_RIGHT: tb = TRACK_BIT_LEFT; break;
2660  }
2662  }
2663 
2664  if (mode != TRANSPORT_RAIL) return 0;
2665 
2666  TrackBits trackbits = TRACK_BIT_NONE;
2667  TrackdirBits red_signals = TRACKDIR_BIT_NONE;
2668 
2669  switch (GetRailTileType(tile)) {
2670  default: NOT_REACHED();
2671  case RAIL_TILE_NORMAL:
2672  trackbits = GetTrackBits(tile);
2673  break;
2674 
2675  case RAIL_TILE_SIGNALS: {
2676  trackbits = GetTrackBits(tile);
2677  byte a = GetPresentSignals(tile);
2678  uint b = GetSignalStates(tile);
2679 
2680  b &= a;
2681 
2682  /* When signals are not present (in neither direction),
2683  * we pretend them to be green. Otherwise, it depends on
2684  * the signal type. For signals that are only active from
2685  * one side, we set the missing signals explicitly to
2686  * `green'. Otherwise, they implicitly become `red'. */
2687  if (!IsOnewaySignal(tile, TRACK_UPPER) || (a & SignalOnTrack(TRACK_UPPER)) == 0) b |= ~a & SignalOnTrack(TRACK_UPPER);
2688  if (!IsOnewaySignal(tile, TRACK_LOWER) || (a & SignalOnTrack(TRACK_LOWER)) == 0) b |= ~a & SignalOnTrack(TRACK_LOWER);
2689 
2690  if ((b & 0x8) == 0) red_signals |= (TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_X_NE | TRACKDIR_BIT_Y_SE | TRACKDIR_BIT_UPPER_E);
2691  if ((b & 0x4) == 0) red_signals |= (TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_Y_NW | TRACKDIR_BIT_UPPER_W);
2692  if ((b & 0x2) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_E);
2693  if ((b & 0x1) == 0) red_signals |= (TRACKDIR_BIT_RIGHT_S | TRACKDIR_BIT_LOWER_W);
2694 
2695  break;
2696  }
2697 
2698  case RAIL_TILE_DEPOT: {
2700 
2701  if (side != INVALID_DIAGDIR && side != dir) break;
2702 
2703  trackbits = DiagDirToDiagTrackBits(dir);
2704  break;
2705  }
2706  }
2707 
2708  return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), red_signals);
2709 }
2710 
2711 static bool ClickTile_Track(TileIndex tile)
2712 {
2713  if (!IsRailDepot(tile)) return false;
2714 
2715  ShowDepotWindow(tile, VEH_TRAIN);
2716  return true;
2717 }
2718 
2719 static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
2720 {
2721  const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
2722  td->rail_speed = rti->max_speed;
2723  td->owner[0] = GetTileOwner(tile);
2724  SetDParamX(td->dparam, 0, rti->strings.name);
2725  switch (GetRailTileType(tile)) {
2726  case RAIL_TILE_NORMAL:
2727  td->str = STR_LAI_RAIL_DESCRIPTION_TRACK;
2728  break;
2729 
2730  case RAIL_TILE_SIGNALS: {
2731  static const StringID signal_type[6][6] = {
2732  {
2733  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_SIGNALS,
2734  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2735  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2736  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2737  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2738  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS
2739  },
2740  {
2741  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PRESIGNALS,
2742  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRESIGNALS,
2743  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2744  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2745  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2746  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS
2747  },
2748  {
2749  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_EXITSIGNALS,
2750  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_EXITSIGNALS,
2751  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXITSIGNALS,
2752  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2753  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2754  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS
2755  },
2756  {
2757  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_COMBOSIGNALS,
2758  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_COMBOSIGNALS,
2759  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_COMBOSIGNALS,
2760  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBOSIGNALS,
2761  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2762  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS
2763  },
2764  {
2765  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_PBSSIGNALS,
2766  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_PBSSIGNALS,
2767  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_PBSSIGNALS,
2768  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_PBSSIGNALS,
2769  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBSSIGNALS,
2770  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS
2771  },
2772  {
2773  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NORMAL_NOENTRYSIGNALS,
2774  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PRE_NOENTRYSIGNALS,
2775  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_EXIT_NOENTRYSIGNALS,
2776  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_COMBO_NOENTRYSIGNALS,
2777  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_PBS_NOENTRYSIGNALS,
2778  STR_LAI_RAIL_DESCRIPTION_TRACK_WITH_NOENTRYSIGNALS
2779  }
2780  };
2781 
2782  SignalType primary_signal;
2783  SignalType secondary_signal;
2784  if (HasSignalOnTrack(tile, TRACK_UPPER)) {
2785  primary_signal = GetSignalType(tile, TRACK_UPPER);
2786  secondary_signal = HasSignalOnTrack(tile, TRACK_LOWER) ? GetSignalType(tile, TRACK_LOWER) : primary_signal;
2787  } else {
2788  secondary_signal = primary_signal = GetSignalType(tile, TRACK_LOWER);
2789  }
2790 
2791  td->str = signal_type[secondary_signal][primary_signal];
2792  break;
2793  }
2794 
2795  case RAIL_TILE_DEPOT:
2796  td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
2797  if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
2798  if (td->rail_speed > 0) {
2799  td->rail_speed = min(td->rail_speed, 61);
2800  } else {
2801  td->rail_speed = 61;
2802  }
2803  }
2804  td->build_date = Depot::GetByTile(tile)->build_date;
2805  break;
2806 
2807  default:
2808  NOT_REACHED();
2809  }
2810 }
2811 
2812 static void ChangeTileOwner_Track(TileIndex tile, Owner old_owner, Owner new_owner)
2813 {
2814  if (!IsTileOwner(tile, old_owner)) return;
2815 
2816  if (new_owner != INVALID_OWNER) {
2817  /* Update company infrastructure counts. No need to dirty windows here, we'll redraw the whole screen anyway. */
2818  uint num_pieces = 1;
2819  if (IsPlainRail(tile)) {
2820  TrackBits bits = GetTrackBits(tile);
2821  num_pieces = CountBits(bits);
2822  if (TracksOverlap(bits)) num_pieces *= num_pieces;
2823  }
2824  RailType rt = GetRailType(tile);
2825  Company::Get(old_owner)->infrastructure.rail[rt] -= num_pieces;
2826  Company::Get(new_owner)->infrastructure.rail[rt] += num_pieces;
2827 
2828  if (HasSignals(tile)) {
2829  uint num_sigs = CountBits(GetPresentSignals(tile));
2830  Company::Get(old_owner)->infrastructure.signal -= num_sigs;
2831  Company::Get(new_owner)->infrastructure.signal += num_sigs;
2832  }
2833 
2834  SetTileOwner(tile, new_owner);
2835  } else {
2836  DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
2837  }
2838 }
2839 
2840 static const byte _fractcoords_behind[4] = { 0x8F, 0x8, 0x80, 0xF8 };
2841 static const byte _fractcoords_enter[4] = { 0x8A, 0x48, 0x84, 0xA8 };
2842 static const int8 _deltacoord_leaveoffset[8] = {
2843  -1, 0, 1, 0, /* x */
2844  0, 1, 0, -1 /* y */
2845 };
2846 
2847 
2855 {
2857  int length = v->CalcNextVehicleOffset();
2858 
2859  switch (dir) {
2860  case DIAGDIR_NE: return ((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) - (length + 1)));
2861  case DIAGDIR_SE: return -((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) + (length + 1)));
2862  case DIAGDIR_SW: return -((int)(v->x_pos & 0x0F) - ((_fractcoords_enter[dir] & 0x0F) + (length + 1)));
2863  default:
2864  case DIAGDIR_NW: return ((int)(v->y_pos & 0x0F) - ((_fractcoords_enter[dir] >> 4) - (length + 1)));
2865  }
2866 
2867  return 0; // make compilers happy
2868 }
2869 
2875 {
2876  /* this routine applies only to trains in depot tiles */
2877  if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
2878 
2879  Train *v = Train::From(u);
2880 
2881  /* depot direction */
2883 
2884  /* Calculate the point where the following wagon should be activated. */
2885  int length = v->CalcNextVehicleOffset();
2886 
2887  byte fract_coord_leave =
2888  ((_fractcoords_enter[dir] & 0x0F) + // x
2889  (length + 1) * _deltacoord_leaveoffset[dir]) +
2890  (((_fractcoords_enter[dir] >> 4) + // y
2891  ((length + 1) * _deltacoord_leaveoffset[dir + 4])) << 4);
2892 
2893  byte fract_coord = (x & 0xF) + ((y & 0xF) << 4);
2894 
2895  if (_fractcoords_behind[dir] == fract_coord) {
2896  /* make sure a train is not entering the tile from behind */
2897  return VETSB_CANNOT_ENTER;
2898  } else if (_fractcoords_enter[dir] == fract_coord) {
2899  if (DiagDirToDir(ReverseDiagDir(dir)) == v->direction) {
2900  /* enter the depot */
2901  v->track = TRACK_BIT_DEPOT,
2902  v->vehstatus |= VS_HIDDEN; // hide it
2903  v->direction = ReverseDir(v->direction);
2904  if (v->Next() == NULL) VehicleEnterDepot(v->First());
2905  v->tile = tile;
2906 
2908  return VETSB_ENTERED_WORMHOLE;
2909  }
2910  } else if (fract_coord_leave == fract_coord) {
2911  if (DiagDirToDir(dir) == v->direction) {
2912  /* leave the depot? */
2913  if ((v = v->Next()) != NULL) {
2914  v->vehstatus &= ~VS_HIDDEN;
2915  v->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
2916  }
2917  }
2918  }
2919 
2920  return VETSB_CONTINUE;
2921 }
2922 
2934 static CommandCost TestAutoslopeOnRailTile(TileIndex tile, uint flags, int z_old, Slope tileh_old, int z_new, Slope tileh_new, TrackBits rail_bits)
2935 {
2936  if (!_settings_game.construction.build_on_slopes || !AutoslopeEnabled()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2937 
2938  /* Is the slope-rail_bits combination valid in general? I.e. is it safe to call GetRailFoundation() ? */
2939  if (CheckRailSlope(tileh_new, rail_bits, TRACK_BIT_NONE, tile).Failed()) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2940 
2941  /* Get the slopes on top of the foundations */
2942  z_old += ApplyFoundationToSlope(GetRailFoundation(tileh_old, rail_bits), &tileh_old);
2943  z_new += ApplyFoundationToSlope(GetRailFoundation(tileh_new, rail_bits), &tileh_new);
2944 
2945  Corner track_corner;
2946  switch (rail_bits) {
2947  case TRACK_BIT_LEFT: track_corner = CORNER_W; break;
2948  case TRACK_BIT_LOWER: track_corner = CORNER_S; break;
2949  case TRACK_BIT_RIGHT: track_corner = CORNER_E; break;
2950  case TRACK_BIT_UPPER: track_corner = CORNER_N; break;
2951 
2952  /* Surface slope must not be changed */
2953  default:
2954  if (z_old != z_new || tileh_old != tileh_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2955  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2956  }
2957 
2958  /* The height of the track_corner must not be changed. The rest ensures GetRailFoundation() already. */
2959  z_old += GetSlopeZInCorner(RemoveHalftileSlope(tileh_old), track_corner);
2960  z_new += GetSlopeZInCorner(RemoveHalftileSlope(tileh_new), track_corner);
2961  if (z_old != z_new) return_cmd_error(STR_ERROR_MUST_REMOVE_RAILROAD_TRACK);
2962 
2963  CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
2964  /* Make the ground dirty, if surface slope has changed */
2965  if (tileh_old != tileh_new) {
2966  /* If there is flat water on the lower halftile add the cost for clearing it */
2967  if (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old)) cost.AddCost(_price[PR_CLEAR_WATER]);
2968  if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
2969  }
2970  return cost;
2971 }
2972 
2976 static Vehicle *EnsureNoShipProc(Vehicle *v, void *data)
2977 {
2978  return v->type == VEH_SHIP ? v : NULL;
2979 }
2980 
2981 static CommandCost TerraformTile_Track(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
2982 {
2983  int z_old;
2984  Slope tileh_old = GetTileSlope(tile, &z_old);
2985  if (IsPlainRail(tile)) {
2986  TrackBits rail_bits = GetTrackBits(tile);
2987  /* Is there flat water on the lower halftile that must be cleared expensively? */
2988  bool was_water = (GetRailGroundType(tile) == RAIL_GROUND_WATER && IsSlopeWithOneCornerRaised(tileh_old));
2989 
2990  /* Allow clearing the water only if there is no ship */
2991  if (was_water && HasVehicleOnPos(tile, NULL, &EnsureNoShipProc)) return_cmd_error(STR_ERROR_SHIP_IN_THE_WAY);
2992 
2993  /* First test autoslope. However if it succeeds we still have to test the rest, because non-autoslope terraforming is cheaper. */
2994  CommandCost autoslope_result = TestAutoslopeOnRailTile(tile, flags, z_old, tileh_old, z_new, tileh_new, rail_bits);
2995 
2996  /* When there is only a single horizontal/vertical track, one corner can be terraformed. */
2997  Corner allowed_corner;
2998  switch (rail_bits) {
2999  case TRACK_BIT_RIGHT: allowed_corner = CORNER_W; break;
3000  case TRACK_BIT_UPPER: allowed_corner = CORNER_S; break;
3001  case TRACK_BIT_LEFT: allowed_corner = CORNER_E; break;
3002  case TRACK_BIT_LOWER: allowed_corner = CORNER_N; break;
3003  default: return autoslope_result;
3004  }
3005 
3006  Foundation f_old = GetRailFoundation(tileh_old, rail_bits);
3007 
3008  /* Do not allow terraforming if allowed_corner is part of anti-zig-zag foundations */
3009  if (tileh_old != SLOPE_NS && tileh_old != SLOPE_EW && IsSpecialRailFoundation(f_old)) return autoslope_result;
3010 
3011  /* Everything is valid, which only changes allowed_corner */
3012  for (Corner corner = (Corner)0; corner < CORNER_END; corner = (Corner)(corner + 1)) {
3013  if (allowed_corner == corner) continue;
3014  if (z_old + GetSlopeZInCorner(tileh_old, corner) != z_new + GetSlopeZInCorner(tileh_new, corner)) return autoslope_result;
3015  }
3016 
3017  /* Make the ground dirty */
3018  if ((flags & DC_EXEC) != 0) SetRailGroundType(tile, RAIL_GROUND_BARREN);
3019 
3020  /* allow terraforming */
3021  return CommandCost(EXPENSES_CONSTRUCTION, was_water ? _price[PR_CLEAR_WATER] : (Money)0);
3023  AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetRailDepotDirection(tile))) {
3024  return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
3025  }
3026  return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
3027 }
3028 
3029 
3030 extern const TileTypeProcs _tile_type_rail_procs = {
3031  DrawTile_Track, // draw_tile_proc
3032  GetSlopePixelZ_Track, // get_slope_z_proc
3033  ClearTile_Track, // clear_tile_proc
3034  NULL, // add_accepted_cargo_proc
3035  GetTileDesc_Track, // get_tile_desc_proc
3036  GetTileTrackStatus_Track, // get_tile_track_status_proc
3037  ClickTile_Track, // click_tile_proc
3038  NULL, // animate_tile_proc
3039  TileLoop_Track, // tile_loop_proc
3040  ChangeTileOwner_Track, // change_tile_owner_proc
3041  NULL, // add_produced_cargo_proc
3042  VehicleEnter_Track, // vehicle_enter_tile_proc
3043  GetFoundation_Track, // get_foundation_proc
3044  TerraformTile_Track, // terraform_tile_proc
3045 };