Feature: Multi-track level crossings (#9931)
[openttd-github.git] / src / train_cmd.cpp
blobe5789d807f106ea8309b6aad3bdc35271224dea5
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file train_cmd.cpp Handling of trains. */
10 #include "stdafx.h"
11 #include "error.h"
12 #include "articulated_vehicles.h"
13 #include "command_func.h"
14 #include "pathfinder/npf/npf_func.h"
15 #include "pathfinder/yapf/yapf.hpp"
16 #include "news_func.h"
17 #include "company_func.h"
18 #include "newgrf_sound.h"
19 #include "newgrf_text.h"
20 #include "strings_func.h"
21 #include "viewport_func.h"
22 #include "vehicle_func.h"
23 #include "sound_func.h"
24 #include "ai/ai.hpp"
25 #include "game/game.hpp"
26 #include "newgrf_station.h"
27 #include "effectvehicle_func.h"
28 #include "network/network.h"
29 #include "spritecache.h"
30 #include "core/random_func.hpp"
31 #include "company_base.h"
32 #include "newgrf.h"
33 #include "order_backup.h"
34 #include "zoom_func.h"
35 #include "newgrf_debug.h"
36 #include "framerate_type.h"
37 #include "train_cmd.h"
38 #include "misc_cmd.h"
40 #include "table/strings.h"
41 #include "table/train_sprites.h"
43 #include "safeguards.h"
45 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
46 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
47 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
48 static TileIndex TrainApproachingCrossingTile(const Train *v);
49 static void CheckIfTrainNeedsService(Train *v);
50 static void CheckNextTrainTile(Train *v);
52 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
53 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
55 template <>
56 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
58 return image_index < lengthof(_engine_sprite_base);
62 /**
63 * Return the cargo weight multiplier to use for a rail vehicle
64 * @param cargo Cargo type to get multiplier for
65 * @return Cargo weight multiplier
67 byte FreightWagonMult(CargoID cargo)
69 if (!CargoSpec::Get(cargo)->is_freight) return 1;
70 return _settings_game.vehicle.freight_trains;
73 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
74 void CheckTrainsLengths()
76 bool first = true;
78 for (const Train *v : Train::Iterate()) {
79 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
80 for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
81 if (u->track != TRACK_BIT_DEPOT) {
82 if ((w->track != TRACK_BIT_DEPOT &&
83 std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
84 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
85 SetDParam(0, v->index);
86 SetDParam(1, v->owner);
87 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
89 if (!_networking && first) {
90 first = false;
91 Command<CMD_PAUSE>::Post(PM_PAUSED_ERROR, true);
93 /* Break so we warn only once for each train. */
94 break;
103 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
104 * to/removed from the chain, and when the game is loaded.
105 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
106 * @param allowed_changes Stuff that is allowed to change.
108 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
110 uint16 max_speed = UINT16_MAX;
112 assert(this->IsFrontEngine() || this->IsFreeWagon());
114 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
115 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
116 this->gcache.cached_total_length = 0;
117 this->compatible_railtypes = RAILTYPES_NONE;
119 bool train_can_tilt = true;
120 int min_curve_speed_mod = INT_MAX;
122 for (Train *u = this; u != nullptr; u = u->Next()) {
123 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
125 /* Check the this->first cache. */
126 assert(u->First() == this);
128 /* update the 'first engine' */
129 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
130 u->railtype = rvi_u->railtype;
132 if (u->IsEngine()) first_engine = u->engine_type;
134 /* Set user defined data to its default value */
135 u->tcache.user_def_data = rvi_u->user_def_data;
136 this->InvalidateNewGRFCache();
137 u->InvalidateNewGRFCache();
140 for (Train *u = this; u != nullptr; u = u->Next()) {
141 /* Update user defined data (must be done before other properties) */
142 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
143 this->InvalidateNewGRFCache();
144 u->InvalidateNewGRFCache();
147 for (Train *u = this; u != nullptr; u = u->Next()) {
148 const Engine *e_u = u->GetEngine();
149 const RailVehicleInfo *rvi_u = &e_u->u.rail;
151 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
152 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
154 /* Cache wagon override sprite group. nullptr is returned if there is none */
155 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
157 /* Reset colour map */
158 u->colourmap = PAL_NONE;
160 /* Update powered-wagon-status and visual effect */
161 u->UpdateVisualEffect(true);
163 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
164 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
165 /* wagon is powered */
166 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
167 } else {
168 ClrBit(u->flags, VRF_POWEREDWAGON);
171 if (!u->IsArticulatedPart()) {
172 /* Do not count powered wagons for the compatible railtypes, as wagons always
173 have railtype normal */
174 if (rvi_u->power > 0) {
175 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
178 /* Some electric engines can be allowed to run on normal rail. It happens to all
179 * existing electric engines when elrails are disabled and then re-enabled */
180 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
181 u->railtype = RAILTYPE_RAIL;
182 u->compatible_railtypes |= RAILTYPES_RAIL;
185 /* max speed is the minimum of the speed limits of all vehicles in the consist */
186 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
187 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
188 if (speed != 0) max_speed = std::min(speed, max_speed);
192 uint16 new_cap = e_u->DetermineCapacity(u);
193 if (allowed_changes & CCF_CAPACITY) {
194 /* Update vehicle capacity. */
195 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
196 u->refit_cap = std::min(new_cap, u->refit_cap);
197 u->cargo_cap = new_cap;
198 } else {
199 /* Verify capacity hasn't changed. */
200 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
202 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
204 /* check the vehicle length (callback) */
205 uint16 veh_len = CALLBACK_FAILED;
206 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
207 /* Use callback 36 */
208 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
210 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
211 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
213 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
214 /* Use callback 11 */
215 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
217 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
218 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
220 if (allowed_changes & CCF_LENGTH) {
221 /* Update vehicle length. */
222 u->gcache.cached_veh_length = veh_len;
223 } else {
224 /* Verify length hasn't changed. */
225 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
228 this->gcache.cached_total_length += u->gcache.cached_veh_length;
229 this->InvalidateNewGRFCache();
230 u->InvalidateNewGRFCache();
233 /* store consist weight/max speed in cache */
234 this->vcache.cached_max_speed = max_speed;
235 this->tcache.cached_tilt = train_can_tilt;
236 this->tcache.cached_curve_speed_mod = min_curve_speed_mod;
237 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
239 /* recalculate cached weights and power too (we do this *after* the rest, so it is known which wagons are powered and need extra weight added) */
240 this->CargoChanged();
242 if (this->IsFrontEngine()) {
243 this->UpdateAcceleration();
244 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
245 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
246 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
247 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
252 * Get the stop location of (the center) of the front vehicle of a train at
253 * a platform of a station.
254 * @param station_id the ID of the station where we're stopping
255 * @param tile the tile where the vehicle currently is
256 * @param v the vehicle to get the stop location of
257 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
258 * @param station_length 'return' the station length in 1/16th tiles
259 * @return the location, calculated from the begin of the station to stop at.
261 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
263 const Station *st = Station::Get(station_id);
264 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
265 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
267 /* Default to the middle of the station for stations stops that are not in
268 * the order list like intermediate stations when non-stop is disabled */
269 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
270 if (v->gcache.cached_total_length >= *station_length) {
271 /* The train is longer than the station, make it stop at the far end of the platform */
272 osl = OSL_PLATFORM_FAR_END;
273 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
274 osl = v->current_order.GetStopLocation();
277 /* The stop location of the FRONT! of the train */
278 int stop;
279 switch (osl) {
280 default: NOT_REACHED();
282 case OSL_PLATFORM_NEAR_END:
283 stop = v->gcache.cached_total_length;
284 break;
286 case OSL_PLATFORM_MIDDLE:
287 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
288 break;
290 case OSL_PLATFORM_FAR_END:
291 stop = *station_length;
292 break;
295 /* Subtract half the front vehicle length of the train so we get the real
296 * stop location of the train. */
297 return stop - (v->gcache.cached_veh_length + 1) / 2;
302 * Computes train speed limit caused by curves
303 * @return imposed speed limit
305 int Train::GetCurveSpeedLimit() const
307 assert(this->First() == this);
309 static const int absolute_max_speed = UINT16_MAX;
310 int max_speed = absolute_max_speed;
312 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
314 int curvecount[2] = {0, 0};
316 /* first find the curve speed limit */
317 int numcurve = 0;
318 int sum = 0;
319 int pos = 0;
320 int lastpos = -1;
321 for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
322 Direction this_dir = u->direction;
323 Direction next_dir = u->Next()->direction;
325 DirDiff dirdiff = DirDifference(this_dir, next_dir);
326 if (dirdiff == DIRDIFF_SAME) continue;
328 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
329 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
330 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
331 if (lastpos != -1) {
332 numcurve++;
333 sum += pos - lastpos;
334 if (pos - lastpos == 1 && max_speed > 88) {
335 max_speed = 88;
338 lastpos = pos;
341 /* if we have a 90 degree turn, fix the speed limit to 60 */
342 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
343 max_speed = 61;
347 if (numcurve > 0 && max_speed > 88) {
348 if (curvecount[0] == 1 && curvecount[1] == 1) {
349 max_speed = absolute_max_speed;
350 } else {
351 sum /= numcurve;
352 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
356 if (max_speed != absolute_max_speed) {
357 /* Apply the current railtype's curve speed advantage */
358 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
359 max_speed += (max_speed / 2) * rti->curve_speed;
361 if (this->tcache.cached_tilt) {
362 /* Apply max_speed bonus of 20% for a tilting train */
363 max_speed += max_speed / 5;
366 /* Apply max_speed modifier (cached value is fixed-point binary with 8 fractional bits)
367 * and clamp the result to an acceptable range. */
368 max_speed += (max_speed * this->tcache.cached_curve_speed_mod) / 256;
369 max_speed = Clamp(max_speed, 2, absolute_max_speed);
372 return max_speed;
376 * Calculates the maximum speed of the vehicle under its current conditions.
377 * @return Maximum speed of the vehicle.
379 int Train::GetCurrentMaxSpeed() const
381 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
382 this->gcache.cached_max_track_speed :
383 this->tcache.cached_max_curve_speed;
385 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
386 StationID sid = GetStationIndex(this->tile);
387 if (this->current_order.ShouldStopAtStation(this, sid)) {
388 int station_ahead;
389 int station_length;
390 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
392 /* The distance to go is whatever is still ahead of the train minus the
393 * distance from the train's stop location to the end of the platform */
394 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
396 if (distance_to_go > 0) {
397 int st_max_speed = 120;
399 int delta_v = this->cur_speed / (distance_to_go + 1);
400 if (max_speed > (this->cur_speed - delta_v)) {
401 st_max_speed = this->cur_speed - (delta_v / 10);
404 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
405 max_speed = std::min(max_speed, st_max_speed);
410 for (const Train *u = this; u != nullptr; u = u->Next()) {
411 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
412 max_speed = std::min(max_speed, 61);
413 break;
416 /* Vehicle is on the middle part of a bridge. */
417 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
418 max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
422 max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
423 return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
426 /** Update acceleration of the train from the cached power and weight. */
427 void Train::UpdateAcceleration()
429 assert(this->IsFrontEngine() || this->IsFreeWagon());
431 uint power = this->gcache.cached_power;
432 uint weight = this->gcache.cached_weight;
433 assert(weight != 0);
434 this->acceleration = Clamp(power / weight * 4, 1, 255);
438 * Get the width of a train vehicle image in the GUI.
439 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
440 * @return Width in pixels
442 int Train::GetDisplayImageWidth(Point *offset) const
444 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
445 int vehicle_pitch = 0;
447 const Engine *e = this->GetEngine();
448 if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
449 reference_width = e->GetGRF()->traininfo_vehicle_width;
450 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
453 if (offset != nullptr) {
454 offset->x = ScaleGUITrad(reference_width) / 2;
455 offset->y = ScaleGUITrad(vehicle_pitch);
457 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
460 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
462 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
463 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
467 * Get the sprite to display the train.
468 * @param direction Direction of view/travel.
469 * @param image_type Visualisation context.
470 * @return Sprite to display.
472 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
474 uint8 spritenum = this->spritenum;
476 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
478 if (is_custom_sprite(spritenum)) {
479 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
480 if (result->IsValid()) return;
482 spritenum = this->GetEngine()->original_image_index;
485 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
486 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
488 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
490 result->Set(sprite);
493 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
495 const Engine *e = Engine::Get(engine);
496 Direction dir = rear_head ? DIR_E : DIR_W;
497 uint8 spritenum = e->u.rail.image_index;
499 if (is_custom_sprite(spritenum)) {
500 GetCustomVehicleIcon(engine, dir, image_type, result);
501 if (result->IsValid()) {
502 if (e->GetGRF() != nullptr) {
503 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
505 return;
508 spritenum = Engine::Get(engine)->original_image_index;
511 if (rear_head) spritenum++;
513 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
516 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
518 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
519 int yf = y;
520 int yr = y;
522 VehicleSpriteSeq seqf, seqr;
523 GetRailIcon(engine, false, yf, image_type, &seqf);
524 GetRailIcon(engine, true, yr, image_type, &seqr);
526 Rect rectf, rectr;
527 seqf.GetBounds(&rectf);
528 seqr.GetBounds(&rectr);
530 preferred_x = Clamp(preferred_x,
531 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
532 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
534 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
535 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
536 } else {
537 VehicleSpriteSeq seq;
538 GetRailIcon(engine, false, y, image_type, &seq);
540 Rect rect;
541 seq.GetBounds(&rect);
542 preferred_x = Clamp(preferred_x,
543 left - UnScaleGUI(rect.left),
544 right - UnScaleGUI(rect.right));
546 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
551 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
552 * @param engine The engine to get the sprite from.
553 * @param[out] width The width of the sprite.
554 * @param[out] height The height of the sprite.
555 * @param[out] xoffs Number of pixels to shift the sprite to the right.
556 * @param[out] yoffs Number of pixels to shift the sprite downwards.
557 * @param image_type Context the sprite is used in.
559 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
561 int y = 0;
563 VehicleSpriteSeq seq;
564 GetRailIcon(engine, false, y, image_type, &seq);
566 Rect rect;
567 seq.GetBounds(&rect);
569 width = UnScaleGUI(rect.right - rect.left + 1);
570 height = UnScaleGUI(rect.bottom - rect.top + 1);
571 xoffs = UnScaleGUI(rect.left);
572 yoffs = UnScaleGUI(rect.top);
574 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
575 GetRailIcon(engine, true, y, image_type, &seq);
576 seq.GetBounds(&rect);
578 /* Calculate values relative to an imaginary center between the two sprites. */
579 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
580 height = std::max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
581 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
582 yoffs = std::min(yoffs, UnScaleGUI(rect.top));
587 * Build a railroad wagon.
588 * @param flags type of operation.
589 * @param tile tile of the depot where rail-vehicle is built.
590 * @param e the engine to build.
591 * @param[out] ret the vehicle that has been built.
592 * @return the cost of this operation or an error.
594 static CommandCost CmdBuildRailWagon(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
596 const RailVehicleInfo *rvi = &e->u.rail;
598 /* Check that the wagon can drive on the track in question */
599 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
601 if (flags & DC_EXEC) {
602 Train *v = new Train();
603 *ret = v;
604 v->spritenum = rvi->image_index;
606 v->engine_type = e->index;
607 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
609 DiagDirection dir = GetRailDepotDirection(tile);
611 v->direction = DiagDirToDir(dir);
612 v->tile = tile;
614 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
615 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
617 v->x_pos = x;
618 v->y_pos = y;
619 v->z_pos = GetSlopePixelZ(x, y);
620 v->owner = _current_company;
621 v->track = TRACK_BIT_DEPOT;
622 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
624 v->SetWagon();
626 v->SetFreeWagon();
627 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
629 v->cargo_type = e->GetDefaultCargoType();
630 v->cargo_cap = rvi->capacity;
631 v->refit_cap = 0;
633 v->railtype = rvi->railtype;
635 v->date_of_last_service = _date;
636 v->build_year = _cur_year;
637 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
638 v->random_bits = VehicleRandomBits();
640 v->group_id = DEFAULT_GROUP;
642 AddArticulatedParts(v);
644 v->UpdatePosition();
645 v->First()->ConsistChanged(CCF_ARRANGE);
646 UpdateTrainGroupID(v->First());
648 CheckConsistencyOfArticulatedVehicle(v);
650 /* Try to connect the vehicle to one of free chains of wagons. */
651 for (Train *w : Train::Iterate()) {
652 if (w->tile == tile && ///< Same depot
653 w->IsFreeWagon() && ///< A free wagon chain
654 w->engine_type == e->index && ///< Same type
655 w->First() != v && ///< Don't connect to ourself
656 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
657 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DC_EXEC, v->index, w->Last()->index, true).Succeeded()) {
658 break;
664 return CommandCost();
667 /** Move all free vehicles in the depot to the train */
668 static void NormalizeTrainVehInDepot(const Train *u)
670 for (const Train *v : Train::Iterate()) {
671 if (v->IsFreeWagon() && v->tile == u->tile &&
672 v->track == TRACK_BIT_DEPOT) {
673 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DC_EXEC, v->index, u->index, true).Failed()) {
674 break;
680 static void AddRearEngineToMultiheadedTrain(Train *v)
682 Train *u = new Train();
683 v->value >>= 1;
684 u->value = v->value;
685 u->direction = v->direction;
686 u->owner = v->owner;
687 u->tile = v->tile;
688 u->x_pos = v->x_pos;
689 u->y_pos = v->y_pos;
690 u->z_pos = v->z_pos;
691 u->track = TRACK_BIT_DEPOT;
692 u->vehstatus = v->vehstatus & ~VS_STOPPED;
693 u->spritenum = v->spritenum + 1;
694 u->cargo_type = v->cargo_type;
695 u->cargo_subtype = v->cargo_subtype;
696 u->cargo_cap = v->cargo_cap;
697 u->refit_cap = v->refit_cap;
698 u->railtype = v->railtype;
699 u->engine_type = v->engine_type;
700 u->date_of_last_service = v->date_of_last_service;
701 u->build_year = v->build_year;
702 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
703 u->random_bits = VehicleRandomBits();
704 v->SetMultiheaded();
705 u->SetMultiheaded();
706 v->SetNext(u);
707 u->UpdatePosition();
709 /* Now we need to link the front and rear engines together */
710 v->other_multiheaded_part = u;
711 u->other_multiheaded_part = v;
715 * Build a railroad vehicle.
716 * @param flags type of operation.
717 * @param tile tile of the depot where rail-vehicle is built.
718 * @param e the engine to build.
719 * @param free_cars add any free cars to the train.
720 * @param[out] ret the vehicle that has been built.
721 * @return the cost of this operation or an error.
723 CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, bool free_cars, Vehicle **ret)
725 const RailVehicleInfo *rvi = &e->u.rail;
727 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(flags, tile, e, ret);
729 /* Check if depot and new engine uses the same kind of tracks *
730 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
731 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
733 if (flags & DC_EXEC) {
734 DiagDirection dir = GetRailDepotDirection(tile);
735 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
736 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
738 Train *v = new Train();
739 *ret = v;
740 v->direction = DiagDirToDir(dir);
741 v->tile = tile;
742 v->owner = _current_company;
743 v->x_pos = x;
744 v->y_pos = y;
745 v->z_pos = GetSlopePixelZ(x, y);
746 v->track = TRACK_BIT_DEPOT;
747 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
748 v->spritenum = rvi->image_index;
749 v->cargo_type = e->GetDefaultCargoType();
750 v->cargo_cap = rvi->capacity;
751 v->refit_cap = 0;
752 v->last_station_visited = INVALID_STATION;
753 v->last_loading_station = INVALID_STATION;
755 v->engine_type = e->index;
756 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
758 v->reliability = e->reliability;
759 v->reliability_spd_dec = e->reliability_spd_dec;
760 v->max_age = e->GetLifeLengthInDays();
762 v->railtype = rvi->railtype;
764 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
765 v->date_of_last_service = _date;
766 v->build_year = _cur_year;
767 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
768 v->random_bits = VehicleRandomBits();
770 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
771 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
773 v->group_id = DEFAULT_GROUP;
775 v->SetFrontEngine();
776 v->SetEngine();
778 v->UpdatePosition();
780 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
781 AddRearEngineToMultiheadedTrain(v);
782 } else {
783 AddArticulatedParts(v);
786 v->ConsistChanged(CCF_ARRANGE);
787 UpdateTrainGroupID(v);
789 if (free_cars && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
790 NormalizeTrainVehInDepot(v);
793 CheckConsistencyOfArticulatedVehicle(v);
796 return CommandCost();
799 static Train *FindGoodVehiclePos(const Train *src)
801 EngineID eng = src->engine_type;
802 TileIndex tile = src->tile;
804 for (Train *dst : Train::Iterate()) {
805 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
806 /* check so all vehicles in the line have the same engine. */
807 Train *t = dst;
808 while (t->engine_type == eng) {
809 t = t->Next();
810 if (t == nullptr) return dst;
815 return nullptr;
818 /** Helper type for lists/vectors of trains */
819 typedef std::vector<Train *> TrainList;
822 * Make a backup of a train into a train list.
823 * @param list to make the backup in
824 * @param t the train to make the backup of
826 static void MakeTrainBackup(TrainList &list, Train *t)
828 for (; t != nullptr; t = t->Next()) list.push_back(t);
832 * Restore the train from the backup list.
833 * @param list the train to restore.
835 static void RestoreTrainBackup(TrainList &list)
837 /* No train, nothing to do. */
838 if (list.size() == 0) return;
840 Train *prev = nullptr;
841 /* Iterate over the list and rebuild it. */
842 for (Train *t : list) {
843 if (prev != nullptr) {
844 prev->SetNext(t);
845 } else if (t->Previous() != nullptr) {
846 /* Make sure the head of the train is always the first in the chain. */
847 t->Previous()->SetNext(nullptr);
849 prev = t;
854 * Remove the given wagon from its consist.
855 * @param part the part of the train to remove.
856 * @param chain whether to remove the whole chain.
858 static void RemoveFromConsist(Train *part, bool chain = false)
860 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
862 /* Unlink at the front, but make it point to the next
863 * vehicle after the to be remove part. */
864 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
866 /* Unlink at the back */
867 tail->SetNext(nullptr);
871 * Inserts a chain into the train at dst.
872 * @param dst the place where to append after.
873 * @param chain the chain to actually add.
875 static void InsertInConsist(Train *dst, Train *chain)
877 /* We do not want to add something in the middle of an articulated part. */
878 assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
880 chain->Last()->SetNext(dst->Next());
881 dst->SetNext(chain);
885 * Normalise the dual heads in the train, i.e. if one is
886 * missing move that one to this train.
887 * @param t the train to normalise.
889 static void NormaliseDualHeads(Train *t)
891 for (; t != nullptr; t = t->GetNextVehicle()) {
892 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
894 /* Make sure that there are no free cars before next engine */
895 Train *u;
896 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
898 if (u == t->other_multiheaded_part) continue;
900 /* Remove the part from the 'wrong' train */
901 RemoveFromConsist(t->other_multiheaded_part);
902 /* And add it to the 'right' train */
903 InsertInConsist(u, t->other_multiheaded_part);
908 * Normalise the sub types of the parts in this chain.
909 * @param chain the chain to normalise.
911 static void NormaliseSubtypes(Train *chain)
913 /* Nothing to do */
914 if (chain == nullptr) return;
916 /* We must be the first in the chain. */
917 assert(chain->Previous() == nullptr);
919 /* Set the appropriate bits for the first in the chain. */
920 if (chain->IsWagon()) {
921 chain->SetFreeWagon();
922 } else {
923 assert(chain->IsEngine());
924 chain->SetFrontEngine();
927 /* Now clear the bits for the rest of the chain */
928 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
929 t->ClearFreeWagon();
930 t->ClearFrontEngine();
935 * Check/validate whether we may actually build a new train.
936 * @note All vehicles are/were 'heads' of their chains.
937 * @param original_dst The original destination chain.
938 * @param dst The destination chain after constructing the train.
939 * @param original_src The original source chain.
940 * @param src The source chain after constructing the train.
941 * @return possible error of this command.
943 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
945 /* Just add 'new' engines and subtract the original ones.
946 * If that's less than or equal to 0 we can be sure we did
947 * not add any engines (read: trains) along the way. */
948 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
949 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
950 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
951 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
952 return CommandCost();
955 /* Get a free unit number and check whether it's within the bounds.
956 * There will always be a maximum of one new train. */
957 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
959 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
963 * Check whether the train parts can be attached.
964 * @param t the train to check
965 * @return possible error of this command.
967 static CommandCost CheckTrainAttachment(Train *t)
969 /* No multi-part train, no need to check. */
970 if (t == nullptr || t->Next() == nullptr) return CommandCost();
972 /* The maximum length for a train. For each part we decrease this by one
973 * and if the result is negative the train is simply too long. */
974 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
976 /* For free-wagon chains, check if they are within the max_train_length limit. */
977 if (!t->IsEngine()) {
978 t = t->Next();
979 while (t != nullptr) {
980 allowed_len -= t->gcache.cached_veh_length;
982 t = t->Next();
985 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
986 return CommandCost();
989 Train *head = t;
990 Train *prev = t;
992 /* Break the prev -> t link so it always holds within the loop. */
993 t = t->Next();
994 prev->SetNext(nullptr);
996 /* Make sure the cache is cleared. */
997 head->InvalidateNewGRFCache();
999 while (t != nullptr) {
1000 allowed_len -= t->gcache.cached_veh_length;
1002 Train *next = t->Next();
1004 /* Unlink the to-be-added piece; it is already unlinked from the previous
1005 * part due to the fact that the prev -> t link is broken. */
1006 t->SetNext(nullptr);
1008 /* Don't check callback for articulated or rear dual headed parts */
1009 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1010 /* Back up and clear the first_engine data to avoid using wagon override group */
1011 EngineID first_engine = t->gcache.first_engine;
1012 t->gcache.first_engine = INVALID_ENGINE;
1014 /* We don't want the cache to interfere. head's cache is cleared before
1015 * the loop and after each callback does not need to be cleared here. */
1016 t->InvalidateNewGRFCache();
1018 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1020 /* Restore original first_engine data */
1021 t->gcache.first_engine = first_engine;
1023 /* We do not want to remember any cached variables from the test run */
1024 t->InvalidateNewGRFCache();
1025 head->InvalidateNewGRFCache();
1027 if (callback != CALLBACK_FAILED) {
1028 /* A failing callback means everything is okay */
1029 StringID error = STR_NULL;
1031 if (head->GetGRF()->grf_version < 8) {
1032 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1033 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1034 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1035 } else {
1036 if (callback < 0x400) {
1037 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1038 } else {
1039 switch (callback) {
1040 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1041 case 0x401: // allow
1042 break;
1044 default: // unknown reason -> disallow
1045 case 0x402: // disallow attaching
1046 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1047 break;
1052 if (error != STR_NULL) return_cmd_error(error);
1056 /* And link it to the new part. */
1057 prev->SetNext(t);
1058 prev = t;
1059 t = next;
1062 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1063 return CommandCost();
1067 * Validate whether we are going to create valid trains.
1068 * @note All vehicles are/were 'heads' of their chains.
1069 * @param original_dst The original destination chain.
1070 * @param dst The destination chain after constructing the train.
1071 * @param original_src The original source chain.
1072 * @param src The source chain after constructing the train.
1073 * @param check_limit Whether to check the vehicle limit.
1074 * @return possible error of this command.
1076 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1078 /* Check whether we may actually construct the trains. */
1079 CommandCost ret = CheckTrainAttachment(src);
1080 if (ret.Failed()) return ret;
1081 ret = CheckTrainAttachment(dst);
1082 if (ret.Failed()) return ret;
1084 /* Check whether we need to build a new train. */
1085 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1089 * Arrange the trains in the wanted way.
1090 * @param dst_head The destination chain of the to be moved vehicle.
1091 * @param dst The destination for the to be moved vehicle.
1092 * @param src_head The source chain of the to be moved vehicle.
1093 * @param src The to be moved vehicle.
1094 * @param move_chain Whether to move all vehicles after src or not.
1096 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1098 /* First determine the front of the two resulting trains */
1099 if (*src_head == *dst_head) {
1100 /* If we aren't moving part(s) to a new train, we are just moving the
1101 * front back and there is not destination head. */
1102 *dst_head = nullptr;
1103 } else if (*dst_head == nullptr) {
1104 /* If we are moving to a new train the head of the move train would become
1105 * the head of the new vehicle. */
1106 *dst_head = src;
1109 if (src == *src_head) {
1110 /* If we are moving the front of a train then we are, in effect, creating
1111 * a new head for the train. Point to that. Unless we are moving the whole
1112 * train in which case there is not 'source' train anymore.
1113 * In case we are a multiheaded part we want the complete thing to come
1114 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1115 * that is followed by a rear multihead we do not want to include that. */
1116 *src_head = move_chain ? nullptr :
1117 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1120 /* Now it's just simply removing the part that we are going to move from the
1121 * source train and *if* the destination is a not a new train add the chain
1122 * at the destination location. */
1123 RemoveFromConsist(src, move_chain);
1124 if (*dst_head != src) InsertInConsist(dst, src);
1126 /* Now normalise the dual heads, that is move the dual heads around in such
1127 * a way that the head and rear of a dual head are in the same train */
1128 NormaliseDualHeads(*src_head);
1129 NormaliseDualHeads(*dst_head);
1133 * Normalise the head of the train again, i.e. that is tell the world that
1134 * we have changed and update all kinds of variables.
1135 * @param head the train to update.
1137 static void NormaliseTrainHead(Train *head)
1139 /* Not much to do! */
1140 if (head == nullptr) return;
1142 /* Tell the 'world' the train changed. */
1143 head->ConsistChanged(CCF_ARRANGE);
1144 UpdateTrainGroupID(head);
1146 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1147 if (!head->IsFrontEngine()) return;
1149 /* Update the refit button and window */
1150 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1151 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1153 /* If we don't have a unit number yet, set one. */
1154 if (head->unitnumber != 0) return;
1155 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1159 * Move a rail vehicle around inside the depot.
1160 * @param flags type of operation
1161 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1162 * @param src_veh source vehicle index
1163 * @param dest_veh what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1164 * @param move_chain move all vehicles following the source vehicle
1165 * @return the cost of this operation or an error
1167 CommandCost CmdMoveRailVehicle(DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
1169 Train *src = Train::GetIfValid(src_veh);
1170 if (src == nullptr) return CMD_ERROR;
1172 CommandCost ret = CheckOwnership(src->owner);
1173 if (ret.Failed()) return ret;
1175 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1176 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1178 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1179 Train *dst;
1180 if (dest_veh == INVALID_VEHICLE) {
1181 dst = (src->IsEngine() || (flags & DC_AUTOREPLACE)) ? nullptr : FindGoodVehiclePos(src);
1182 } else {
1183 dst = Train::GetIfValid(dest_veh);
1184 if (dst == nullptr) return CMD_ERROR;
1186 CommandCost ret = CheckOwnership(dst->owner);
1187 if (ret.Failed()) return ret;
1189 /* Do not allow appending to crashed vehicles, too */
1190 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1193 /* if an articulated part is being handled, deal with its parent vehicle */
1194 src = src->GetFirstEnginePart();
1195 if (dst != nullptr) {
1196 dst = dst->GetFirstEnginePart();
1199 /* don't move the same vehicle.. */
1200 if (src == dst) return CommandCost();
1202 /* locate the head of the two chains */
1203 Train *src_head = src->First();
1204 Train *dst_head;
1205 if (dst != nullptr) {
1206 dst_head = dst->First();
1207 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1208 /* Now deal with articulated part of destination wagon */
1209 dst = dst->GetLastEnginePart();
1210 } else {
1211 dst_head = nullptr;
1214 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1216 /* When moving all wagons, we can't have the same src_head and dst_head */
1217 if (move_chain && src_head == dst_head) return CommandCost();
1219 /* When moving a multiheaded part to be place after itself, bail out. */
1220 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1222 /* Check if all vehicles in the source train are stopped inside a depot. */
1223 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1225 /* Check if all vehicles in the destination train are stopped inside a depot. */
1226 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1228 /* First make a backup of the order of the trains. That way we can do
1229 * whatever we want with the order and later on easily revert. */
1230 TrainList original_src;
1231 TrainList original_dst;
1233 MakeTrainBackup(original_src, src_head);
1234 MakeTrainBackup(original_dst, dst_head);
1236 /* Also make backup of the original heads as ArrangeTrains can change them.
1237 * For the destination head we do not care if it is the same as the source
1238 * head because in that case it's just a copy. */
1239 Train *original_src_head = src_head;
1240 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1242 /* We want this information from before the rearrangement, but execute this after the validation.
1243 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1244 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1245 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1246 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1248 /* (Re)arrange the trains in the wanted arrangement. */
1249 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1251 if ((flags & DC_AUTOREPLACE) == 0) {
1252 /* If the autoreplace flag is set we do not need to test for the validity
1253 * because we are going to revert the train to its original state. As we
1254 * assume the original state was correct autoreplace can skip this. */
1255 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1256 if (ret.Failed()) {
1257 /* Restore the train we had. */
1258 RestoreTrainBackup(original_src);
1259 RestoreTrainBackup(original_dst);
1260 return ret;
1264 /* do it? */
1265 if (flags & DC_EXEC) {
1266 /* Remove old heads from the statistics */
1267 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1268 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1270 /* First normalise the sub types of the chains. */
1271 NormaliseSubtypes(src_head);
1272 NormaliseSubtypes(dst_head);
1274 /* There are 14 different cases:
1275 * 1) front engine gets moved to a new train, it stays a front engine.
1276 * a) the 'next' part is a wagon that becomes a free wagon chain.
1277 * b) the 'next' part is an engine that becomes a front engine.
1278 * c) there is no 'next' part, nothing else happens
1279 * 2) front engine gets moved to another train, it is not a front engine anymore
1280 * a) the 'next' part is a wagon that becomes a free wagon chain.
1281 * b) the 'next' part is an engine that becomes a front engine.
1282 * c) there is no 'next' part, nothing else happens
1283 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1284 * a) the 'next' part is a wagon that becomes a free wagon chain.
1285 * b) the 'next' part is an engine that becomes a front engine.
1286 * 4) free wagon gets moved
1287 * a) the 'next' part is a wagon that becomes a free wagon chain.
1288 * b) the 'next' part is an engine that becomes a front engine.
1289 * c) there is no 'next' part, nothing else happens
1290 * 5) non front engine gets moved and becomes a new train, nothing else happens
1291 * 6) non front engine gets moved within a train / to another train, nothing happens
1292 * 7) wagon gets moved, nothing happens
1294 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1295 /* Cases #2 and #3: the front engine gets trashed. */
1296 CloseWindowById(WC_VEHICLE_VIEW, src->index);
1297 CloseWindowById(WC_VEHICLE_ORDERS, src->index);
1298 CloseWindowById(WC_VEHICLE_REFIT, src->index);
1299 CloseWindowById(WC_VEHICLE_DETAILS, src->index);
1300 CloseWindowById(WC_VEHICLE_TIMETABLE, src->index);
1301 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1302 SetWindowDirty(WC_COMPANY, _current_company);
1304 /* Delete orders, group stuff and the unit number as we're not the
1305 * front of any vehicle anymore. */
1306 DeleteVehicleOrders(src);
1307 RemoveVehicleFromGroup(src);
1308 src->unitnumber = 0;
1311 /* We weren't a front engine but are becoming one. So
1312 * we should be put in the default group. */
1313 if (original_src_head != src && dst_head == src) {
1314 SetTrainGroupID(src, DEFAULT_GROUP);
1315 SetWindowDirty(WC_COMPANY, _current_company);
1318 /* Add new heads to statistics */
1319 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1320 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1322 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1323 NormaliseTrainHead(src_head);
1324 NormaliseTrainHead(dst_head);
1326 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1327 CheckCargoCapacity(src_head);
1328 CheckCargoCapacity(dst_head);
1331 if (src_head != nullptr) src_head->First()->MarkDirty();
1332 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1334 /* We are undoubtedly changing something in the depot and train list. */
1335 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1336 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1337 } else {
1338 /* We don't want to execute what we're just tried. */
1339 RestoreTrainBackup(original_src);
1340 RestoreTrainBackup(original_dst);
1343 return CommandCost();
1347 * Sell a (single) train wagon/engine.
1348 * @param flags type of operation
1349 * @param t the train wagon to sell
1350 * @param sell_chain the selling mode
1351 * - sell_chain = false: only sell the single dragged wagon/engine (and any belonging rear-engines)
1352 * - sell_chain = true: sell the vehicle and all vehicles following it in the chain
1353 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1354 * @param backup_order make order backup?
1355 * @param user the user for the order backup.
1356 * @return the cost of this operation or an error
1358 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
1360 Train *v = Train::From(t)->GetFirstEnginePart();
1361 Train *first = v->First();
1363 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1365 /* First make a backup of the order of the train. That way we can do
1366 * whatever we want with the order and later on easily revert. */
1367 TrainList original;
1368 MakeTrainBackup(original, first);
1370 /* We need to keep track of the new head and the head of what we're going to sell. */
1371 Train *new_head = first;
1372 Train *sell_head = nullptr;
1374 /* Split the train in the wanted way. */
1375 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1377 /* We don't need to validate the second train; it's going to be sold. */
1378 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1379 if (ret.Failed()) {
1380 /* Restore the train we had. */
1381 RestoreTrainBackup(original);
1382 return ret;
1385 if (first->orders == nullptr && !OrderList::CanAllocateItem()) {
1386 /* Restore the train we had. */
1387 RestoreTrainBackup(original);
1388 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1391 CommandCost cost(EXPENSES_NEW_VEHICLES);
1392 for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1394 /* do it? */
1395 if (flags & DC_EXEC) {
1396 /* First normalise the sub types of the chain. */
1397 NormaliseSubtypes(new_head);
1399 if (v == first && v->IsEngine() && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1400 /* We are selling the front engine. In this case we want to
1401 * 'give' the order, unit number and such to the new head. */
1402 new_head->orders = first->orders;
1403 new_head->AddToShared(first);
1404 DeleteVehicleOrders(first);
1406 /* Copy other important data from the front engine */
1407 new_head->CopyVehicleConfigAndStatistics(first);
1408 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1409 } else if (v->IsPrimaryVehicle() && backup_order) {
1410 OrderBackup::Backup(v, user);
1413 /* We need to update the information about the train. */
1414 NormaliseTrainHead(new_head);
1416 /* We are undoubtedly changing something in the depot and train list. */
1417 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1418 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1420 /* Actually delete the sold 'goods' */
1421 delete sell_head;
1422 } else {
1423 /* We don't want to execute what we're just tried. */
1424 RestoreTrainBackup(original);
1427 return cost;
1430 void Train::UpdateDeltaXY()
1432 /* Set common defaults. */
1433 this->x_offs = -1;
1434 this->y_offs = -1;
1435 this->x_extent = 3;
1436 this->y_extent = 3;
1437 this->z_extent = 6;
1438 this->x_bb_offs = 0;
1439 this->y_bb_offs = 0;
1441 if (!IsDiagonalDirection(this->direction)) {
1442 static const int _sign_table[] =
1444 /* x, y */
1445 -1, -1, // DIR_N
1446 -1, 1, // DIR_E
1447 1, 1, // DIR_S
1448 1, -1, // DIR_W
1451 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1453 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1454 this->x_offs -= half_shorten * _sign_table[this->direction];
1455 this->y_offs -= half_shorten * _sign_table[this->direction + 1];
1456 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1457 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1458 } else {
1459 switch (this->direction) {
1460 /* Shorten southern corner of the bounding box according the vehicle length
1461 * and center the bounding box on the vehicle. */
1462 case DIR_NE:
1463 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1464 this->x_extent = this->gcache.cached_veh_length - 1;
1465 this->x_bb_offs = -1;
1466 break;
1468 case DIR_NW:
1469 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1470 this->y_extent = this->gcache.cached_veh_length - 1;
1471 this->y_bb_offs = -1;
1472 break;
1474 /* Move northern corner of the bounding box down according to vehicle length
1475 * and center the bounding box on the vehicle. */
1476 case DIR_SW:
1477 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1478 this->x_extent = VEHICLE_LENGTH - 1;
1479 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1480 break;
1482 case DIR_SE:
1483 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1484 this->y_extent = VEHICLE_LENGTH - 1;
1485 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1486 break;
1488 default:
1489 NOT_REACHED();
1495 * Mark a train as stuck and stop it if it isn't stopped right now.
1496 * @param v %Train to mark as being stuck.
1498 static void MarkTrainAsStuck(Train *v)
1500 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1501 /* It is the first time the problem occurred, set the "train stuck" flag. */
1502 SetBit(v->flags, VRF_TRAIN_STUCK);
1504 v->wait_counter = 0;
1506 /* Stop train */
1507 v->cur_speed = 0;
1508 v->subspeed = 0;
1509 v->SetLastSpeed();
1511 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1516 * Swap the two up/down flags in two ways:
1517 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1518 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1519 * @param[in,out] swap_flag1 First train flag.
1520 * @param[in,out] swap_flag2 Second train flag.
1522 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1524 uint16 flag1 = *swap_flag1;
1525 uint16 flag2 = *swap_flag2;
1527 /* Clear the flags */
1528 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1529 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1530 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1531 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1533 /* Reverse the rail-flags (if needed) */
1534 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1535 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1536 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1537 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1539 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1540 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1541 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1542 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1547 * Updates some variables after swapping the vehicle.
1548 * @param v swapped vehicle
1550 static void UpdateStatusAfterSwap(Train *v)
1552 /* Reverse the direction. */
1553 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1555 /* Call the proper EnterTile function unless we are in a wormhole. */
1556 if (v->track != TRACK_BIT_WORMHOLE) {
1557 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1558 } else {
1559 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1560 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1561 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1562 * when we shouldn't have. Check if this is the case. */
1563 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1564 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1565 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1566 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1567 /* We have just left the wormhole, possibly set the
1568 * "goingdown" bit. UpdateInclination() can be used
1569 * because we are at the border of the tile. */
1570 v->UpdatePosition();
1571 v->UpdateInclination(true, true);
1572 return;
1577 v->UpdatePosition();
1578 v->UpdateViewport(true, true);
1582 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1583 * @param v Consist to change.
1584 * @param l %Vehicle index in the consist of the first vehicle.
1585 * @param r %Vehicle index in the consist of the second vehicle.
1587 void ReverseTrainSwapVeh(Train *v, int l, int r)
1589 Train *a, *b;
1591 /* locate vehicles to swap */
1592 for (a = v; l != 0; l--) a = a->Next();
1593 for (b = v; r != 0; r--) b = b->Next();
1595 if (a != b) {
1596 /* swap the hidden bits */
1598 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1599 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1600 a->vehstatus = tmp;
1603 Swap(a->track, b->track);
1604 Swap(a->direction, b->direction);
1605 Swap(a->x_pos, b->x_pos);
1606 Swap(a->y_pos, b->y_pos);
1607 Swap(a->tile, b->tile);
1608 Swap(a->z_pos, b->z_pos);
1610 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1612 UpdateStatusAfterSwap(a);
1613 UpdateStatusAfterSwap(b);
1614 } else {
1615 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1616 * This is a little bit redundant way, a->gv_flags will
1617 * be (re)set twice, but it reduces code duplication */
1618 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1619 UpdateStatusAfterSwap(a);
1625 * Check if the vehicle is a train
1626 * @param v vehicle on tile
1627 * @return v if it is a train, nullptr otherwise
1629 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1631 return (v->type == VEH_TRAIN) ? v : nullptr;
1636 * Checks if a train is approaching a rail-road crossing
1637 * @param v vehicle on tile
1638 * @param data tile with crossing we are testing
1639 * @return v if it is approaching a crossing, nullptr otherwise
1641 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1643 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
1645 Train *t = Train::From(v);
1646 if (!t->IsFrontEngine()) return nullptr;
1648 TileIndex tile = *(TileIndex *)data;
1650 if (TrainApproachingCrossingTile(t) != tile) return nullptr;
1652 return t;
1657 * Finds a vehicle approaching rail-road crossing
1658 * @param tile tile to test
1659 * @return true if a vehicle is approaching the crossing
1660 * @pre tile is a rail-road crossing
1662 static bool TrainApproachingCrossing(TileIndex tile)
1664 assert(IsLevelCrossingTile(tile));
1666 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1667 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1669 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1671 dir = ReverseDiagDir(dir);
1672 tile_from = tile + TileOffsByDiagDir(dir);
1674 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1678 * Check if a level crossing should be barred.
1679 * @param tile The tile to check.
1680 * @return True if the crossing should be barred, else false.
1682 static inline bool CheckLevelCrossing(TileIndex tile)
1684 /* reserved || train on crossing || train approaching crossing */
1685 return HasCrossingReservation(tile) || HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
1689 * Sets a level crossing tile to the correct state.
1690 * @param tile Tile to update.
1691 * @param sound Should we play sound?
1692 * @param force_barred Should we set the crossing to barred?
1693 * @pre tile is a rail-road crossing.
1695 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
1697 assert(IsLevelCrossingTile(tile));
1698 bool set_barred;
1700 /* We force the crossing to be barred when an adjacent crossing is barred, otherwise let it decide for itself. */
1701 set_barred = force_barred || CheckLevelCrossing(tile);
1703 /* The state has changed */
1704 if (set_barred != IsCrossingBarred(tile)) {
1705 if (set_barred && sound && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1706 SetCrossingBarred(tile, set_barred);
1707 MarkTileDirtyByTile(tile);
1712 * Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
1713 * @param tile Tile which causes the update.
1714 * @param sound Should we play sound?
1715 * @param force_bar Should we force the crossing to be barred?
1717 void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
1719 if (!IsLevelCrossingTile(tile)) return;
1721 bool forced_state = force_bar;
1723 const Axis axis = GetCrossingRoadAxis(tile);
1724 const DiagDirection dir1 = AxisToDiagDir(axis);
1725 const DiagDirection dir2 = ReverseDiagDir(dir1);
1727 /* Check if an adjacent crossing is barred. */
1728 for (DiagDirection dir : { dir1, dir2 }) {
1729 for (TileIndex t = tile; !forced_state && t < MapSize() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1730 forced_state |= CheckLevelCrossing(t);
1734 /* Now that we know whether all tiles in this crossing should be barred or open,
1735 * we need to update those tiles. We start with the tile itself, then look along the road axis. */
1736 UpdateLevelCrossingTile(tile, sound, forced_state);
1737 for (DiagDirection dir : { dir1, dir2 }) {
1738 for (TileIndex t = TileAddByDiagDir(tile, dir); t < MapSize() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1739 UpdateLevelCrossingTile(t, sound, forced_state);
1745 * Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.
1746 * @param The tile which causes the update.
1748 void MarkDirtyAdjacentLevelCrossingTiles(TileIndex tile, Axis road_axis)
1750 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1751 const DiagDirection dir2 = ReverseDiagDir(dir1);
1752 for (DiagDirection dir : { dir1, dir2 }) {
1753 const TileIndex t = TileAddByDiagDir(tile, dir);
1754 if (t < MapSize() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1755 MarkTileDirtyByTile(t);
1761 * Bars crossing and plays ding-ding sound if not barred already
1762 * @param tile tile with crossing
1763 * @pre tile is a rail-road crossing
1765 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1767 if (!IsCrossingBarred(tile)) {
1768 SetCrossingReservation(tile, true);
1769 UpdateLevelCrossing(tile, true);
1775 * Advances wagons for train reversing, needed for variable length wagons.
1776 * This one is called before the train is reversed.
1777 * @param v First vehicle in chain
1779 static void AdvanceWagonsBeforeSwap(Train *v)
1781 Train *base = v;
1782 Train *first = base; // first vehicle to move
1783 Train *last = v->Last(); // last vehicle to move
1784 uint length = CountVehiclesInChain(v);
1786 while (length > 2) {
1787 last = last->Previous();
1788 first = first->Next();
1790 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1792 /* do not update images now
1793 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1794 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1796 base = first; // == base->Next()
1797 length -= 2;
1803 * Advances wagons for train reversing, needed for variable length wagons.
1804 * This one is called after the train is reversed.
1805 * @param v First vehicle in chain
1807 static void AdvanceWagonsAfterSwap(Train *v)
1809 /* first of all, fix the situation when the train was entering a depot */
1810 Train *dep = v; // last vehicle in front of just left depot
1811 while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1812 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1815 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1817 if (leave != nullptr) {
1818 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1819 int d = TicksToLeaveDepot(dep);
1821 if (d <= 0) {
1822 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1823 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1824 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1826 } else {
1827 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1830 Train *base = v;
1831 Train *first = base; // first vehicle to move
1832 Train *last = v->Last(); // last vehicle to move
1833 uint length = CountVehiclesInChain(v);
1835 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1836 * they have already correct spacing, so we have to make sure they are moved how they should */
1837 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1839 while (length > 2) {
1840 /* we reached vehicle (originally) in front of a depot, stop now
1841 * (we would move wagons that are already moved with new wagon length). */
1842 if (base == dep) break;
1844 /* the last wagon was that one leaving a depot, so do not move it anymore */
1845 if (last == dep) nomove = true;
1847 last = last->Previous();
1848 first = first->Next();
1850 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1852 /* do not update images now */
1853 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1855 base = first; // == base->Next()
1856 length -= 2;
1860 static bool IsWholeTrainInsideDepot(const Train *v)
1862 for (const Train *u = v; u != nullptr; u = u->Next()) {
1863 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
1865 return true;
1869 * Turn a train around.
1870 * @param v %Train to turn around.
1872 void ReverseTrainDirection(Train *v)
1874 if (IsRailDepotTile(v->tile)) {
1875 if (IsWholeTrainInsideDepot(v)) return;
1876 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1879 /* Clear path reservation in front if train is not stuck. */
1880 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1882 /* Check if we were approaching a rail/road-crossing */
1883 TileIndex crossing = TrainApproachingCrossingTile(v);
1885 /* count number of vehicles */
1886 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1888 AdvanceWagonsBeforeSwap(v);
1890 /* swap start<>end, start+1<>end-1, ... */
1891 int l = 0;
1892 do {
1893 ReverseTrainSwapVeh(v, l++, r--);
1894 } while (l <= r);
1896 AdvanceWagonsAfterSwap(v);
1898 if (IsRailDepotTile(v->tile)) {
1899 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1902 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1904 ClrBit(v->flags, VRF_REVERSING);
1906 /* recalculate cached data */
1907 v->ConsistChanged(CCF_TRACK);
1909 /* update all images */
1910 for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
1912 /* update crossing we were approaching */
1913 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1915 /* maybe we are approaching crossing now, after reversal */
1916 crossing = TrainApproachingCrossingTile(v);
1917 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1919 /* If we are inside a depot after reversing, don't bother with path reserving. */
1920 if (v->track == TRACK_BIT_DEPOT) {
1921 /* Can't be stuck here as inside a depot is always a safe tile. */
1922 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1923 ClrBit(v->flags, VRF_TRAIN_STUCK);
1924 return;
1927 /* VehicleExitDir does not always produce the desired dir for depots and
1928 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1929 DiagDirection dir = VehicleExitDir(v->direction, v->track);
1930 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
1932 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
1933 /* If we are currently on a tile with conventional signals, we can't treat the
1934 * current tile as a safe tile or we would enter a PBS block without a reservation. */
1935 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1936 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
1937 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1939 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1940 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1942 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1943 if (TryPathReserve(v, false, first_tile_okay)) {
1944 /* Do a look-ahead now in case our current tile was already a safe tile. */
1945 CheckNextTrainTile(v);
1946 } else if (v->current_order.GetType() != OT_LOADING) {
1947 /* Do not wait for a way out when we're still loading */
1948 MarkTrainAsStuck(v);
1950 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1951 /* A train not inside a PBS block can't be stuck. */
1952 ClrBit(v->flags, VRF_TRAIN_STUCK);
1953 v->wait_counter = 0;
1958 * Reverse train.
1959 * @param flags type of operation
1960 * @param veh_id train to reverse
1961 * @param reverse_single_veh if true, reverse a unit in a train (needs to be in a depot)
1962 * @return the cost of this operation or an error
1964 CommandCost CmdReverseTrainDirection(DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
1966 Train *v = Train::GetIfValid(veh_id);
1967 if (v == nullptr) return CMD_ERROR;
1969 CommandCost ret = CheckOwnership(v->owner);
1970 if (ret.Failed()) return ret;
1972 if (reverse_single_veh) {
1973 /* turn a single unit around */
1975 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1976 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1978 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1980 Train *front = v->First();
1981 /* make sure the vehicle is stopped in the depot */
1982 if (!front->IsStoppedInDepot()) {
1983 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1986 if (flags & DC_EXEC) {
1987 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1989 front->ConsistChanged(CCF_ARRANGE);
1990 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
1991 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1992 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
1993 SetWindowClassesDirty(WC_TRAINS_LIST);
1995 } else {
1996 /* turn the whole train around */
1997 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
1998 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
2000 if (flags & DC_EXEC) {
2001 /* Properly leave the station if we are loading and won't be loading anymore */
2002 if (v->current_order.IsType(OT_LOADING)) {
2003 const Vehicle *last = v;
2004 while (last->Next() != nullptr) last = last->Next();
2006 /* not a station || different station --> leave the station */
2007 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2008 v->LeaveStation();
2012 /* We cancel any 'skip signal at dangers' here */
2013 v->force_proceed = TFP_NONE;
2014 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2016 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2017 ToggleBit(v->flags, VRF_REVERSING);
2018 } else {
2019 v->cur_speed = 0;
2020 v->SetLastSpeed();
2021 HideFillingPercent(&v->fill_percent_te_id);
2022 ReverseTrainDirection(v);
2026 return CommandCost();
2030 * Force a train through a red signal
2031 * @param flags type of operation
2032 * @param veh_id train to ignore the red signal
2033 * @return the cost of this operation or an error
2035 CommandCost CmdForceTrainProceed(DoCommandFlag flags, VehicleID veh_id)
2037 Train *t = Train::GetIfValid(veh_id);
2038 if (t == nullptr) return CMD_ERROR;
2040 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2042 CommandCost ret = CheckOwnership(t->owner);
2043 if (ret.Failed()) return ret;
2046 if (flags & DC_EXEC) {
2047 /* If we are forced to proceed, cancel that order.
2048 * If we are marked stuck we would want to force the train
2049 * to proceed to the next signal. In the other cases we
2050 * would like to pass the signal at danger and run till the
2051 * next signal we encounter. */
2052 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2053 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2056 return CommandCost();
2060 * Try to find a depot nearby.
2061 * @param v %Train that wants a depot.
2062 * @param max_distance Maximal search distance.
2063 * @return Information where the closest train depot is located.
2064 * @pre The given vehicle must not be crashed!
2066 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2068 assert(!(v->vehstatus & VS_CRASHED));
2070 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2072 PBSTileInfo origin = FollowTrainReservation(v);
2073 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2075 switch (_settings_game.pf.pathfinder_for_trains) {
2076 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2077 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2079 default: NOT_REACHED();
2084 * Locate the closest depot for this consist, and return the information to the caller.
2085 * @param[out] location If not \c nullptr and a depot is found, store its location in the given address.
2086 * @param[out] destination If not \c nullptr and a depot is found, store its index in the given address.
2087 * @param[out] reverse If not \c nullptr and a depot is found, store reversal information in the given address.
2088 * @return A depot has been found.
2090 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2092 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2093 if (tfdd.best_length == UINT_MAX) return false;
2095 if (location != nullptr) *location = tfdd.tile;
2096 if (destination != nullptr) *destination = GetDepotIndex(tfdd.tile);
2097 if (reverse != nullptr) *reverse = tfdd.reverse;
2099 return true;
2102 /** Play a sound for a train leaving the station. */
2103 void Train::PlayLeaveStationSound() const
2105 static const SoundFx sfx[] = {
2106 SND_04_DEPARTURE_STEAM,
2107 SND_0A_DEPARTURE_TRAIN,
2108 SND_0A_DEPARTURE_TRAIN,
2109 SND_47_DEPARTURE_MONORAIL,
2110 SND_41_DEPARTURE_MAGLEV
2113 if (PlayVehicleSound(this, VSE_START)) return;
2115 EngineID engtype = this->engine_type;
2116 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2120 * Check if the train is on the last reserved tile and try to extend the path then.
2121 * @param v %Train that needs its path extended.
2123 static void CheckNextTrainTile(Train *v)
2125 /* Don't do any look-ahead if path_backoff_interval is 255. */
2126 if (_settings_game.pf.path_backoff_interval == 255) return;
2128 /* Exit if we are inside a depot. */
2129 if (v->track == TRACK_BIT_DEPOT) return;
2131 switch (v->current_order.GetType()) {
2132 /* Exit if we reached our destination depot. */
2133 case OT_GOTO_DEPOT:
2134 if (v->tile == v->dest_tile) return;
2135 break;
2137 case OT_GOTO_WAYPOINT:
2138 /* If we reached our waypoint, make sure we see that. */
2139 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2140 break;
2142 case OT_NOTHING:
2143 case OT_LEAVESTATION:
2144 case OT_LOADING:
2145 /* Exit if the current order doesn't have a destination, but the train has orders. */
2146 if (v->GetNumOrders() > 0) return;
2147 break;
2149 default:
2150 break;
2152 /* Exit if we are on a station tile and are going to stop. */
2153 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2155 Trackdir td = v->GetVehicleTrackdir();
2157 /* On a tile with a red non-pbs signal, don't look ahead. */
2158 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2159 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2160 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2162 CFollowTrackRail ft(v);
2163 if (!ft.Follow(v->tile, td)) return;
2165 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2166 /* Next tile is not reserved. */
2167 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2168 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2169 /* If the next tile is a PBS signal, try to make a reservation. */
2170 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2171 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2172 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2174 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
2181 * Will the train stay in the depot the next tick?
2182 * @param v %Train to check.
2183 * @return True if it stays in the depot, false otherwise.
2185 static bool CheckTrainStayInDepot(Train *v)
2187 /* bail out if not all wagons are in the same depot or not in a depot at all */
2188 for (const Train *u = v; u != nullptr; u = u->Next()) {
2189 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2192 /* if the train got no power, then keep it in the depot */
2193 if (v->gcache.cached_power == 0) {
2194 v->vehstatus |= VS_STOPPED;
2195 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2196 return true;
2199 SigSegState seg_state;
2201 if (v->force_proceed == TFP_NONE) {
2202 /* force proceed was not pressed */
2203 if (++v->wait_counter < 37) {
2204 SetWindowClassesDirty(WC_TRAINS_LIST);
2205 return true;
2208 v->wait_counter = 0;
2210 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2211 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2212 /* Full and no PBS signal in block or depot reserved, can't exit. */
2213 SetWindowClassesDirty(WC_TRAINS_LIST);
2214 return true;
2216 } else {
2217 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2220 /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2221 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2222 /* Service when depot has no reservation. */
2223 if (!HasDepotReservation(v->tile)) VehicleEnterDepot(v);
2224 return true;
2227 /* Only leave when we can reserve a path to our destination. */
2228 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2229 /* No path and no force proceed. */
2230 SetWindowClassesDirty(WC_TRAINS_LIST);
2231 MarkTrainAsStuck(v);
2232 return true;
2235 SetDepotReservation(v->tile, true);
2236 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2238 VehicleServiceInDepot(v);
2239 SetWindowClassesDirty(WC_TRAINS_LIST);
2240 v->PlayLeaveStationSound();
2242 v->track = TRACK_BIT_X;
2243 if (v->direction & 2) v->track = TRACK_BIT_Y;
2245 v->vehstatus &= ~VS_HIDDEN;
2246 v->cur_speed = 0;
2248 v->UpdateViewport(true, true);
2249 v->UpdatePosition();
2250 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2251 v->UpdateAcceleration();
2252 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2254 return false;
2258 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2259 * @param v %Train owning the reservation.
2260 * @param tile Tile with reservation to clear.
2261 * @param track_dir Track direction to clear.
2263 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2265 DiagDirection dir = TrackdirToExitdir(track_dir);
2267 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2268 /* Are we just leaving a tunnel/bridge? */
2269 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2270 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2272 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2273 /* Free the reservation only if no other train is on the tiles. */
2274 SetTunnelBridgeReservation(tile, false);
2275 SetTunnelBridgeReservation(end, false);
2277 if (_settings_client.gui.show_track_reservation) {
2278 if (IsBridge(tile)) {
2279 MarkBridgeDirty(tile);
2280 } else {
2281 MarkTileDirtyByTile(tile);
2282 MarkTileDirtyByTile(end);
2287 } else if (IsRailStationTile(tile)) {
2288 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2289 /* If the new tile is not a further tile of the same station, we
2290 * clear the reservation for the whole platform. */
2291 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2292 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2294 } else {
2295 /* Any other tile */
2296 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2301 * Free the reserved path in front of a vehicle.
2302 * @param v %Train owning the reserved path.
2304 void FreeTrainTrackReservation(const Train *v)
2306 assert(v->IsFrontEngine());
2308 TileIndex tile = v->tile;
2309 Trackdir td = v->GetVehicleTrackdir();
2310 bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2311 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2313 /* Can't be holding a reservation if we enter a depot. */
2314 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2315 if (v->track == TRACK_BIT_DEPOT) {
2316 /* Front engine is in a depot. We enter if some part is not in the depot. */
2317 for (const Train *u = v; u != nullptr; u = u->Next()) {
2318 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2321 /* Don't free reservation if it's not ours. */
2322 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2324 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2325 while (ft.Follow(tile, td)) {
2326 tile = ft.m_new_tile;
2327 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2328 td = RemoveFirstTrackdir(&bits);
2329 assert(bits == TRACKDIR_BIT_NONE);
2331 if (!IsValidTrackdir(td)) break;
2333 if (IsTileType(tile, MP_RAILWAY)) {
2334 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2335 /* Conventional signal along trackdir: remove reservation and stop. */
2336 UnreserveRailTrack(tile, TrackdirToTrack(td));
2337 break;
2339 if (HasPbsSignalOnTrackdir(tile, td)) {
2340 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2341 /* Red PBS signal? Can't be our reservation, would be green then. */
2342 break;
2343 } else {
2344 /* Turn the signal back to red. */
2345 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2346 MarkTileDirtyByTile(tile);
2348 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2349 break;
2353 /* Don't free first station/bridge/tunnel if we are on it. */
2354 if (free_tile || (!(ft.m_is_station && GetStationIndex(ft.m_new_tile) == station_id) && !ft.m_is_tunnel && !ft.m_is_bridge)) ClearPathReservation(v, tile, td);
2356 free_tile = true;
2360 static const byte _initial_tile_subcoord[6][4][3] = {
2361 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2362 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2363 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2364 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2365 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2366 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2370 * Perform pathfinding for a train.
2372 * @param v The train
2373 * @param tile The tile the train is about to enter
2374 * @param enterdir Diagonal direction the train is coming from
2375 * @param tracks Usable tracks on the new tile
2376 * @param[out] path_found Whether a path has been found or not.
2377 * @param do_track_reservation Path reservation is requested
2378 * @param[out] dest State and destination of the requested path
2379 * @param[out] final_dest Final tile of the best path found
2380 * @return The best track the train should follow
2382 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
2384 if (final_dest != nullptr) *final_dest = INVALID_TILE;
2386 switch (_settings_game.pf.pathfinder_for_trains) {
2387 case VPF_NPF: return NPFTrainChooseTrack(v, path_found, do_track_reservation, dest);
2388 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2390 default: NOT_REACHED();
2395 * Extend a train path as far as possible. Stops on encountering a safe tile,
2396 * another reservation or a track choice.
2397 * @return INVALID_TILE indicates that the reservation failed.
2399 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2401 PBSTileInfo origin = FollowTrainReservation(v);
2403 CFollowTrackRail ft(v);
2405 TileIndex tile = origin.tile;
2406 Trackdir cur_td = origin.trackdir;
2407 while (ft.Follow(tile, cur_td)) {
2408 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2409 /* Possible signal tile. */
2410 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2413 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2414 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2415 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2418 /* Station, depot or waypoint are a possible target. */
2419 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2420 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2421 /* Choice found or possible target encountered.
2422 * On finding a possible target, we need to stop and let the pathfinder handle the
2423 * remaining path. This is because we don't know if this target is in one of our
2424 * orders, so we might cause pathfinding to fail later on if we find a choice.
2425 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2426 * a wrong path not leading to our next destination. */
2427 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2429 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2430 * actually starts its search at the first unreserved tile. */
2431 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2433 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2434 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2435 if (enterdir != nullptr) *enterdir = ft.m_exitdir;
2436 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2439 tile = ft.m_new_tile;
2440 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2442 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2443 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2444 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2445 /* Safe position is all good, path valid and okay. */
2446 return PBSTileInfo(tile, cur_td, true);
2449 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2452 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2453 /* End of line, path valid and okay. */
2454 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2457 /* Sorry, can't reserve path, back out. */
2458 tile = origin.tile;
2459 cur_td = origin.trackdir;
2460 TileIndex stopped = ft.m_old_tile;
2461 Trackdir stopped_td = ft.m_old_td;
2462 while (tile != stopped || cur_td != stopped_td) {
2463 if (!ft.Follow(tile, cur_td)) break;
2465 if (Rail90DegTurnDisallowed(GetTileRailType(ft.m_old_tile), GetTileRailType(ft.m_new_tile))) {
2466 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2467 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2469 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2471 tile = ft.m_new_tile;
2472 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2474 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2477 /* Path invalid. */
2478 return PBSTileInfo();
2482 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2483 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2485 * @param v The vehicle.
2486 * @param tile The tile the search should start from.
2487 * @param td The trackdir the search should start from.
2488 * @param override_railtype Whether all physically compatible railtypes should be followed.
2489 * @return True if a path to a safe stopping tile could be reserved.
2491 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2493 switch (_settings_game.pf.pathfinder_for_trains) {
2494 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_railtype);
2495 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2497 default: NOT_REACHED();
2501 /** This class will save the current order of a vehicle and restore it on destruction. */
2502 class VehicleOrderSaver {
2503 private:
2504 Train *v;
2505 Order old_order;
2506 TileIndex old_dest_tile;
2507 StationID old_last_station_visited;
2508 VehicleOrderID index;
2509 bool suppress_implicit_orders;
2510 bool restored;
2512 public:
2513 VehicleOrderSaver(Train *_v) :
2514 v(_v),
2515 old_order(_v->current_order),
2516 old_dest_tile(_v->dest_tile),
2517 old_last_station_visited(_v->last_station_visited),
2518 index(_v->cur_real_order_index),
2519 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS)),
2520 restored(false)
2525 * Restore the saved order to the vehicle.
2527 void Restore()
2529 this->v->current_order = this->old_order;
2530 this->v->dest_tile = this->old_dest_tile;
2531 this->v->last_station_visited = this->old_last_station_visited;
2532 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2533 this->restored = true;
2537 * Restore the saved order to the vehicle, if Restore() has not already been called.
2539 ~VehicleOrderSaver()
2541 if (!this->restored) this->Restore();
2545 * Set the current vehicle order to the next order in the order list.
2546 * @param skip_first Shall the first (i.e. active) order be skipped?
2547 * @return True if a suitable next order could be found.
2549 bool SwitchToNextOrder(bool skip_first)
2551 if (this->v->GetNumOrders() == 0) return false;
2553 if (skip_first) ++this->index;
2555 int depth = 0;
2557 do {
2558 /* Wrap around. */
2559 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2561 Order *order = this->v->GetOrder(this->index);
2562 assert(order != nullptr);
2564 switch (order->GetType()) {
2565 case OT_GOTO_DEPOT:
2566 /* Skip service in depot orders when the train doesn't need service. */
2567 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2568 FALLTHROUGH;
2569 case OT_GOTO_STATION:
2570 case OT_GOTO_WAYPOINT:
2571 this->v->current_order = *order;
2572 return UpdateOrderDest(this->v, order, 0, true);
2573 case OT_CONDITIONAL: {
2574 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2575 if (next != INVALID_VEH_ORDER_ID) {
2576 depth++;
2577 this->index = next;
2578 /* Don't increment next, so no break here. */
2579 continue;
2581 break;
2583 default:
2584 break;
2586 /* Don't increment inside the while because otherwise conditional
2587 * orders can lead to an infinite loop. */
2588 ++this->index;
2589 depth++;
2590 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2592 return false;
2596 /* choose a track */
2597 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2599 Track best_track = INVALID_TRACK;
2600 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2601 bool changed_signal = false;
2602 TileIndex final_dest = INVALID_TILE;
2604 assert((tracks & ~TRACK_BIT_MASK) == 0);
2606 if (got_reservation != nullptr) *got_reservation = false;
2608 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2609 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2610 /* Do we have a suitable reserved track? */
2611 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2613 /* Quick return in case only one possible track is available */
2614 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2615 Track track = FindFirstTrack(tracks);
2616 /* We need to check for signals only here, as a junction tile can't have signals. */
2617 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2618 do_track_reservation = true;
2619 changed_signal = true;
2620 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2621 } else if (!do_track_reservation) {
2622 return track;
2624 best_track = track;
2627 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2628 DiagDirection dest_enterdir = enterdir;
2629 if (do_track_reservation) {
2630 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2631 if (res_dest.tile == INVALID_TILE) {
2632 /* Reservation failed? */
2633 if (mark_stuck) MarkTrainAsStuck(v);
2634 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2635 return FindFirstTrack(tracks);
2637 if (res_dest.okay) {
2638 /* Got a valid reservation that ends at a safe target, quick exit. */
2639 if (got_reservation != nullptr) *got_reservation = true;
2640 if (changed_signal) MarkTileDirtyByTile(tile);
2641 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2642 return best_track;
2645 /* Check if the train needs service here, so it has a chance to always find a depot.
2646 * Also check if the current order is a service order so we don't reserve a path to
2647 * the destination but instead to the next one if service isn't needed. */
2648 CheckIfTrainNeedsService(v);
2649 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2652 /* Save the current train order. The destructor will restore the old order on function exit. */
2653 VehicleOrderSaver orders(v);
2655 /* If the current tile is the destination of the current order and
2656 * a reservation was requested, advance to the next order.
2657 * Don't advance on a depot order as depots are always safe end points
2658 * for a path and no look-ahead is necessary. This also avoids a
2659 * problem with depot orders not part of the order list when the
2660 * order list itself is empty. */
2661 if (v->current_order.IsType(OT_LEAVESTATION)) {
2662 orders.SwitchToNextOrder(false);
2663 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2664 v->current_order.IsType(OT_GOTO_STATION) ?
2665 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2666 v->tile == v->dest_tile))) {
2667 orders.SwitchToNextOrder(true);
2670 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2671 /* Pathfinders are able to tell that route was only 'guessed'. */
2672 bool path_found = true;
2673 TileIndex new_tile = res_dest.tile;
2675 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2676 if (new_tile == tile) best_track = next_track;
2677 v->HandlePathfindingResult(path_found);
2680 /* No track reservation requested -> finished. */
2681 if (!do_track_reservation) return best_track;
2683 /* A path was found, but could not be reserved. */
2684 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2685 if (mark_stuck) MarkTrainAsStuck(v);
2686 FreeTrainTrackReservation(v);
2687 return best_track;
2690 /* No possible reservation target found, we are probably lost. */
2691 if (res_dest.tile == INVALID_TILE) {
2692 /* Try to find any safe destination. */
2693 PBSTileInfo origin = FollowTrainReservation(v);
2694 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2695 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2696 best_track = FindFirstTrack(res);
2697 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2698 if (got_reservation != nullptr) *got_reservation = true;
2699 if (changed_signal) MarkTileDirtyByTile(tile);
2700 } else {
2701 FreeTrainTrackReservation(v);
2702 if (mark_stuck) MarkTrainAsStuck(v);
2704 return best_track;
2707 if (got_reservation != nullptr) *got_reservation = true;
2709 /* Reservation target found and free, check if it is safe. */
2710 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2711 /* Extend reservation until we have found a safe position. */
2712 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2713 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2714 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
2715 if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2716 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2719 /* Get next order with destination. */
2720 if (orders.SwitchToNextOrder(true)) {
2721 PBSTileInfo cur_dest;
2722 bool path_found;
2723 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest, nullptr);
2724 if (cur_dest.tile != INVALID_TILE) {
2725 res_dest = cur_dest;
2726 if (res_dest.okay) continue;
2727 /* Path found, but could not be reserved. */
2728 FreeTrainTrackReservation(v);
2729 if (mark_stuck) MarkTrainAsStuck(v);
2730 if (got_reservation != nullptr) *got_reservation = false;
2731 changed_signal = false;
2732 break;
2735 /* No order or no safe position found, try any position. */
2736 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2737 FreeTrainTrackReservation(v);
2738 if (mark_stuck) MarkTrainAsStuck(v);
2739 if (got_reservation != nullptr) *got_reservation = false;
2740 changed_signal = false;
2742 break;
2745 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2747 if (changed_signal) MarkTileDirtyByTile(tile);
2749 orders.Restore();
2750 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
2751 (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) &&
2752 final_dest != INVALID_TILE && IsRailDepotTile(final_dest)) {
2753 v->current_order.SetDestination(GetDepotIndex(final_dest));
2754 v->dest_tile = final_dest;
2755 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2758 return best_track;
2762 * Try to reserve a path to a safe position.
2764 * @param v The vehicle
2765 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2766 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2767 * @return True if a path could be reserved.
2769 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2771 assert(v->IsFrontEngine());
2773 /* We have to handle depots specially as the track follower won't look
2774 * at the depot tile itself but starts from the next tile. If we are still
2775 * inside the depot, a depot reservation can never be ours. */
2776 if (v->track == TRACK_BIT_DEPOT) {
2777 if (HasDepotReservation(v->tile)) {
2778 if (mark_as_stuck) MarkTrainAsStuck(v);
2779 return false;
2780 } else {
2781 /* Depot not reserved, but the next tile might be. */
2782 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
2783 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2787 Vehicle *other_train = nullptr;
2788 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2789 /* The path we are driving on is already blocked by some other train.
2790 * This can only happen in certain situations when mixing path and
2791 * block signals or when changing tracks and/or signals.
2792 * Exit here as doing any further reservations will probably just
2793 * make matters worse. */
2794 if (other_train != nullptr && other_train->index != v->index) {
2795 if (mark_as_stuck) MarkTrainAsStuck(v);
2796 return false;
2798 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2799 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2800 /* Can't be stuck then. */
2801 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2802 ClrBit(v->flags, VRF_TRAIN_STUCK);
2803 return true;
2806 /* If we are in a depot, tentatively reserve the depot. */
2807 if (v->track == TRACK_BIT_DEPOT) {
2808 SetDepotReservation(v->tile, true);
2809 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2812 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2813 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2814 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
2816 if (Rail90DegTurnDisallowed(GetTileRailType(origin.tile), GetTileRailType(new_tile))) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
2818 bool res_made = false;
2819 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2821 if (!res_made) {
2822 /* Free the depot reservation as well. */
2823 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2824 return false;
2827 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2828 v->wait_counter = 0;
2829 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2831 ClrBit(v->flags, VRF_TRAIN_STUCK);
2832 return true;
2836 static bool CheckReverseTrain(const Train *v)
2838 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2839 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2840 !(v->direction & 1)) {
2841 return false;
2844 assert(v->track != TRACK_BIT_NONE);
2846 switch (_settings_game.pf.pathfinder_for_trains) {
2847 case VPF_NPF: return NPFTrainCheckReverse(v);
2848 case VPF_YAPF: return YapfTrainCheckReverse(v);
2850 default: NOT_REACHED();
2855 * Get the location of the next station to visit.
2856 * @param station Next station to visit.
2857 * @return Location of the new station.
2859 TileIndex Train::GetOrderStationLocation(StationID station)
2861 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2863 const Station *st = Station::Get(station);
2864 if (!(st->facilities & FACIL_TRAIN)) {
2865 /* The destination station has no trainstation tiles. */
2866 this->IncrementRealOrderIndex();
2867 return 0;
2870 return st->xy;
2873 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
2874 void Train::MarkDirty()
2876 Train *v = this;
2877 do {
2878 v->colourmap = PAL_NONE;
2879 v->UpdateViewport(true, false);
2880 } while ((v = v->Next()) != nullptr);
2882 /* need to update acceleration and cached values since the goods on the train changed. */
2883 this->CargoChanged();
2884 this->UpdateAcceleration();
2888 * This function looks at the vehicle and updates its speed (cur_speed
2889 * and subspeed) variables. Furthermore, it returns the distance that
2890 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2891 * the distance to drive before moving a step on the map.
2892 * @return distance to drive.
2894 int Train::UpdateSpeed()
2896 switch (_settings_game.vehicle.train_acceleration_model) {
2897 default: NOT_REACHED();
2898 case AM_ORIGINAL:
2899 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2901 case AM_REALISTIC:
2902 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2907 * Trains enters a station, send out a news item if it is the first train, and start loading.
2908 * @param v Train that entered the station.
2909 * @param station Station visited.
2911 static void TrainEnterStation(Train *v, StationID station)
2913 v->last_station_visited = station;
2915 /* check if a train ever visited this station before */
2916 Station *st = Station::Get(station);
2917 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2918 st->had_vehicle_of_type |= HVOT_TRAIN;
2919 SetDParam(0, st->index);
2920 AddVehicleNewsItem(
2921 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2922 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
2923 v->index,
2924 st->index
2926 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2927 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2930 v->force_proceed = TFP_NONE;
2931 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2933 v->BeginLoading();
2935 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
2936 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2939 /* Check if the vehicle is compatible with the specified tile */
2940 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2942 return IsTileOwner(tile, v->owner) &&
2943 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2946 /** Data structure for storing engine speed changes of an acceleration type. */
2947 struct AccelerationSlowdownParams {
2948 byte small_turn; ///< Speed change due to a small turn.
2949 byte large_turn; ///< Speed change due to a large turn.
2950 byte z_up; ///< Fraction to remove when moving up.
2951 byte z_down; ///< Fraction to add when moving down.
2954 /** Speed update fractions for each acceleration type. */
2955 static const AccelerationSlowdownParams _accel_slowdown[] = {
2956 /* normal accel */
2957 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
2958 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
2959 {0, 256 / 2, 256 / 4, 2}, ///< maglev
2963 * Modify the speed of the vehicle due to a change in altitude.
2964 * @param v %Train to update.
2965 * @param old_z Previous height.
2967 static inline void AffectSpeedByZChange(Train *v, int old_z)
2969 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2971 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2973 if (old_z < v->z_pos) {
2974 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2975 } else {
2976 uint16 spd = v->cur_speed + asp->z_down;
2977 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2981 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
2983 if (IsTileType(tile, MP_RAILWAY) &&
2984 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
2985 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
2986 Trackdir trackdir = FindFirstTrackdir(tracks);
2987 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
2988 /* A PBS block with a non-PBS signal facing us? */
2989 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
2992 return false;
2995 /** Tries to reserve track under whole train consist. */
2996 void Train::ReserveTrackUnderConsist() const
2998 for (const Train *u = this; u != nullptr; u = u->Next()) {
2999 switch (u->track) {
3000 case TRACK_BIT_WORMHOLE:
3001 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3002 break;
3003 case TRACK_BIT_DEPOT:
3004 break;
3005 default:
3006 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3007 break;
3013 * The train vehicle crashed!
3014 * Update its status and other parts around it.
3015 * @param flooded Crash was caused by flooding.
3016 * @return Number of people killed.
3018 uint Train::Crash(bool flooded)
3020 uint pass = 0;
3021 if (this->IsFrontEngine()) {
3022 pass += 2; // driver
3024 /* Remove the reserved path in front of the train if it is not stuck.
3025 * Also clear all reserved tracks the train is currently on. */
3026 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3027 for (const Train *v = this; v != nullptr; v = v->Next()) {
3028 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3029 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3030 /* ClearPathReservation will not free the wormhole exit
3031 * if the train has just entered the wormhole. */
3032 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
3036 /* we may need to update crossing we were approaching,
3037 * but must be updated after the train has been marked crashed */
3038 TileIndex crossing = TrainApproachingCrossingTile(this);
3039 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3041 /* Remove the loading indicators (if any) */
3042 HideFillingPercent(&this->fill_percent_te_id);
3045 pass += this->GroundVehicleBase::Crash(flooded);
3047 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3048 return pass;
3052 * Marks train as crashed and creates an AI event.
3053 * Doesn't do anything if the train is crashed already.
3054 * @param v first vehicle of chain
3055 * @return number of victims (including 2 drivers; zero if train was already crashed)
3057 static uint TrainCrashed(Train *v)
3059 uint num = 0;
3061 /* do not crash train twice */
3062 if (!(v->vehstatus & VS_CRASHED)) {
3063 num = v->Crash();
3064 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3065 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3068 /* Try to re-reserve track under already crashed train too.
3069 * Crash() clears the reservation! */
3070 v->ReserveTrackUnderConsist();
3072 return num;
3075 /** Temporary data storage for testing collisions. */
3076 struct TrainCollideChecker {
3077 Train *v; ///< %Vehicle we are testing for collision.
3078 uint num; ///< Total number of victims if train collided.
3082 * Collision test function.
3083 * @param v %Train vehicle to test collision with.
3084 * @param data %Train being examined.
3085 * @return \c nullptr (always continue search)
3087 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3089 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3091 /* not a train or in depot */
3092 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
3094 /* do not crash into trains of another company. */
3095 if (v->owner != tcc->v->owner) return nullptr;
3097 /* get first vehicle now to make most usual checks faster */
3098 Train *coll = Train::From(v)->First();
3100 /* can't collide with own wagons */
3101 if (coll == tcc->v) return nullptr;
3103 int x_diff = v->x_pos - tcc->v->x_pos;
3104 int y_diff = v->y_pos - tcc->v->y_pos;
3106 /* Do fast calculation to check whether trains are not in close vicinity
3107 * and quickly reject trains distant enough for any collision.
3108 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3109 * Differences are then ORed and then we check for any higher bits */
3110 uint hash = (y_diff + 7) | (x_diff + 7);
3111 if (hash & ~15) return nullptr;
3113 /* Slower check using multiplication */
3114 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3115 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return nullptr;
3117 /* Happens when there is a train under bridge next to bridge head */
3118 if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
3120 /* crash both trains */
3121 tcc->num += TrainCrashed(tcc->v);
3122 tcc->num += TrainCrashed(coll);
3124 return nullptr; // continue searching
3128 * Checks whether the specified train has a collision with another vehicle. If
3129 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3130 * Reports the incident in a flashy news item, modifies station ratings and
3131 * plays a sound.
3132 * @param v %Train to test.
3134 static bool CheckTrainCollision(Train *v)
3136 /* can't collide in depot */
3137 if (v->track == TRACK_BIT_DEPOT) return false;
3139 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3141 TrainCollideChecker tcc;
3142 tcc.v = v;
3143 tcc.num = 0;
3145 /* find colliding vehicles */
3146 if (v->track == TRACK_BIT_WORMHOLE) {
3147 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3148 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3149 } else {
3150 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3153 /* any dead -> no crash */
3154 if (tcc.num == 0) return false;
3156 SetDParam(0, tcc.num);
3157 AddTileNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->tile);
3159 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3160 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3161 return true;
3164 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3166 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
3168 Train *t = Train::From(v);
3169 DiagDirection exitdir = *(DiagDirection *)data;
3171 /* not front engine of a train, inside wormhole or depot, crashed */
3172 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
3174 if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return nullptr;
3176 return t;
3180 * Move a vehicle chain one movement stop forwards.
3181 * @param v First vehicle to move.
3182 * @param nomove Stop moving this and all following vehicles.
3183 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3184 * @return True if the vehicle could be moved forward, false otherwise.
3186 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3188 Train *first = v->First();
3189 Train *prev;
3190 bool direction_changed = false; // has direction of any part changed?
3192 /* For every vehicle after and including the given vehicle */
3193 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3194 DiagDirection enterdir = DIAGDIR_BEGIN;
3195 bool update_signals_crossing = false; // will we update signals or crossing state?
3197 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3198 if (v->track != TRACK_BIT_WORMHOLE) {
3199 /* Not inside tunnel */
3200 if (gp.old_tile == gp.new_tile) {
3201 /* Staying in the old tile */
3202 if (v->track == TRACK_BIT_DEPOT) {
3203 /* Inside depot */
3204 gp.x = v->x_pos;
3205 gp.y = v->y_pos;
3206 } else {
3207 /* Not inside depot */
3209 /* Reverse when we are at the end of the track already, do not move to the new position */
3210 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3212 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3213 if (HasBit(r, VETS_CANNOT_ENTER)) {
3214 goto invalid_rail;
3216 if (HasBit(r, VETS_ENTERED_STATION)) {
3217 /* The new position is the end of the platform */
3218 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3221 } else {
3222 /* A new tile is about to be entered. */
3224 /* Determine what direction we're entering the new tile from */
3225 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3226 assert(IsValidDiagDirection(enterdir));
3228 /* Get the status of the tracks in the new tile and mask
3229 * away the bits that aren't reachable. */
3230 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3231 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3233 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3234 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3236 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3237 if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3238 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3239 * can be switched on halfway a turn */
3240 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3243 if (bits == TRACK_BIT_NONE) goto invalid_rail;
3245 /* Check if the new tile constrains tracks that are compatible
3246 * with the current train, if not, bail out. */
3247 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3249 TrackBits chosen_track;
3250 if (prev == nullptr) {
3251 /* Currently the locomotive is active. Determine which one of the
3252 * available tracks to choose */
3253 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3254 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3256 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3257 /* For each signal we find decrease the counter by one.
3258 * We start at two, so the first signal we pass decreases
3259 * this to one, then if we reach the next signal it is
3260 * decreased to zero and we won't pass that new signal. */
3261 Trackdir dir = FindFirstTrackdir(trackdirbits);
3262 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3263 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3264 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3265 /* However, we do not want to be stopped by PBS signals
3266 * entered via the back. */
3267 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3268 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3272 /* Check if it's a red signal and that force proceed is not clicked. */
3273 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3274 /* In front of a red signal */
3275 Trackdir i = FindFirstTrackdir(trackdirbits);
3277 /* Don't handle stuck trains here. */
3278 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3280 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3281 v->cur_speed = 0;
3282 v->subspeed = 0;
3283 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3284 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * DAY_TICKS * 2) return false;
3285 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3286 v->cur_speed = 0;
3287 v->subspeed = 0;
3288 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3289 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * DAY_TICKS * 2) {
3290 DiagDirection exitdir = TrackdirToExitdir(i);
3291 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3293 exitdir = ReverseDiagDir(exitdir);
3295 /* check if a train is waiting on the other side */
3296 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3300 /* If we would reverse but are currently in a PBS block and
3301 * reversing of stuck trains is disabled, don't reverse.
3302 * This does not apply if the reason for reversing is a one-way
3303 * signal blocking us, because a train would then be stuck forever. */
3304 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3305 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3306 v->wait_counter = 0;
3307 return false;
3309 goto reverse_train_direction;
3310 } else {
3311 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3313 } else {
3314 /* The wagon is active, simply follow the prev vehicle. */
3315 if (prev->tile == gp.new_tile) {
3316 /* Choose the same track as prev */
3317 if (prev->track == TRACK_BIT_WORMHOLE) {
3318 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3319 * However, just choose the track into the wormhole. */
3320 assert(IsTunnel(prev->tile));
3321 chosen_track = bits;
3322 } else {
3323 chosen_track = prev->track;
3325 } else {
3326 /* Choose the track that leads to the tile where prev is.
3327 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3328 * I.e. when the tile between them has only space for a single vehicle like
3329 * 1) horizontal/vertical track tiles and
3330 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3331 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3333 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3334 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3335 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3336 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3337 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3339 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3340 assert(IsValidDiagDirection(exitdir));
3341 chosen_track = _connecting_track[enterdir][exitdir];
3343 chosen_track &= bits;
3346 /* Make sure chosen track is a valid track */
3347 assert(
3348 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3349 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3350 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3352 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3353 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3354 gp.x = (gp.x & ~0xF) | b[0];
3355 gp.y = (gp.y & ~0xF) | b[1];
3356 Direction chosen_dir = (Direction)b[2];
3358 /* Call the landscape function and tell it that the vehicle entered the tile */
3359 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3360 if (HasBit(r, VETS_CANNOT_ENTER)) {
3361 goto invalid_rail;
3364 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3365 Track track = FindFirstTrack(chosen_track);
3366 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3367 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3368 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3369 MarkTileDirtyByTile(gp.new_tile);
3372 /* Clear any track reservation when the last vehicle leaves the tile */
3373 if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3375 v->tile = gp.new_tile;
3377 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3378 v->First()->ConsistChanged(CCF_TRACK);
3381 v->track = chosen_track;
3382 assert(v->track);
3385 /* We need to update signal status, but after the vehicle position hash
3386 * has been updated by UpdateInclination() */
3387 update_signals_crossing = true;
3389 if (chosen_dir != v->direction) {
3390 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3391 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3392 DirDiff diff = DirDifference(v->direction, chosen_dir);
3393 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3395 direction_changed = true;
3396 v->direction = chosen_dir;
3399 if (v->IsFrontEngine()) {
3400 v->wait_counter = 0;
3402 /* If we are approaching a crossing that is reserved, play the sound now. */
3403 TileIndex crossing = TrainApproachingCrossingTile(v);
3404 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3406 /* Always try to extend the reservation when entering a tile. */
3407 CheckNextTrainTile(v);
3410 if (HasBit(r, VETS_ENTERED_STATION)) {
3411 /* The new position is the location where we want to stop */
3412 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3415 } else {
3416 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
3417 /* Perform look-ahead on tunnel exit. */
3418 if (v->IsFrontEngine()) {
3419 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
3420 CheckNextTrainTile(v);
3422 /* Prevent v->UpdateInclination() being called with wrong parameters.
3423 * This could happen if the train was reversed inside the tunnel/bridge. */
3424 if (gp.old_tile == gp.new_tile) {
3425 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
3427 } else {
3428 v->x_pos = gp.x;
3429 v->y_pos = gp.y;
3430 v->UpdatePosition();
3431 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3432 continue;
3436 /* update image of train, as well as delta XY */
3437 v->UpdateDeltaXY();
3439 v->x_pos = gp.x;
3440 v->y_pos = gp.y;
3441 v->UpdatePosition();
3443 /* update the Z position of the vehicle */
3444 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3446 if (prev == nullptr) {
3447 /* This is the first vehicle in the train */
3448 AffectSpeedByZChange(v, old_z);
3451 if (update_signals_crossing) {
3452 if (v->IsFrontEngine()) {
3453 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3454 /* We are entering a block with PBS signals right now, but
3455 * not through a PBS signal. This means we don't have a
3456 * reservation right now. As a conventional signal will only
3457 * ever be green if no other train is in the block, getting
3458 * a path should always be possible. If the player built
3459 * such a strange network that it is not possible, the train
3460 * will be marked as stuck and the player has to deal with
3461 * the problem. */
3462 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3463 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3464 !TryPathReserve(v)) {
3465 MarkTrainAsStuck(v);
3470 /* Signals can only change when the first
3471 * (above) or the last vehicle moves. */
3472 if (v->Next() == nullptr) {
3473 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3474 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
3478 /* Do not check on every tick to save some computing time. */
3479 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3482 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3484 return true;
3486 invalid_rail:
3487 /* We've reached end of line?? */
3488 if (prev != nullptr) error("Disconnecting train");
3490 reverse_train_direction:
3491 if (reverse) {
3492 v->wait_counter = 0;
3493 v->cur_speed = 0;
3494 v->subspeed = 0;
3495 ReverseTrainDirection(v);
3498 return false;
3502 * Collect trackbits of all crashed train vehicles on a tile
3503 * @param v Vehicle passed from Find/HasVehicleOnPos()
3504 * @param data trackdirbits for the result
3505 * @return nullptr to iterate over all vehicles on the tile.
3507 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
3509 TrackBits *trackbits = (TrackBits *)data;
3511 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3512 TrackBits train_tbits = Train::From(v)->track;
3513 if (train_tbits == TRACK_BIT_WORMHOLE) {
3514 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3515 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
3516 } else if (train_tbits != TRACK_BIT_DEPOT) {
3517 *trackbits |= train_tbits;
3521 return nullptr;
3525 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3526 * train, then goes to the last wagon and deletes that. Each call to this function
3527 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3528 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3529 * @param v the Vehicle of which last wagon is to be removed
3531 static void DeleteLastWagon(Train *v)
3533 Train *first = v->First();
3535 /* Go to the last wagon and delete the link pointing there
3536 * *u is then the one-before-last wagon, and *v the last
3537 * one which will physically be removed */
3538 Train *u = v;
3539 for (; v->Next() != nullptr; v = v->Next()) u = v;
3540 u->SetNext(nullptr);
3542 if (first != v) {
3543 /* Recalculate cached train properties */
3544 first->ConsistChanged(CCF_ARRANGE);
3545 /* Update the depot window if the first vehicle is in depot -
3546 * if v == first, then it is updated in PreDestructor() */
3547 if (first->track == TRACK_BIT_DEPOT) {
3548 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3550 v->last_station_visited = first->last_station_visited; // for PreDestructor
3553 /* 'v' shouldn't be accessed after it has been deleted */
3554 TrackBits trackbits = v->track;
3555 TileIndex tile = v->tile;
3556 Owner owner = v->owner;
3558 delete v;
3559 v = nullptr; // make sure nobody will try to read 'v' anymore
3561 if (trackbits == TRACK_BIT_WORMHOLE) {
3562 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3563 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
3566 Track track = TrackBitsToTrack(trackbits);
3567 if (HasReservedTracks(tile, trackbits)) {
3568 UnreserveRailTrack(tile, track);
3570 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3571 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3572 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3574 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3575 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3576 for (Track t : SetTrackBitIterator(remaining_trackbits)) TryReserveRailTrack(tile, t);
3579 /* check if the wagon was on a road/rail-crossing */
3580 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3582 /* Update signals */
3583 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3584 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
3585 } else {
3586 SetSignalsOnBothDir(tile, track, owner);
3591 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3592 * @param v First crashed vehicle.
3594 static void ChangeTrainDirRandomly(Train *v)
3596 static const DirDiff delta[] = {
3597 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3600 do {
3601 /* We don't need to twist around vehicles if they're not visible */
3602 if (!(v->vehstatus & VS_HIDDEN)) {
3603 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3604 /* Refrain from updating the z position of the vehicle when on
3605 * a bridge, because UpdateInclination() will put the vehicle under
3606 * the bridge in that case */
3607 if (v->track != TRACK_BIT_WORMHOLE) {
3608 v->UpdatePosition();
3609 v->UpdateInclination(false, true);
3610 } else {
3611 v->UpdateViewport(false, true);
3614 } while ((v = v->Next()) != nullptr);
3618 * Handle a crashed train.
3619 * @param v First train vehicle.
3620 * @return %Vehicle chain still exists.
3622 static bool HandleCrashedTrain(Train *v)
3624 int state = ++v->crash_anim_pos;
3626 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3627 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3630 uint32 r;
3631 if (state <= 200 && Chance16R(1, 7, r)) {
3632 int index = (r * 10 >> 16);
3634 Vehicle *u = v;
3635 do {
3636 if (--index < 0) {
3637 r = Random();
3639 CreateEffectVehicleRel(u,
3640 GB(r, 8, 3) + 2,
3641 GB(r, 16, 3) + 2,
3642 GB(r, 0, 3) + 5,
3643 EV_EXPLOSION_SMALL);
3644 break;
3646 } while ((u = u->Next()) != nullptr);
3649 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3651 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3652 bool ret = v->Next() != nullptr;
3653 DeleteLastWagon(v);
3654 return ret;
3657 return true;
3660 /** Maximum speeds for train that is broken down or approaching line end */
3661 static const uint16 _breakdown_speeds[16] = {
3662 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3667 * Train is approaching line end, slow down and possibly reverse
3669 * @param v front train engine
3670 * @param signal not line end, just a red signal
3671 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3672 * @return true iff we did NOT have to reverse
3674 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3676 /* Calc position within the current tile */
3677 uint x = v->x_pos & 0xF;
3678 uint y = v->y_pos & 0xF;
3680 /* for diagonal directions, 'x' will be 0..15 -
3681 * for other directions, it will be 1, 3, 5, ..., 15 */
3682 switch (v->direction) {
3683 case DIR_N : x = ~x + ~y + 25; break;
3684 case DIR_NW: x = y; FALLTHROUGH;
3685 case DIR_NE: x = ~x + 16; break;
3686 case DIR_E : x = ~x + y + 9; break;
3687 case DIR_SE: x = y; break;
3688 case DIR_S : x = x + y - 7; break;
3689 case DIR_W : x = ~y + x + 9; break;
3690 default: break;
3693 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3694 * does not cross the tile boundary when we do reverse, but as the vehicle's
3695 * location is based on their center, use half a vehicle's length as offset.
3696 * Multiply the half-length by two for straight directions to compensate that
3697 * we only get odd x offsets there. */
3698 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3699 /* we are too near the tile end, reverse now */
3700 v->cur_speed = 0;
3701 if (reverse) ReverseTrainDirection(v);
3702 return false;
3705 /* slow down */
3706 v->vehstatus |= VS_TRAIN_SLOWING;
3707 uint16 break_speed = _breakdown_speeds[x & 0xF];
3708 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3710 return true;
3715 * Determines whether train would like to leave the tile
3716 * @param v train to test
3717 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
3719 static bool TrainCanLeaveTile(const Train *v)
3721 /* Exit if inside a tunnel/bridge or a depot */
3722 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3724 TileIndex tile = v->tile;
3726 /* entering a tunnel/bridge? */
3727 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3728 DiagDirection dir = GetTunnelBridgeDirection(tile);
3729 if (DiagDirToDir(dir) == v->direction) return false;
3732 /* entering a depot? */
3733 if (IsRailDepotTile(tile)) {
3734 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
3735 if (DiagDirToDir(dir) == v->direction) return false;
3738 return true;
3743 * Determines whether train is approaching a rail-road crossing
3744 * (thus making it barred)
3745 * @param v front engine of train
3746 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
3747 * @pre v in non-crashed front engine
3749 static TileIndex TrainApproachingCrossingTile(const Train *v)
3751 assert(v->IsFrontEngine());
3752 assert(!(v->vehstatus & VS_CRASHED));
3754 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3756 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3757 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3759 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3760 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3761 !CheckCompatibleRail(v, tile)) {
3762 return INVALID_TILE;
3765 return tile;
3770 * Checks for line end. Also, bars crossing at next tile if needed
3772 * @param v vehicle we are checking
3773 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3774 * @return true iff we did NOT have to reverse
3776 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3778 /* First, handle broken down train */
3780 int t = v->breakdown_ctr;
3781 if (t > 1) {
3782 v->vehstatus |= VS_TRAIN_SLOWING;
3784 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3785 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3786 } else {
3787 v->vehstatus &= ~VS_TRAIN_SLOWING;
3790 if (!TrainCanLeaveTile(v)) return true;
3792 /* Determine the non-diagonal direction in which we will exit this tile */
3793 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3794 /* Calculate next tile */
3795 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3797 /* Determine the track status on the next tile */
3798 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3799 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3801 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3802 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3804 /* We are sure the train is not entering a depot, it is detected above */
3806 /* mask unreachable track bits if we are forbidden to do 90deg turns */
3807 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3808 if (Rail90DegTurnDisallowed(GetTileRailType(v->tile), GetTileRailType(tile))) {
3809 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3812 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3813 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3814 return TrainApproachingLineEnd(v, false, reverse);
3817 /* approaching red signal */
3818 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3820 /* approaching a rail/road crossing? then make it red */
3821 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
3823 return true;
3827 static bool TrainLocoHandler(Train *v, bool mode)
3829 /* train has crashed? */
3830 if (v->vehstatus & VS_CRASHED) {
3831 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3834 if (v->force_proceed != TFP_NONE) {
3835 ClrBit(v->flags, VRF_TRAIN_STUCK);
3836 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3839 /* train is broken down? */
3840 if (v->HandleBreakdown()) return true;
3842 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3843 ReverseTrainDirection(v);
3846 /* exit if train is stopped */
3847 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3849 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3850 if (ProcessOrders(v) && CheckReverseTrain(v)) {
3851 v->wait_counter = 0;
3852 v->cur_speed = 0;
3853 v->subspeed = 0;
3854 ClrBit(v->flags, VRF_LEAVING_STATION);
3855 ReverseTrainDirection(v);
3856 return true;
3857 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3858 /* Try to reserve a path when leaving the station as we
3859 * might not be marked as wanting a reservation, e.g.
3860 * when an overlength train gets turned around in a station. */
3861 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3862 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
3864 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
3865 TryPathReserve(v, true, true);
3867 ClrBit(v->flags, VRF_LEAVING_STATION);
3870 v->HandleLoading(mode);
3872 if (v->current_order.IsType(OT_LOADING)) return true;
3874 if (CheckTrainStayInDepot(v)) return true;
3876 if (!mode) v->ShowVisualEffect();
3878 /* We had no order but have an order now, do look ahead. */
3879 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3880 CheckNextTrainTile(v);
3883 /* Handle stuck trains. */
3884 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3885 ++v->wait_counter;
3887 /* Should we try reversing this tick if still stuck? */
3888 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
3890 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3891 if (!TryPathReserve(v)) {
3892 /* Still stuck. */
3893 if (turn_around) ReverseTrainDirection(v);
3895 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
3896 /* Show message to player. */
3897 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
3898 SetDParam(0, v->index);
3899 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3901 v->wait_counter = 0;
3903 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3904 if (v->force_proceed == TFP_NONE) return true;
3905 ClrBit(v->flags, VRF_TRAIN_STUCK);
3906 v->wait_counter = 0;
3907 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3911 if (v->current_order.IsType(OT_LEAVESTATION)) {
3912 v->current_order.Free();
3913 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3914 return true;
3917 int j = v->UpdateSpeed();
3919 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3920 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3921 /* If we manually stopped, we're not force-proceeding anymore. */
3922 v->force_proceed = TFP_NONE;
3923 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3926 int adv_spd = v->GetAdvanceDistance();
3927 if (j < adv_spd) {
3928 /* if the vehicle has speed 0, update the last_speed field. */
3929 if (v->cur_speed == 0) v->SetLastSpeed();
3930 } else {
3931 TrainCheckIfLineEnds(v);
3932 /* Loop until the train has finished moving. */
3933 for (;;) {
3934 j -= adv_spd;
3935 TrainController(v, nullptr);
3936 /* Don't continue to move if the train crashed. */
3937 if (CheckTrainCollision(v)) break;
3938 /* Determine distance to next map position */
3939 adv_spd = v->GetAdvanceDistance();
3941 /* No more moving this tick */
3942 if (j < adv_spd || v->cur_speed == 0) break;
3944 OrderType order_type = v->current_order.GetType();
3945 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3946 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3947 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
3948 IsTileType(v->tile, MP_STATION) &&
3949 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
3950 ProcessOrders(v);
3953 v->SetLastSpeed();
3956 for (Train *u = v; u != nullptr; u = u->Next()) {
3957 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3959 u->UpdateViewport(false, false);
3962 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
3964 return true;
3968 * Get running cost for the train consist.
3969 * @return Yearly running costs.
3971 Money Train::GetRunningCost() const
3973 Money cost = 0;
3974 const Train *v = this;
3976 do {
3977 const Engine *e = v->GetEngine();
3978 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
3980 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
3981 if (cost_factor == 0) continue;
3983 /* Halve running cost for multiheaded parts */
3984 if (v->IsMultiheaded()) cost_factor /= 2;
3986 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
3987 } while ((v = v->GetNextVehicle()) != nullptr);
3989 return cost;
3993 * Update train vehicle data for a tick.
3994 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
3996 bool Train::Tick()
3998 this->tick_counter++;
4000 if (this->IsFrontEngine()) {
4001 PerformanceAccumulator framerate(PFE_GL_TRAINS);
4003 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
4005 this->current_order_time++;
4007 if (!TrainLocoHandler(this, false)) return false;
4009 return TrainLocoHandler(this, true);
4010 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4011 /* Delete flooded standalone wagon chain */
4012 if (++this->crash_anim_pos >= 4400) {
4013 delete this;
4014 return false;
4018 return true;
4022 * Check whether a train needs service, and if so, find a depot or service it.
4023 * @return v %Train to check.
4025 static void CheckIfTrainNeedsService(Train *v)
4027 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4028 if (v->IsChainInDepot()) {
4029 VehicleServiceInDepot(v);
4030 return;
4033 uint max_penalty;
4034 switch (_settings_game.pf.pathfinder_for_trains) {
4035 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
4036 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
4037 default: NOT_REACHED();
4040 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4041 /* Only go to the depot if it is not too far out of our way. */
4042 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4043 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4044 /* If we were already heading for a depot but it has
4045 * suddenly moved farther away, we continue our normal
4046 * schedule? */
4047 v->current_order.MakeDummy();
4048 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4050 return;
4053 DepotID depot = GetDepotIndex(tfdd.tile);
4055 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4056 v->current_order.GetDestination() != depot &&
4057 !Chance16(3, 16)) {
4058 return;
4061 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4062 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE, ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, ODATFB_NEAREST_DEPOT);
4063 v->dest_tile = tfdd.tile;
4064 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4067 /** Update day counters of the train vehicle. */
4068 void Train::OnNewDay()
4070 AgeVehicle(this);
4072 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4074 if (this->IsFrontEngine()) {
4075 CheckVehicleBreakdown(this);
4077 CheckIfTrainNeedsService(this);
4079 CheckOrders(this);
4081 /* update destination */
4082 if (this->current_order.IsType(OT_GOTO_STATION)) {
4083 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4084 if (tile != INVALID_TILE) this->dest_tile = tile;
4087 if (this->running_ticks != 0) {
4088 /* running costs */
4089 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4091 this->profit_this_year -= cost.GetCost();
4092 this->running_ticks = 0;
4094 SubtractMoneyFromCompanyFract(this->owner, cost);
4096 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4097 SetWindowClassesDirty(WC_TRAINS_LIST);
4103 * Get the tracks of the train vehicle.
4104 * @return Current tracks of the vehicle.
4106 Trackdir Train::GetVehicleTrackdir() const
4108 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4110 if (this->track == TRACK_BIT_DEPOT) {
4111 /* We'll assume the train is facing outwards */
4112 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4115 if (this->track == TRACK_BIT_WORMHOLE) {
4116 /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4117 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4120 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);