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