Fix some daylength issues, possible division by zero in main menu.
[openttd-joker.git] / src / train_cmd.cpp
blobece9fea79c0b785317bcc51ac31eb44defd1f28a
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file train_cmd.cpp Handling of trains. */
12 #include "stdafx.h"
13 #include "error.h"
14 #include "articulated_vehicles.h"
15 #include "command_func.h"
16 #include "pathfinder/npf/npf_func.h"
17 #include "pathfinder/yapf/yapf.hpp"
18 #include "news_func.h"
19 #include "company_func.h"
20 #include "newgrf_sound.h"
21 #include "newgrf_text.h"
22 #include "strings_func.h"
23 #include "viewport_func.h"
24 #include "vehicle_func.h"
25 #include "sound_func.h"
26 #include "ai/ai.hpp"
27 #include "game/game.hpp"
28 #include "newgrf_station.h"
29 #include "effectvehicle_func.h"
30 #include "network/network.h"
31 #include "spritecache.h"
32 #include "core/random_func.hpp"
33 #include "company_base.h"
34 #include "newgrf.h"
35 #include "order_backup.h"
36 #include "zoom_func.h"
37 #include "newgrf_debug.h"
38 #include "tracerestrict.h"
39 #include "logic_signals.h"
40 #include "tbtr_template_vehicle_func.h"
41 #include "autoreplace_func.h"
42 #include "bridge_signal_map.h"
43 #include "tunnelbridge.h"
45 #include "table/strings.h"
46 #include "table/train_cmd.h"
48 #include "engine_func.h"
50 #include "safeguards.h"
52 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
53 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse);
54 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
55 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
56 static TileIndex TrainApproachingCrossingTile(const Train *v);
57 static void CheckIfTrainNeedsService(Train *v);
58 static void CheckNextTrainTile(Train *v);
60 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
61 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
63 template <>
64 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
66 return image_index < lengthof(_engine_sprite_base);
69 /**
70 * Determine the side in which the train will leave the tile
72 * @param direction vehicle direction
73 * @param track vehicle track bits
74 * @return side of tile the train will leave
76 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
78 static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
80 DiagDirection diagdir = DirToDiagDir(direction);
82 /* Determine the diagonal direction in which we will exit this tile */
83 if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
84 diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
87 return diagdir;
91 /**
92 * Return the cargo weight multiplier to use for a rail vehicle
93 * @param cargo Cargo type to get multiplier for
94 * @return Cargo weight multiplier
96 byte FreightWagonMult(CargoID cargo)
98 if (!CargoSpec::Get(cargo)->is_freight) return 1;
99 return _settings_game.vehicle.freight_trains;
102 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
103 void CheckTrainsLengths()
105 const Train *v;
106 bool first = true;
108 FOR_ALL_TRAINS(v) {
109 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
110 for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
111 if (u->track != TRACK_BIT_DEPOT) {
112 if ((w->track != TRACK_BIT_DEPOT &&
113 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
114 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
115 SetDParam(0, v->index);
116 SetDParam(1, v->owner);
117 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
119 if (!_networking && first) {
120 first = false;
121 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
123 /* Break so we warn only once for each train. */
124 break;
133 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
134 * to/removed from the chain, and when the game is loaded.
135 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
136 * @param allowed_changes Stuff that is allowed to change.
138 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
140 uint16 max_speed = UINT16_MAX;
142 assert(this->IsFrontEngine() || this->IsFreeWagon());
144 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
145 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
146 this->gcache.cached_total_length = 0;
147 this->compatible_railtypes = RAILTYPES_NONE;
149 bool train_can_tilt = true;
151 for (Train *u = this; u != NULL; u = u->Next()) {
152 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
154 /* Check the this->first cache. */
155 assert(u->First() == this);
157 /* update the 'first engine' */
158 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
159 u->railtype = rvi_u->railtype;
161 if (u->IsEngine()) first_engine = u->engine_type;
163 /* Set user defined data to its default value */
164 u->tcache.user_def_data = rvi_u->user_def_data;
165 this->InvalidateNewGRFCache();
166 u->InvalidateNewGRFCache();
169 for (Train *u = this; u != NULL; u = u->Next()) {
170 /* Update user defined data (must be done before other properties) */
171 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
172 this->InvalidateNewGRFCache();
173 u->InvalidateNewGRFCache();
176 for (Train *u = this; u != NULL; u = u->Next()) {
177 const Engine *e_u = u->GetEngine();
178 const RailVehicleInfo *rvi_u = &e_u->u.rail;
180 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
182 /* Cache wagon override sprite group. NULL is returned if there is none */
183 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
185 /* Reset colour map */
186 u->colourmap = PAL_NONE;
188 RailType rt = u->railtype;
190 /* Update powered-wagon-status and visual effect */
191 u->UpdateVisualEffect(true);
193 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
194 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
195 /* wagon is powered */
196 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
197 } else {
198 ClrBit(u->flags, VRF_POWEREDWAGON);
201 if (!u->IsArticulatedPart()) {
202 /* Do not count powered wagons for the compatible railtypes, as wagons always
203 have railtype normal */
204 if (rvi_u->power > 0) {
205 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
208 /* Some electric engines can be allowed to run on normal rail. It happens to all
209 * existing electric engines when elrails are disabled and then re-enabled */
210 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
211 u->railtype = RAILTYPE_RAIL;
212 u->compatible_railtypes |= RAILTYPES_RAIL;
215 /* max speed is the minimum of the speed limits of all vehicles in the consist */
216 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
217 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
218 if (speed != 0) max_speed = min(speed, max_speed);
222 uint16 new_cap = e_u->DetermineCapacity(u);
223 if (allowed_changes & CCF_CAPACITY) {
224 /* Update vehicle capacity. */
225 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
226 u->refit_cap = min(new_cap, u->refit_cap);
227 u->cargo_cap = new_cap;
228 } else {
229 /* Verify capacity hasn't changed. */
230 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
232 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
234 /* check the vehicle length (callback) */
235 uint16 veh_len = CALLBACK_FAILED;
236 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
237 /* Use callback 36 */
238 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
240 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
241 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
243 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
244 /* Use callback 11 */
245 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
247 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
248 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
250 if (allowed_changes & CCF_LENGTH) {
251 /* Update vehicle length. */
252 u->gcache.cached_veh_length = veh_len;
253 } else {
254 /* Verify length hasn't changed. */
255 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
258 this->gcache.cached_total_length += u->gcache.cached_veh_length;
259 this->InvalidateNewGRFCache();
260 u->InvalidateNewGRFCache();
263 /* store consist weight/max speed in cache */
264 this->vcache.cached_max_speed = max_speed;
265 this->tcache.cached_tilt = train_can_tilt;
266 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
268 /* 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) */
269 this->CargoChanged();
271 if (this->IsFrontEngine()) {
272 this->UpdateAcceleration();
273 if ( !HasBit(this->subtype, GVSF_VIRTUAL) ) SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
274 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
275 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
276 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
281 * Get the stop location of (the center) of the front vehicle of a train at
282 * a platform of a station.
283 * @param station_id the ID of the station where we're stopping
284 * @param tile the tile where the vehicle currently is
285 * @param v the vehicle to get the stop location of
286 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
287 * @param station_length 'return' the station length in 1/16th tiles
288 * @return the location, calculated from the begin of the station to stop at.
290 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
292 const Station *st = Station::Get(station_id);
293 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
294 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
296 /* Default to the middle of the station for stations stops that are not in
297 * the order list like intermediate stations when non-stop is disabled */
298 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
299 if (v->gcache.cached_total_length >= *station_length) {
300 /* The train is longer than the station, make it stop at the far end of the platform */
301 osl = OSL_PLATFORM_FAR_END;
302 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
303 osl = v->current_order.GetStopLocation();
306 /* The stop location of the FRONT! of the train */
307 int stop;
308 switch (osl) {
309 default: NOT_REACHED();
311 case OSL_PLATFORM_NEAR_END:
312 stop = v->gcache.cached_total_length;
313 break;
315 case OSL_PLATFORM_MIDDLE:
316 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
317 break;
319 case OSL_PLATFORM_FAR_END:
320 stop = *station_length;
321 break;
324 /* Subtract half the front vehicle length of the train so we get the real
325 * stop location of the train. */
326 return stop - (v->gcache.cached_veh_length + 1) / 2;
331 * Computes train speed limit caused by curves
332 * @return imposed speed limit
334 int Train::GetCurveSpeedLimit() const
336 assert(this->First() == this);
338 static const int absolute_max_speed = UINT16_MAX;
339 int max_speed = absolute_max_speed;
341 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
343 int curvecount[2] = {0, 0};
345 /* first find the curve speed limit */
346 int numcurve = 0;
347 int sum = 0;
348 int pos = 0;
349 int lastpos = -1;
350 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
351 Direction this_dir = u->direction;
352 Direction next_dir = u->Next()->direction;
354 DirDiff dirdiff = DirDifference(this_dir, next_dir);
355 if (dirdiff == DIRDIFF_SAME) continue;
357 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
358 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
359 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
360 if (lastpos != -1) {
361 numcurve++;
362 sum += pos - lastpos;
363 if (pos - lastpos == 1 && max_speed > 88) {
364 max_speed = 88;
367 lastpos = pos;
370 /* if we have a 90 degree turn, fix the speed limit to 60 */
371 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
372 max_speed = 61;
376 if (numcurve > 0 && max_speed > 88) {
377 if (curvecount[0] == 1 && curvecount[1] == 1) {
378 max_speed = absolute_max_speed;
379 } else {
380 sum /= numcurve;
381 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
385 if (max_speed != absolute_max_speed) {
386 /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
387 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
388 max_speed += (max_speed / 2) * rti->curve_speed;
390 if (this->tcache.cached_tilt) {
391 /* Apply max_speed bonus of 20% for a tilting train */
392 max_speed += max_speed / 5;
396 return max_speed;
399 enum TrackBits;
402 * Calculates the maximum speed of the vehicle under its current conditions.
403 * @return Maximum speed of the vehicle.
405 int Train::GetCurrentMaxSpeed() const
407 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
408 this->gcache.cached_max_track_speed :
409 this->tcache.cached_max_curve_speed;
411 if (!(this->vehstatus & VS_CRASHED) && _settings_game.vehicle.train_speed_adaption) {
412 int atc_speed = max_speed;
414 CFollowTrackRail ft(this);
415 Trackdir old_td = this->GetVehicleTrackdir();
417 if (ft.Follow(this->tile, this->GetVehicleTrackdir())) {
418 /* Basic idea: Follow the track for 20 tiles or 3 signals (i.e. at most two signal blocks) looking for other trains. */
419 /* If we find one (that meets certain restrictions), we limit the max speed to the speed of that train. */
420 int num_tiles = 0;
421 int num_signals = 0;
423 do {
424 old_td = ft.m_old_td;
426 /* If we are on a depot or rail station tile stop searching */
427 if (IsDepotTile(ft.m_new_tile) || IsRailStationTile(ft.m_new_tile))
428 break;
430 /* Increment signal counter if we're on a signal */
431 if (IsTileType(ft.m_new_tile, MP_RAILWAY) && ///< Tile has rails
432 KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE && ///< Tile has exactly *one* track
433 HasSignalOnTrack(ft.m_new_tile, TrackBitsToTrack(TrackdirBitsToTrackBits(ft.m_new_td_bits)))) { ///< Tile has signal
434 num_signals++;
437 /* Check if tile has train/is reserved */
438 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE && ///< Tile has exactly *one* track
439 HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) { ///< Tile is reserved
440 Train* other_train = GetTrainForReservation(ft.m_new_tile, TrackBitsToTrack(TrackdirBitsToTrackBits(ft.m_new_td_bits)));
443 if (other_train != nullptr &&
444 other_train != this && ///< Other train is not this train
445 other_train->GetAccelerationStatus() != AS_BRAKE) { ///< Other train is not braking
446 atc_speed = other_train->GetCurrentSpeed();
447 break;
451 /* Decide what in direction to continue: reservation, straight or "first/only" direction. */
452 /* Abort if there's no reservation even though the tile contains multiple tracks. */
453 TrackdirBits reserved = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new_tile));
455 if (reserved != TRACKDIR_BIT_NONE) {
456 // There is a reservation to follow.
457 old_td = FindFirstTrackdir(reserved);
459 else if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
460 // Tile has more than one track and we have no reservation. Bail out.
461 break;
463 else {
464 // There was no reservation but there is only one direction to follow, so follow it.
465 old_td = FindFirstTrackdir(ft.m_new_td_bits);
468 num_tiles++;
469 } while (num_tiles < 20 && num_signals < 3 && ft.Follow(ft.m_new_tile, old_td));
472 /* Check that the ATC speed is sufficiently large.
473 Avoids assertion error in UpdateSpeed(). */
474 max_speed = max(25, min(max_speed, atc_speed));
477 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
478 StationID sid = GetStationIndex(this->tile);
479 if (this->current_order.ShouldStopAtStation(this, sid)) {
480 int station_ahead;
481 int station_length;
482 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
484 /* The distance to go is whatever is still ahead of the train minus the
485 * distance from the train's stop location to the end of the platform */
486 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
488 if (distance_to_go > 0) {
489 int st_max_speed = 120;
491 int delta_v = this->cur_speed / (distance_to_go + 1);
492 if (max_speed > (this->cur_speed - delta_v)) {
493 st_max_speed = this->cur_speed - (delta_v / 10);
496 st_max_speed = max(st_max_speed, 25 * distance_to_go);
497 max_speed = min(max_speed, st_max_speed);
502 for (const Train *u = this; u != NULL; u = u->Next()) {
503 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
504 max_speed = min(max_speed, 61);
505 break;
508 /* Vehicle is on the middle part of a bridge. */
509 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
510 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
514 max_speed = min(max_speed, this->current_order.GetMaxSpeed());
515 return min(max_speed, this->gcache.cached_max_track_speed);
518 /** Update acceleration of the train from the cached power and weight. */
519 void Train::UpdateAcceleration()
521 assert(this->IsFrontEngine() || this->IsFreeWagon());
523 uint power = this->gcache.cached_power;
524 uint weight = this->gcache.cached_weight;
525 assert(weight != 0);
526 this->acceleration = Clamp(power / weight * 4, 1, 255);
530 * Get the width of a train vehicle image in the GUI.
531 * @param offset Additional offset for positioning the sprite; set to NULL if not needed
532 * @return Width in pixels
534 int Train::GetDisplayImageWidth(Point *offset) const
536 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
537 int vehicle_pitch = 0;
539 const Engine *e = this->GetEngine();
540 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
541 reference_width = e->GetGRF()->traininfo_vehicle_width;
542 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
545 if (offset != NULL) {
546 offset->x = ScaleGUITrad(reference_width) / 2;
547 offset->y = ScaleGUITrad(vehicle_pitch);
549 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
552 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
554 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
555 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
559 * Get the sprite to display the train.
560 * @param direction Direction of view/travel.
561 * @param image_type Visualisation context.
562 * @return Sprite to display.
564 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
566 uint8 spritenum = this->spritenum;
568 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
570 if (is_custom_sprite(spritenum)) {
571 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
572 if (result->IsValid()) return;
574 spritenum = this->GetEngine()->original_image_index;
577 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
578 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
580 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
582 result->Set(sprite);
585 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
587 const Engine *e = Engine::Get(engine);
588 Direction dir = rear_head ? DIR_E : DIR_W;
589 uint8 spritenum = e->u.rail.image_index;
591 if (is_custom_sprite(spritenum)) {
592 GetCustomVehicleIcon(engine, dir, image_type, result);
593 if (result->IsValid()) {
594 if (e->GetGRF() != NULL) {
595 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
597 return;
600 spritenum = Engine::Get(engine)->original_image_index;
603 if (rear_head) spritenum++;
605 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
608 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
610 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
611 int yf = y;
612 int yr = y;
614 VehicleSpriteSeq seqf, seqr;
615 GetRailIcon(engine, false, yf, image_type, &seqf);
616 GetRailIcon(engine, true, yr, image_type, &seqr);
618 Rect16 rectf = seqf.GetBounds();
619 Rect16 rectr = seqr.GetBounds();
621 preferred_x = SoftClamp(preferred_x,
622 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
623 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
625 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
626 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
627 } else {
628 VehicleSpriteSeq seq;
629 GetRailIcon(engine, false, y, image_type, &seq);
631 Rect16 rect = seq.GetBounds();
632 preferred_x = Clamp(preferred_x,
633 left - UnScaleGUI(rect.left),
634 right - UnScaleGUI(rect.right));
636 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
641 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
642 * @param engine The engine to get the sprite from.
643 * @param[out] width The width of the sprite.
644 * @param[out] height The height of the sprite.
645 * @param[out] xoffs Number of pixels to shift the sprite to the right.
646 * @param[out] yoffs Number of pixels to shift the sprite downwards.
647 * @param image_type Context the sprite is used in.
649 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
651 int y = 0;
653 VehicleSpriteSeq seq;
654 GetRailIcon(engine, false, y, image_type, &seq);
656 Rect16 rect = seq.GetBounds();
658 width = UnScaleGUI(rect.right - rect.left + 1);
659 height = UnScaleGUI(rect.bottom - rect.top + 1);
660 xoffs = UnScaleGUI(rect.left);
661 yoffs = UnScaleGUI(rect.top);
663 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
664 GetRailIcon(engine, true, y, image_type, &seq);
665 rect = seq.GetBounds();
667 /* Calculate values relative to an imaginary center between the two sprites. */
668 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
669 height = max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
670 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
671 yoffs = min(yoffs, UnScaleGUI(rect.top));
676 * Build a railroad wagon.
677 * @param tile tile of the depot where rail-vehicle is built.
678 * @param flags type of operation.
679 * @param e the engine to build.
680 * @param ret[out] the vehicle that has been built.
681 * @return the cost of this operation or an error.
683 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
685 const RailVehicleInfo *rvi = &e->u.rail;
687 /* Check that the wagon can drive on the track in question */
688 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
690 if (flags & DC_EXEC) {
691 Train *v = new Train();
692 *ret = v;
693 v->spritenum = rvi->image_index;
695 v->engine_type = e->index;
696 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
698 DiagDirection dir = GetRailDepotDirection(tile);
700 v->direction = DiagDirToDir(dir);
701 v->tile = tile;
703 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
704 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
706 v->x_pos = x;
707 v->y_pos = y;
708 v->z_pos = GetSlopePixelZ(x, y);
709 v->owner = _current_company;
710 v->track = TRACK_BIT_DEPOT;
711 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
712 v->reverse_distance = 0;
714 v->SetWagon();
716 v->SetFreeWagon();
717 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
719 v->cargo_type = e->GetDefaultCargoType();
720 v->cargo_cap = rvi->capacity;
721 v->refit_cap = 0;
723 v->railtype = rvi->railtype;
725 v->date_of_last_service = _date;
726 v->build_year = _cur_year;
727 v->sprite_seq.Set(SPR_IMG_QUERY);
728 v->random_bits = VehicleRandomBits();
730 v->group_id = DEFAULT_GROUP;
732 AddArticulatedParts(v);
734 _new_vehicle_id = v->index;
736 v->UpdatePosition();
737 v->First()->ConsistChanged(CCF_ARRANGE);
738 UpdateTrainGroupID(v->First());
740 CheckConsistencyOfArticulatedVehicle(v);
742 /* Try to connect the vehicle to one of free chains of wagons. */
743 Train *w;
744 FOR_ALL_TRAINS(w) {
745 if (w->tile == tile && ///< Same depot
746 w->IsFreeWagon() && ///< A free wagon chain
747 w->engine_type == e->index && ///< Same type
748 w->First() != v && ///< Don't connect to ourself
749 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
750 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
751 break;
756 return CommandCost();
759 /** Move all free vehicles in the depot to the train */
760 static void NormalizeTrainVehInDepot(const Train *u)
762 const Train *v;
763 FOR_ALL_TRAINS(v) {
764 if (v->IsFreeWagon() && v->tile == u->tile &&
765 v->track == TRACK_BIT_DEPOT) {
766 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
767 CMD_MOVE_RAIL_VEHICLE).Failed())
768 break;
773 static void AddRearEngineToMultiheadedTrain(Train *v)
775 Train *u = new Train();
776 v->value >>= 1;
777 u->value = v->value;
778 u->direction = v->direction;
779 u->owner = v->owner;
780 u->tile = v->tile;
781 u->x_pos = v->x_pos;
782 u->y_pos = v->y_pos;
783 u->z_pos = v->z_pos;
784 u->track = TRACK_BIT_DEPOT;
785 u->vehstatus = v->vehstatus & ~VS_STOPPED;
786 u->spritenum = v->spritenum + 1;
787 u->cargo_type = v->cargo_type;
788 u->cargo_subtype = v->cargo_subtype;
789 u->cargo_cap = v->cargo_cap;
790 u->refit_cap = v->refit_cap;
791 u->railtype = v->railtype;
792 u->engine_type = v->engine_type;
793 u->date_of_last_service = v->date_of_last_service;
794 u->build_year = v->build_year;
795 u->sprite_seq.Set(SPR_IMG_QUERY);
796 u->random_bits = VehicleRandomBits();
797 v->SetMultiheaded();
798 u->SetMultiheaded();
799 v->SetNext(u);
800 u->UpdatePosition();
802 /* Now we need to link the front and rear engines together */
803 v->other_multiheaded_part = u;
804 u->other_multiheaded_part = v;
808 * Build a railroad vehicle.
809 * @param tile tile of the depot where rail-vehicle is built.
810 * @param flags type of operation.
811 * @param e the engine to build.
812 * @param data bit 0 prevents any free cars from being added to the train.
813 * @param ret[out] the vehicle that has been built.
814 * @return the cost of this operation or an error.
816 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
818 const RailVehicleInfo *rvi = &e->u.rail;
820 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
822 /* Check if depot and new engine uses the same kind of tracks *
823 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
824 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
826 if (flags & DC_EXEC) {
827 DiagDirection dir = GetRailDepotDirection(tile);
828 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
829 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
831 Train *v = new Train();
832 *ret = v;
833 v->direction = DiagDirToDir(dir);
834 v->tile = tile;
835 v->owner = _current_company;
836 v->x_pos = x;
837 v->y_pos = y;
838 v->z_pos = GetSlopePixelZ(x, y);
839 v->track = TRACK_BIT_DEPOT;
840 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
841 v->spritenum = rvi->image_index;
842 v->cargo_type = e->GetDefaultCargoType();
843 v->cargo_cap = rvi->capacity;
844 v->refit_cap = 0;
845 v->last_station_visited = INVALID_STATION;
846 v->last_loading_station = INVALID_STATION;
847 v->reverse_distance = 0;
849 v->engine_type = e->index;
850 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
852 v->reliability = e->reliability;
853 v->reliability_spd_dec = e->reliability_spd_dec;
854 v->max_age = e->GetLifeLengthInDays();
856 v->railtype = rvi->railtype;
857 _new_vehicle_id = v->index;
859 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
860 v->date_of_last_service = _date;
861 v->build_year = _cur_year;
862 v->sprite_seq.Set(SPR_IMG_QUERY);
863 v->random_bits = VehicleRandomBits();
865 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
866 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
868 v->group_id = DEFAULT_GROUP;
870 v->SetFrontEngine();
871 v->SetEngine();
873 v->UpdatePosition();
875 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
876 AddRearEngineToMultiheadedTrain(v);
877 } else {
878 AddArticulatedParts(v);
881 v->ConsistChanged(CCF_ARRANGE);
882 UpdateTrainGroupID(v);
884 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
885 NormalizeTrainVehInDepot(v);
888 CheckConsistencyOfArticulatedVehicle(v);
891 return CommandCost();
894 static Train *FindGoodVehiclePos(const Train *src)
896 EngineID eng = src->engine_type;
897 TileIndex tile = src->tile;
899 Train *dst;
900 FOR_ALL_TRAINS(dst) {
901 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
902 /* check so all vehicles in the line have the same engine. */
903 Train *t = dst;
904 while (t->engine_type == eng) {
905 t = t->Next();
906 if (t == NULL) return dst;
911 return NULL;
914 /** Helper type for lists/vectors of trains */
915 typedef SmallVector<Train *, 16> TrainList;
918 * Make a backup of a train into a train list.
919 * @param list to make the backup in
920 * @param t the train to make the backup of
922 static void MakeTrainBackup(TrainList &list, Train *t)
924 for (; t != NULL; t = t->Next()) *list.Append() = t;
928 * Restore the train from the backup list.
929 * @param list the train to restore.
931 static void RestoreTrainBackup(TrainList &list)
933 /* No train, nothing to do. */
934 if (list.Length() == 0) return;
936 Train *prev = NULL;
937 /* Iterate over the list and rebuild it. */
938 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
939 Train *t = *iter;
940 if (prev != NULL) {
941 prev->SetNext(t);
942 } else if (t->Previous() != NULL) {
943 /* Make sure the head of the train is always the first in the chain. */
944 t->Previous()->SetNext(NULL);
946 prev = t;
951 * Remove the given wagon from its consist.
952 * @param part the part of the train to remove.
953 * @param chain whether to remove the whole chain.
955 static void RemoveFromConsist(Train *part, bool chain = false)
957 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
959 /* Unlink at the front, but make it point to the next
960 * vehicle after the to be remove part. */
961 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
963 /* Unlink at the back */
964 tail->SetNext(NULL);
968 * Inserts a chain into the train at dst.
969 * @param dst the place where to append after.
970 * @param chain the chain to actually add.
972 static void InsertInConsist(Train *dst, Train *chain)
974 /* We do not want to add something in the middle of an articulated part. */
975 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
977 chain->Last()->SetNext(dst->Next());
978 dst->SetNext(chain);
982 * Normalise the dual heads in the train, i.e. if one is
983 * missing move that one to this train.
984 * @param t the train to normalise.
986 static void NormaliseDualHeads(Train *t)
988 for (; t != NULL; t = t->GetNextVehicle()) {
989 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
991 /* Make sure that there are no free cars before next engine */
992 Train *u;
993 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
995 if (u == t->other_multiheaded_part) continue;
997 /* Remove the part from the 'wrong' train */
998 RemoveFromConsist(t->other_multiheaded_part);
999 /* And add it to the 'right' train */
1000 InsertInConsist(u, t->other_multiheaded_part);
1005 * Normalise the sub types of the parts in this chain.
1006 * @param chain the chain to normalise.
1008 static void NormaliseSubtypes(Train *chain)
1010 /* Nothing to do */
1011 if (chain == NULL) return;
1013 /* We must be the first in the chain. */
1014 assert(chain->Previous() == NULL);
1016 /* Set the appropriate bits for the first in the chain. */
1017 if (chain->IsWagon()) {
1018 chain->SetFreeWagon();
1019 } else {
1020 assert(chain->IsEngine());
1021 chain->SetFrontEngine();
1024 /* Now clear the bits for the rest of the chain */
1025 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
1026 t->ClearFreeWagon();
1027 t->ClearFrontEngine();
1032 * Check/validate whether we may actually build a new train.
1033 * @note All vehicles are/were 'heads' of their chains.
1034 * @param original_dst The original destination chain.
1035 * @param dst The destination chain after constructing the train.
1036 * @param original_dst The original source chain.
1037 * @param dst The source chain after constructing the train.
1038 * @return possible error of this command.
1040 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
1042 /* Just add 'new' engines and subtract the original ones.
1043 * If that's less than or equal to 0 we can be sure we did
1044 * not add any engines (read: trains) along the way. */
1045 if ((src != NULL && src->IsEngine() ? 1 : 0) +
1046 (dst != NULL && dst->IsEngine() ? 1 : 0) -
1047 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
1048 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
1049 return CommandCost();
1052 /* Get a free unit number and check whether it's within the bounds.
1053 * There will always be a maximum of one new train. */
1054 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1056 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1060 * Check whether the train parts can be attached.
1061 * @param t the train to check
1062 * @return possible error of this command.
1064 static CommandCost CheckTrainAttachment(Train *t)
1066 /* No multi-part train, no need to check. */
1067 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
1069 /* The maximum length for a train. For each part we decrease this by one
1070 * and if the result is negative the train is simply too long. */
1071 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1073 Train *head = t;
1074 Train *prev = t;
1076 /* Break the prev -> t link so it always holds within the loop. */
1077 t = t->Next();
1078 prev->SetNext(NULL);
1080 /* Make sure the cache is cleared. */
1081 head->InvalidateNewGRFCache();
1083 while (t != NULL) {
1084 allowed_len -= t->gcache.cached_veh_length;
1086 Train *next = t->Next();
1088 /* Unlink the to-be-added piece; it is already unlinked from the previous
1089 * part due to the fact that the prev -> t link is broken. */
1090 t->SetNext(NULL);
1092 /* Don't check callback for articulated or rear dual headed parts */
1093 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1094 /* Back up and clear the first_engine data to avoid using wagon override group */
1095 EngineID first_engine = t->gcache.first_engine;
1096 t->gcache.first_engine = INVALID_ENGINE;
1098 /* We don't want the cache to interfere. head's cache is cleared before
1099 * the loop and after each callback does not need to be cleared here. */
1100 t->InvalidateNewGRFCache();
1102 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1104 /* Restore original first_engine data */
1105 t->gcache.first_engine = first_engine;
1107 /* We do not want to remember any cached variables from the test run */
1108 t->InvalidateNewGRFCache();
1109 head->InvalidateNewGRFCache();
1111 if (callback != CALLBACK_FAILED) {
1112 /* A failing callback means everything is okay */
1113 StringID error = STR_NULL;
1115 if (head->GetGRF()->grf_version < 8) {
1116 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1117 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1118 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1119 } else {
1120 if (callback < 0x400) {
1121 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1122 } else {
1123 switch (callback) {
1124 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1125 case 0x401: // allow
1126 break;
1128 default: // unknown reason -> disallow
1129 case 0x402: // disallow attaching
1130 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1131 break;
1136 if (error != STR_NULL) return_cmd_error(error);
1140 /* And link it to the new part. */
1141 prev->SetNext(t);
1142 prev = t;
1143 t = next;
1146 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1147 return CommandCost();
1151 * Validate whether we are going to create valid trains.
1152 * @note All vehicles are/were 'heads' of their chains.
1153 * @param original_dst The original destination chain.
1154 * @param dst The destination chain after constructing the train.
1155 * @param original_dst The original source chain.
1156 * @param dst The source chain after constructing the train.
1157 * @param check_limit Whether to check the vehicle limit.
1158 * @return possible error of this command.
1160 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1162 /* Check whether we may actually construct the trains. */
1163 CommandCost ret = CheckTrainAttachment(src);
1164 if (ret.Failed()) return ret;
1165 ret = CheckTrainAttachment(dst);
1166 if (ret.Failed()) return ret;
1168 /* Check whether we need to build a new train. */
1169 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1173 * Arrange the trains in the wanted way.
1174 * @param dst_head The destination chain of the to be moved vehicle.
1175 * @param dst The destination for the to be moved vehicle.
1176 * @param src_head The source chain of the to be moved vehicle.
1177 * @param src The to be moved vehicle.
1178 * @param move_chain Whether to move all vehicles after src or not.
1180 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1182 /* First determine the front of the two resulting trains */
1183 if (*src_head == *dst_head) {
1184 /* If we aren't moving part(s) to a new train, we are just moving the
1185 * front back and there is not destination head. */
1186 *dst_head = NULL;
1187 } else if (*dst_head == NULL) {
1188 /* If we are moving to a new train the head of the move train would become
1189 * the head of the new vehicle. */
1190 *dst_head = src;
1193 if (src == *src_head) {
1194 /* If we are moving the front of a train then we are, in effect, creating
1195 * a new head for the train. Point to that. Unless we are moving the whole
1196 * train in which case there is not 'source' train anymore.
1197 * In case we are a multiheaded part we want the complete thing to come
1198 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1199 * that is followed by a rear multihead we do not want to include that. */
1200 *src_head = move_chain ? NULL :
1201 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1204 /* Now it's just simply removing the part that we are going to move from the
1205 * source train and *if* the destination is a not a new train add the chain
1206 * at the destination location. */
1207 RemoveFromConsist(src, move_chain);
1208 if (*dst_head != src) InsertInConsist(dst, src);
1210 /* Now normalise the dual heads, that is move the dual heads around in such
1211 * a way that the head and rear of a dual head are in the same train */
1212 NormaliseDualHeads(*src_head);
1213 NormaliseDualHeads(*dst_head);
1217 * Normalise the head of the train again, i.e. that is tell the world that
1218 * we have changed and update all kinds of variables.
1219 * @param head the train to update.
1221 static void NormaliseTrainHead(Train *head)
1223 /* Not much to do! */
1224 if (head == NULL) return;
1226 /* Tell the 'world' the train changed. */
1227 head->ConsistChanged(CCF_ARRANGE);
1228 UpdateTrainGroupID(head);
1230 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1231 if (!head->IsFrontEngine()) return;
1233 /* Update the refit button and window */
1234 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1235 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1237 /* If we don't have a unit number yet, set one. */
1238 if (head->unitnumber != 0) return;
1239 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1243 * Move a rail vehicle around inside the depot.
1244 * @param tile unused
1245 * @param flags type of operation
1246 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1247 * @param p1 various bitstuffed elements
1248 * - p1 (bit 0 - 19) source vehicle index
1249 * - p1 (bit 20) move all vehicles following the source vehicle
1250 * - p1 (bit 21) this is a virtual vehicle (for creating TemplateVehicles)
1251 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1252 * @param text unused
1253 * @return the cost of this operation or an error
1255 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1257 VehicleID s = GB(p1, 0, 20);
1258 VehicleID d = GB(p2, 0, 20);
1259 bool move_chain = HasBit(p1, 20);
1261 Train *src = Train::GetIfValid(s);
1262 if (src == NULL) return CMD_ERROR;
1264 CommandCost ret = CheckOwnership(src->owner);
1265 if (ret.Failed()) return ret;
1267 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1268 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1270 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1271 Train *dst;
1272 if (d == INVALID_VEHICLE) {
1273 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1274 } else {
1275 dst = Train::GetIfValid(d);
1276 if (dst == NULL) return CMD_ERROR;
1278 CommandCost ret = CheckOwnership(dst->owner);
1279 if (ret.Failed()) return ret;
1281 /* Do not allow appending to crashed vehicles, too */
1282 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1285 /* if an articulated part is being handled, deal with its parent vehicle */
1286 src = src->GetFirstEnginePart();
1287 if (dst != NULL) {
1288 dst = dst->GetFirstEnginePart();
1289 assert(HasBit(dst->subtype, GVSF_VIRTUAL) == HasBit(src->subtype, GVSF_VIRTUAL));
1292 /* don't move the same vehicle.. */
1293 if (src == dst) return CommandCost();
1295 /* locate the head of the two chains */
1296 Train *src_head = src->First();
1297 assert(HasBit(src_head->subtype, GVSF_VIRTUAL) == HasBit(src->subtype, GVSF_VIRTUAL));
1298 Train *dst_head;
1299 if (dst != NULL) {
1300 dst_head = dst->First();
1301 assert(HasBit(dst_head->subtype, GVSF_VIRTUAL) == HasBit(dst->subtype, GVSF_VIRTUAL));
1302 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1303 /* Now deal with articulated part of destination wagon */
1304 dst = dst->GetLastEnginePart();
1305 } else {
1306 dst_head = NULL;
1309 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1311 /* When moving all wagons, we can't have the same src_head and dst_head */
1312 if (move_chain && src_head == dst_head) return CommandCost();
1314 /* When moving a multiheaded part to be place after itself, bail out. */
1315 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1317 /* Check if all vehicles in the source train are stopped inside a depot. */
1318 /* Do this check only if the vehicle to be moved is non-virtual */
1319 if ( !HasBit(p1, 21) )
1320 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1322 /* Check if all vehicles in the destination train are stopped inside a depot. */
1323 /* Do this check only if the destination vehicle is non-virtual */
1324 if ( !HasBit(p1, 21) )
1325 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1327 /* First make a backup of the order of the trains. That way we can do
1328 * whatever we want with the order and later on easily revert. */
1329 TrainList original_src;
1330 TrainList original_dst;
1332 MakeTrainBackup(original_src, src_head);
1333 MakeTrainBackup(original_dst, dst_head);
1335 /* Also make backup of the original heads as ArrangeTrains can change them.
1336 * For the destination head we do not care if it is the same as the source
1337 * head because in that case it's just a copy. */
1338 Train *original_src_head = src_head;
1339 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1341 /* We want this information from before the rearrangement, but execute this after the validation.
1342 * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1343 * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1344 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1345 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1347 /* (Re)arrange the trains in the wanted arrangement. */
1348 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1350 if ((flags & DC_AUTOREPLACE) == 0) {
1351 /* If the autoreplace flag is set we do not need to test for the validity
1352 * because we are going to revert the train to its original state. As we
1353 * assume the original state was correct autoreplace can skip this. */
1354 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1355 if (ret.Failed()) {
1356 /* Restore the train we had. */
1357 RestoreTrainBackup(original_src);
1358 RestoreTrainBackup(original_dst);
1359 return ret;
1363 /* do it? */
1364 if (flags & DC_EXEC) {
1365 /* Remove old heads from the statistics */
1366 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1367 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1369 /* First normalise the sub types of the chains. */
1370 NormaliseSubtypes(src_head);
1371 NormaliseSubtypes(dst_head);
1373 /* There are 14 different cases:
1374 * 1) front engine gets moved to a new train, it stays a front engine.
1375 * a) the 'next' part is a wagon that becomes a free wagon chain.
1376 * b) the 'next' part is an engine that becomes a front engine.
1377 * c) there is no 'next' part, nothing else happens
1378 * 2) front engine gets moved to another train, it is not a front engine anymore
1379 * a) the 'next' part is a wagon that becomes a free wagon chain.
1380 * b) the 'next' part is an engine that becomes a front engine.
1381 * c) there is no 'next' part, nothing else happens
1382 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1383 * a) the 'next' part is a wagon that becomes a free wagon chain.
1384 * b) the 'next' part is an engine that becomes a front engine.
1385 * 4) free wagon gets moved
1386 * a) the 'next' part is a wagon that becomes a free wagon chain.
1387 * b) the 'next' part is an engine that becomes a front engine.
1388 * c) there is no 'next' part, nothing else happens
1389 * 5) non front engine gets moved and becomes a new train, nothing else happens
1390 * 6) non front engine gets moved within a train / to another train, nothing hapens
1391 * 7) wagon gets moved, nothing happens
1393 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1394 /* Cases #2 and #3: the front engine gets trashed. */
1395 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
1396 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
1397 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
1398 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
1399 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
1400 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1401 SetWindowDirty(WC_COMPANY, _current_company);
1403 /* Delete orders, group stuff and the unit number as we're not the
1404 * front of any vehicle anymore. */
1405 src->DeleteVehicleOrders();
1406 RemoveVehicleFromGroup(src);
1407 src->unitnumber = 0;
1408 if (HasBit(src->flags, VRF_HAVE_SLOT)) {
1409 TraceRestrictRemoveVehicleFromAllSlots(src->index);
1410 ClrBit(src->flags, VRF_HAVE_SLOT);
1414 /* We weren't a front engine but are becoming one. So
1415 * we should be put in the default group. */
1416 if (original_src_head != src && dst_head == src) {
1417 SetTrainGroupID(src, DEFAULT_GROUP);
1418 SetWindowDirty(WC_COMPANY, _current_company);
1421 /* Add new heads to statistics */
1422 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1423 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1425 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1426 NormaliseTrainHead(src_head);
1427 NormaliseTrainHead(dst_head);
1429 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1430 CheckCargoCapacity(src_head);
1431 CheckCargoCapacity(dst_head);
1434 if (src_head != NULL) {
1435 src_head->last_loading_station = INVALID_STATION;
1436 ClrBit(src_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1438 if (dst_head != NULL) {
1439 dst_head->last_loading_station = INVALID_STATION;
1440 ClrBit(dst_head->vehicle_flags, VF_LAST_LOAD_ST_SEP);
1443 if (src_head != NULL) src_head->First()->MarkDirty();
1444 if (dst_head != NULL) dst_head->First()->MarkDirty();
1446 /* We are undoubtedly changing something in the depot and train list. */
1447 /* But only if the moved vehicle is not virtual */
1448 if ( !HasBit(src->subtype, GVSF_VIRTUAL) ) {
1449 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1450 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1451 } else {
1452 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1454 } else {
1455 /* We don't want to execute what we're just tried. */
1456 RestoreTrainBackup(original_src);
1457 RestoreTrainBackup(original_dst);
1460 return CommandCost();
1464 * Sell a (single) train wagon/engine.
1465 * @param flags type of operation
1466 * @param t the train wagon to sell
1467 * @param data the selling mode
1468 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1469 * - data = 1: sell the vehicle and all vehicles following it in the chain
1470 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1471 * @param user the user for the order backup.
1472 * @return the cost of this operation or an error
1474 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1476 /* Sell a chain of vehicles or not? */
1477 bool sell_chain = HasBit(data, 0);
1479 Train *v = Train::From(t)->GetFirstEnginePart();
1480 Train *first = v->First();
1482 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1484 /* First make a backup of the order of the train. That way we can do
1485 * whatever we want with the order and later on easily revert. */
1486 TrainList original;
1487 MakeTrainBackup(original, first);
1489 /* We need to keep track of the new head and the head of what we're going to sell. */
1490 Train *new_head = first;
1491 Train *sell_head = NULL;
1493 /* Split the train in the wanted way. */
1494 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1496 /* We don't need to validate the second train; it's going to be sold. */
1497 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1498 if (ret.Failed()) {
1499 /* Restore the train we had. */
1500 RestoreTrainBackup(original);
1501 return ret;
1504 if (!first->HasOrdersList() && !OrderList::CanAllocateItem()) {
1505 /* Restore the train we had. */
1506 RestoreTrainBackup(original);
1507 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1510 CommandCost cost(EXPENSES_NEW_VEHICLES);
1511 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1513 /* do it? */
1514 if (flags & DC_EXEC) {
1515 /* First normalise the sub types of the chain. */
1516 NormaliseSubtypes(new_head);
1518 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1519 /* We are selling the front engine. In this case we want to
1520 * 'give' the order, unit number and such to the new head. */
1521 new_head->ShareOrdersWith(first);
1522 new_head->AddToShared(first);
1523 first->DeleteVehicleOrders();
1525 /* Copy other important data from the front engine */
1526 new_head->CopyVehicleConfigAndStatistics(first);
1527 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1528 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1529 OrderBackup::Backup(v, user);
1532 /* We need to update the information about the train. */
1533 NormaliseTrainHead(new_head);
1535 /* We are undoubtedly changing something in the depot and train list. */
1536 /* Unless its a virtual train */
1537 if ( !HasBit(v->subtype, GVSF_VIRTUAL) ) {
1538 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1539 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1540 } else {
1541 InvalidateWindowClassesData(WC_CREATE_TEMPLATE);
1544 /* Actually delete the sold 'goods' */
1545 delete sell_head;
1546 } else {
1547 /* We don't want to execute what we're just tried. */
1548 RestoreTrainBackup(original);
1551 return cost;
1554 void Train::UpdateDeltaXY(Direction direction)
1556 /* Set common defaults. */
1557 this->x_offs = -1;
1558 this->y_offs = -1;
1559 this->x_extent = 3;
1560 this->y_extent = 3;
1561 this->z_extent = 6;
1562 this->x_bb_offs = 0;
1563 this->y_bb_offs = 0;
1565 if (!IsDiagonalDirection(direction)) {
1566 static const int _sign_table[] =
1568 /* x, y */
1569 -1, -1, // DIR_N
1570 -1, 1, // DIR_E
1571 1, 1, // DIR_S
1572 1, -1, // DIR_W
1575 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1577 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1578 this->x_offs -= half_shorten * _sign_table[direction];
1579 this->y_offs -= half_shorten * _sign_table[direction + 1];
1580 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1581 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1582 } else {
1583 switch (direction) {
1584 /* Shorten southern corner of the bounding box according the vehicle length
1585 * and center the bounding box on the vehicle. */
1586 case DIR_NE:
1587 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1588 this->x_extent = this->gcache.cached_veh_length - 1;
1589 this->x_bb_offs = -1;
1590 break;
1592 case DIR_NW:
1593 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1594 this->y_extent = this->gcache.cached_veh_length - 1;
1595 this->y_bb_offs = -1;
1596 break;
1598 /* Move northern corner of the bounding box down according to vehicle length
1599 * and center the bounding box on the vehicle. */
1600 case DIR_SW:
1601 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1602 this->x_extent = VEHICLE_LENGTH - 1;
1603 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1604 break;
1606 case DIR_SE:
1607 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1608 this->y_extent = VEHICLE_LENGTH - 1;
1609 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1610 break;
1612 default:
1613 NOT_REACHED();
1619 * Mark a train as stuck and stop it if it isn't stopped right now.
1620 * @param v %Train to mark as being stuck.
1622 static void MarkTrainAsStuck(Train *v, bool waiting_restriction = false)
1624 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1625 /* It is the first time the problem occurred, set the "train stuck" flag. */
1626 SetBit(v->flags, VRF_TRAIN_STUCK);
1627 SB(v->flags, VRF_WAITING_RESTRICTION, 1, waiting_restriction ? 1 : 0);
1629 v->wait_counter = 0;
1631 /* Stop train */
1632 v->cur_speed = 0;
1633 v->subspeed = 0;
1634 v->SetLastSpeed();
1636 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1637 } else if (waiting_restriction != HasBit(v->flags, VRF_WAITING_RESTRICTION)) {
1638 ToggleBit(v->flags, VRF_WAITING_RESTRICTION);
1639 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1644 * Swap the two up/down flags in two ways:
1645 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1646 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1647 * @param swap_flag1 [inout] First train flag.
1648 * @param swap_flag2 [inout] Second train flag.
1650 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1652 uint16 flag1 = *swap_flag1;
1653 uint16 flag2 = *swap_flag2;
1655 /* Clear the flags */
1656 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1657 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1658 ClrBit(*swap_flag1, GVF_CHUNNEL_BIT);
1659 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1660 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1661 ClrBit(*swap_flag2, GVF_CHUNNEL_BIT);
1663 /* Reverse the rail-flags (if needed) */
1664 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1665 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1666 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1667 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1670 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1671 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1672 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1673 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1676 if (HasBit(flag1, GVF_CHUNNEL_BIT)) {
1677 SetBit(*swap_flag2, GVF_CHUNNEL_BIT);
1680 if (HasBit(flag2, GVF_CHUNNEL_BIT)) {
1681 SetBit(*swap_flag1, GVF_CHUNNEL_BIT);
1686 * Updates some variables after swapping the vehicle.
1687 * @param v swapped vehicle
1689 static void UpdateStatusAfterSwap(Train *v)
1691 /* Reverse the direction. */
1692 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1694 /* Call the proper EnterTile function unless we are in a wormhole. */
1695 if (v->track != TRACK_BIT_WORMHOLE) {
1696 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1697 } else {
1698 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1699 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1700 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1701 * when we shouldn't have. Check if this is the case. */
1702 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1703 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1704 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1705 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1706 /* We have just left the wormhole, possibly set the
1707 * "goingdown" bit. UpdateInclination() can be used
1708 * because we are at the border of the tile. */
1709 v->UpdatePosition();
1710 v->UpdateInclination(true, true);
1711 return;
1716 v->UpdatePosition();
1717 if (v->track == TRACK_BIT_WORMHOLE) v->UpdateInclination(false, false, true);
1718 v->UpdateViewport(true, true);
1722 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1723 * @param v Consist to change.
1724 * @param l %Vehicle index in the consist of the first vehicle.
1725 * @param r %Vehicle index in the consist of the second vehicle.
1727 void ReverseTrainSwapVeh(Train *v, int l, int r)
1729 Train *a, *b;
1731 /* locate vehicles to swap */
1732 for (a = v; l != 0; l--) a = a->Next();
1733 for (b = v; r != 0; r--) b = b->Next();
1735 if (a != b) {
1736 /* swap the hidden bits */
1738 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1739 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1740 a->vehstatus = tmp;
1743 Swap(a->track, b->track);
1744 Swap(a->direction, b->direction);
1745 Swap(a->x_pos, b->x_pos);
1746 Swap(a->y_pos, b->y_pos);
1747 Swap(a->tile, b->tile);
1748 Swap(a->z_pos, b->z_pos);
1750 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1752 UpdateStatusAfterSwap(a);
1753 UpdateStatusAfterSwap(b);
1754 } else {
1755 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1756 * This is a little bit redundant way, a->gv_flags will
1757 * be (re)set twice, but it reduces code duplication */
1758 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1759 UpdateStatusAfterSwap(a);
1765 * Check if the vehicle is a train
1766 * @param v vehicle on tile
1767 * @return v if it is a train, NULL otherwise
1769 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1771 return (v->type == VEH_TRAIN) ? v : NULL;
1776 * Checks if a train is approaching a rail-road crossing
1777 * @param v vehicle on tile
1778 * @param data tile with crossing we are testing
1779 * @return v if it is approaching a crossing, NULL otherwise
1781 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1783 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
1785 Train *t = Train::From(v);
1786 if (!t->IsFrontEngine()) return NULL;
1788 TileIndex tile = *(TileIndex *)data;
1790 if (TrainApproachingCrossingTile(t) != tile) return NULL;
1792 return t;
1797 * Finds a vehicle approaching rail-road crossing
1798 * @param tile tile to test
1799 * @return true if a vehicle is approaching the crossing
1800 * @pre tile is a rail-road crossing
1802 static bool TrainApproachingCrossing(TileIndex tile)
1804 assert(IsLevelCrossingTile(tile));
1806 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1807 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1809 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1811 dir = ReverseDiagDir(dir);
1812 tile_from = tile + TileOffsByDiagDir(dir);
1814 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1817 /** Check if the crossing should be closed
1818 * @return train on crossing || train approaching crossing || reserved
1820 static inline bool CheckLevelCrossing(TileIndex tile)
1822 return HasCrossingReservation(tile) || HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile);
1826 * Sets correct crossing state
1827 * @param tile tile to update
1828 * @param sound should we play sound?
1829 * @param is_forced force set the crossing state to that of forced_state
1830 * @param forced_state the crossing state to set when using is_forced
1831 * @pre tile is a rail-road crossing
1833 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool is_forced, bool forced_state)
1835 assert(IsLevelCrossingTile(tile));
1837 // Ignore level crossings for types where it doesn't matter.
1838 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(tile))->label;
1840 if (railTypeLabel == _planning_tracks_label ||
1841 railTypeLabel == _pipeline_tracks_label ||
1842 railTypeLabel == _wires_tracks_label) {
1844 if (IsCrossingBarred(tile)) {
1845 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1848 SetCrossingBarred(tile, false);
1849 return;
1852 bool new_state;
1854 if (is_forced) {
1855 new_state = forced_state;
1856 } else {
1857 new_state = CheckLevelCrossing(tile);
1860 if (new_state != IsCrossingBarred(tile)) {
1861 if (new_state && sound) {
1863 if (_settings_client.sound.ambient) {
1864 SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1867 SetCrossingBarred(tile, new_state);
1868 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
1873 * Cycles the adjacent crossings and sets their state
1874 * @param tile tile to update
1875 * @param sound should we play sound?
1876 * @param force_close force close the crossing
1878 void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_close)
1880 bool forced_state = force_close;
1881 if (!IsLevelCrossingTile(tile)) return;
1883 const Axis axis = GetCrossingRoadAxis(tile);
1884 const DiagDirection dir = AxisToDiagDir(axis);
1885 const DiagDirection reverse_dir = ReverseDiagDir(dir);
1887 for (TileIndex t = tile; !forced_state && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1888 forced_state |= CheckLevelCrossing(t);
1890 for (TileIndex t = TileAddByDiagDir(tile, reverse_dir); !forced_state && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, reverse_dir)) {
1891 forced_state |= CheckLevelCrossing(t);
1894 UpdateLevelCrossingTile(tile, sound, force_close, forced_state);
1895 for (TileIndex t = TileAddByDiagDir(tile, dir); IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1896 UpdateLevelCrossingTile(t, sound, true, forced_state);
1898 for (TileIndex t = TileAddByDiagDir(tile, reverse_dir); IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, reverse_dir)) {
1899 UpdateLevelCrossingTile(t, sound, true, forced_state);
1905 * Bars crossing and plays ding-ding sound if not barred already
1906 * @param tile tile with crossing
1907 * @pre tile is a rail-road crossing
1909 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1911 if (!IsCrossingBarred(tile)) {
1912 UpdateLevelCrossing(tile, true, true);
1918 * Advances wagons for train reversing, needed for variable length wagons.
1919 * This one is called before the train is reversed.
1920 * @param v First vehicle in chain
1922 static void AdvanceWagonsBeforeSwap(Train *v)
1924 Train *base = v;
1925 Train *first = base; // first vehicle to move
1926 Train *last = v->Last(); // last vehicle to move
1927 uint length = CountVehiclesInChain(v);
1929 while (length > 2) {
1930 last = last->Previous();
1931 first = first->Next();
1933 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1935 /* do not update images now
1936 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1937 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1939 base = first; // == base->Next()
1940 length -= 2;
1946 * Advances wagons for train reversing, needed for variable length wagons.
1947 * This one is called after the train is reversed.
1948 * @param v First vehicle in chain
1950 static void AdvanceWagonsAfterSwap(Train *v)
1952 /* first of all, fix the situation when the train was entering a depot */
1953 Train *dep = v; // last vehicle in front of just left depot
1954 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1955 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1958 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1960 if (leave != NULL) {
1961 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1962 int d = TicksToLeaveDepot(dep);
1964 if (d <= 0) {
1965 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1966 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1967 for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1969 } else {
1970 dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1973 Train *base = v;
1974 Train *first = base; // first vehicle to move
1975 Train *last = v->Last(); // last vehicle to move
1976 uint length = CountVehiclesInChain(v);
1978 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1979 * they have already correct spacing, so we have to make sure they are moved how they should */
1980 bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1982 while (length > 2) {
1983 /* we reached vehicle (originally) in front of a depot, stop now
1984 * (we would move wagons that are already moved with new wagon length). */
1985 if (base == dep) break;
1987 /* the last wagon was that one leaving a depot, so do not move it anymore */
1988 if (last == dep) nomove = true;
1990 last = last->Previous();
1991 first = first->Next();
1993 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1995 /* do not update images now */
1996 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1998 base = first; // == base->Next()
1999 length -= 2;
2004 * Turn a train around.
2005 * @param v %Train to turn around.
2007 void ReverseTrainDirection(Train *v)
2009 if (IsRailDepotTile(v->tile)) {
2010 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2013 v->reverse_distance = 0;
2015 /* Clear path reservation in front if train is not stuck. */
2016 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
2018 /* Check if we were approaching a rail/road-crossing */
2019 TileIndex crossing = TrainApproachingCrossingTile(v);
2021 /* count number of vehicles */
2022 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
2024 AdvanceWagonsBeforeSwap(v);
2026 /* swap start<>end, start+1<>end-1, ... */
2027 int l = 0;
2028 do {
2029 ReverseTrainSwapVeh(v, l++, r--);
2030 } while (l <= r);
2032 AdvanceWagonsAfterSwap(v);
2034 if (IsRailDepotTile(v->tile)) {
2035 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2038 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
2040 ClrBit(v->flags, VRF_REVERSING);
2042 /* recalculate cached data */
2043 v->ConsistChanged(CCF_TRACK);
2045 /* update all images */
2046 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
2048 /* update crossing we were approaching */
2049 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2051 /* maybe we are approaching crossing now, after reversal */
2052 crossing = TrainApproachingCrossingTile(v);
2053 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2055 /* If we are inside a depot after reversing, don't bother with path reserving. */
2056 if (v->track == TRACK_BIT_DEPOT) {
2057 /* Can't be stuck here as inside a depot is always a safe tile. */
2058 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2059 ClrBit(v->flags, VRF_TRAIN_STUCK);
2060 return;
2063 /* We are inside tunnel/bidge with signals, reversing will close the entrance. */
2064 if (IsTunnelBridgeWithSignalSimulation(v->tile)) {
2065 /* Flip signal on tunnel entrance tile red. */
2066 SetTunnelBridgeSignalState(v->tile, SIGNAL_STATE_RED);
2067 MarkTileDirtyByTile(v->tile);
2068 /* Clear counters. */
2069 v->wait_counter = 0;
2070 v->tunnel_bridge_signal_num = 0;
2071 return;
2074 /* TrainExitDir does not always produce the desired dir for depots and
2075 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2076 DiagDirection dir = TrainExitDir(v->direction, v->track);
2077 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
2079 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
2080 /* If we are currently on a tile with conventional signals, we can't treat the
2081 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2082 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
2083 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
2084 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
2086 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2087 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
2089 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
2090 if (TryPathReserve(v, false, first_tile_okay)) {
2091 /* Do a look-ahead now in case our current tile was already a safe tile. */
2092 CheckNextTrainTile(v);
2093 } else if (v->current_order.GetType() != OT_LOADING) {
2094 /* Do not wait for a way out when we're still loading */
2095 MarkTrainAsStuck(v);
2097 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2098 /* A train not inside a PBS block can't be stuck. */
2099 ClrBit(v->flags, VRF_TRAIN_STUCK);
2100 v->wait_counter = 0;
2105 * Reverse train.
2106 * @param tile unused
2107 * @param flags type of operation
2108 * @param p1 train to reverse
2109 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
2110 * @param text unused
2111 * @return the cost of this operation or an error
2113 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2115 Train *v = Train::GetIfValid(p1);
2116 if (v == NULL) return CMD_ERROR;
2118 CommandCost ret = CheckOwnership(v->owner);
2119 if (ret.Failed()) return ret;
2121 if (p2 != 0) {
2122 /* turn a single unit around */
2124 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
2125 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2127 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
2129 Train *front = v->First();
2130 /* make sure the vehicle is stopped in the depot */
2131 if (!front->IsStoppedInDepot()) {
2132 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2135 if (flags & DC_EXEC) {
2136 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
2138 front->ConsistChanged(CCF_ARRANGE);
2139 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
2140 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2141 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
2142 SetWindowClassesDirty(WC_TRAINS_LIST);
2144 } else {
2145 /* turn the whole train around */
2146 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
2148 if (flags & DC_EXEC) {
2149 /* Properly leave the station if we are loading and won't be loading anymore */
2150 if (v->current_order.IsType(OT_LOADING)) {
2151 const Vehicle *last = v;
2152 while (last->Next() != NULL) last = last->Next();
2154 /* not a station || different station --> leave the station */
2155 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2156 v->LeaveStation();
2160 /* We cancel any 'skip signal at dangers' here */
2161 v->force_proceed = TFP_NONE;
2162 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2164 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2165 ToggleBit(v->flags, VRF_REVERSING);
2166 } else {
2167 v->cur_speed = 0;
2168 v->SetLastSpeed();
2169 HideFillingPercent(&v->fill_percent_te_id);
2170 ReverseTrainDirection(v);
2174 return CommandCost();
2178 * Force a train through a red signal
2179 * @param tile unused
2180 * @param flags type of operation
2181 * @param p1 train to ignore the red signal
2182 * @param p2 unused
2183 * @param text unused
2184 * @return the cost of this operation or an error
2186 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2188 Train *t = Train::GetIfValid(p1);
2189 if (t == NULL) return CMD_ERROR;
2191 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2193 CommandCost ret = CheckOwnership(t->owner);
2194 if (ret.Failed()) return ret;
2197 if (flags & DC_EXEC) {
2198 /* If we are forced to proceed, cancel that order.
2199 * If we are marked stuck we would want to force the train
2200 * to proceed to the next signal. In the other cases we
2201 * would like to pass the signal at danger and run till the
2202 * next signal we encounter. */
2203 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2204 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2207 return CommandCost();
2211 * Try to find a depot nearby.
2212 * @param v %Train that wants a depot.
2213 * @param max_distance Maximal search distance.
2214 * @return Information where the closest train depot is located.
2215 * @pre The given vehicle must not be crashed!
2217 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2219 assert(!(v->vehstatus & VS_CRASHED));
2221 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2223 PBSTileInfo origin = FollowTrainReservation(v);
2224 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2226 switch (_settings_game.pf.pathfinder_for_trains) {
2227 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2228 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2230 default: NOT_REACHED();
2235 * Locate the closest depot for this consist, and return the information to the caller.
2236 * @param location [out] If not \c NULL and a depot is found, store its location in the given address.
2237 * @param destination [out] If not \c NULL and a depot is found, store its index in the given address.
2238 * @param reverse [out] If not \c NULL and a depot is found, store reversal information in the given address.
2239 * @return A depot has been found.
2241 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2243 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2244 if (tfdd.best_length == UINT_MAX) return false;
2246 if (location != NULL) *location = tfdd.tile;
2247 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2248 if (reverse != NULL) *reverse = tfdd.reverse;
2250 return true;
2253 /** Play a sound for a train leaving the station. */
2254 void Train::PlayLeaveStationSound() const
2256 static const SoundFx sfx[] = {
2257 SND_04_TRAIN,
2258 SND_0A_TRAIN_HORN,
2259 SND_0A_TRAIN_HORN,
2260 SND_47_MAGLEV_2,
2261 SND_41_MAGLEV
2264 if (PlayVehicleSound(this, VSE_START)) return;
2266 EngineID engtype = this->engine_type;
2267 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2271 * Check if the train is on the last reserved tile and try to extend the path then.
2272 * @param v %Train that needs its path extended.
2274 static void CheckNextTrainTile(Train *v)
2276 /* Don't do any look-ahead if path_backoff_interval is 255. */
2277 if (_settings_game.pf.path_backoff_interval == 255) return;
2279 /* Exit if we are inside a depot. */
2280 if (v->track == TRACK_BIT_DEPOT) return;
2282 switch (v->current_order.GetType()) {
2283 /* Exit if we reached our destination depot. */
2284 case OT_GOTO_DEPOT:
2285 if (v->tile == v->dest_tile) return;
2286 break;
2288 case OT_GOTO_WAYPOINT:
2289 /* If we reached our waypoint, make sure we see that. */
2290 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2291 break;
2293 case OT_NOTHING:
2294 case OT_LEAVESTATION:
2295 case OT_LOADING:
2296 /* Exit if the current order doesn't have a destination, but the train has orders. */
2297 if (v->GetNumOrders() > 0) return;
2298 break;
2300 default:
2301 break;
2303 /* Exit if we are on a station tile and are going to stop. */
2304 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2306 Trackdir td = v->GetVehicleTrackdir();
2308 /* On a tile with a red non-pbs signal, don't look ahead. */
2309 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2310 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2311 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2313 CFollowTrackRail ft(v);
2314 if (!ft.Follow(v->tile, td)) return;
2316 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2317 /* Next tile is not reserved. */
2318 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2319 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2320 /* If the next tile is a PBS signal, try to make a reservation. */
2321 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2322 if (_settings_game.pf.forbid_90_deg) {
2323 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2325 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
2332 * Will the train stay in the depot the next tick?
2333 * @param v %Train to check.
2334 * @return True if it stays in the depot, false otherwise.
2336 static bool CheckTrainStayInDepot(Train *v)
2338 /* bail out if not all wagons are in the same depot or not in a depot at all */
2339 for (const Train *u = v; u != NULL; u = u->Next()) {
2340 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2343 /* if the train got no power, then keep it in the depot */
2344 if (v->gcache.cached_power == 0) {
2345 v->vehstatus |= VS_STOPPED;
2346 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2347 return true;
2350 if (v->current_order.IsWaitTimetabled())
2351 v->HandleWaiting(false);
2352 if (v->current_order.IsType(OT_WAITING))
2353 return true;
2355 SigSegState seg_state;
2357 if (v->force_proceed == TFP_NONE) {
2358 /* force proceed was not pressed */
2359 if (++v->wait_counter < 37) {
2360 SetWindowClassesDirty(WC_TRAINS_LIST);
2361 return true;
2364 v->wait_counter = 0;
2366 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2367 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2368 /* Full and no PBS signal in block or depot reserved, can't exit. */
2369 SetWindowClassesDirty(WC_TRAINS_LIST);
2370 return true;
2372 } else {
2373 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2376 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2377 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2378 /* We need to have a reservation for this to work. */
2379 if (HasDepotReservation(v->tile)) return true;
2380 SetDepotReservation(v->tile, true);
2381 VehicleEnterDepot(v);
2382 return true;
2385 /* Only leave when we can reserve a path to our destination. */
2386 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2387 /* No path and no force proceed. */
2388 SetWindowClassesDirty(WC_TRAINS_LIST);
2389 MarkTrainAsStuck(v);
2390 return true;
2393 SetDepotReservation(v->tile, true);
2394 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
2396 VehicleServiceInDepot(v);
2397 SetWindowClassesDirty(WC_TRAINS_LIST);
2398 v->PlayLeaveStationSound();
2400 v->track = TRACK_BIT_X;
2401 if (v->direction & 2) v->track = TRACK_BIT_Y;
2403 v->vehstatus &= ~VS_HIDDEN;
2404 v->cur_speed = 0;
2406 v->UpdateViewport(true, true);
2407 v->UpdatePosition();
2408 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2409 v->UpdateAcceleration();
2410 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2412 return false;
2415 static int GetAndClearLastBridgeEntranceSetSignalIndex(TileIndex bridge_entrance)
2417 uint16 m = _m[bridge_entrance].m2;
2418 if (m & 0x8000) {
2419 auto it = _long_bridge_signal_sim_map.find(bridge_entrance);
2420 if (it != _long_bridge_signal_sim_map.end()) {
2421 LongBridgeSignalStorage &lbss = it->second;
2422 size_t slot = lbss.signal_red_bits.size();
2423 while (slot > 0) {
2424 slot--;
2425 uint64 &slot_bits = lbss.signal_red_bits[slot];
2426 if (slot_bits) {
2427 uint8 i = FindLastBit(slot_bits);
2428 ClrBit(slot_bits, i);
2429 return 1 + 15 + (64 * slot) + i;
2434 if (m & 0x7FFF) {
2435 uint8 i = FindLastBit(m & 0x7FFF);
2436 ClrBit(_m[bridge_entrance].m2, i);
2437 return 1 + i;
2440 return 0;
2443 static void HandleLastTunnelBridgeSignals(TileIndex tile, TileIndex end, DiagDirection dir, bool free)
2445 if (IsBridge(end) && _m[end].m2 != 0) {
2446 /* Clearing last bridge signal. */
2447 int signal_offset = GetAndClearLastBridgeEntranceSetSignalIndex(end);
2448 if (signal_offset) {
2449 TileIndex last_signal_tile = end + (TileOffsByDiagDir(dir) * _settings_game.construction.simulated_wormhole_signals * signal_offset);
2450 MarkTileDirtyByTile(last_signal_tile);
2452 MarkTileDirtyByTile(tile);
2454 if (free) {
2455 /* Open up the wormhole and clear m2. */
2456 if (IsBridge(end)) {
2457 SetAllBridgeEntranceSimulatedSignalsGreen(end);
2460 if (IsTunnelBridgeSignalSimulationEntrance(end) && GetTunnelBridgeSignalState(end) == SIGNAL_STATE_RED) {
2461 SetTunnelBridgeSignalState(end, SIGNAL_STATE_GREEN);
2462 MarkTileDirtyByTile(end);
2463 } else if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
2464 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
2465 MarkTileDirtyByTile(tile);
2470 static void UnreserveBridgeTunnelTile(TileIndex tile)
2472 SetTunnelBridgeReservation(tile, false);
2473 if (IsTunnelBridgeSignalSimulationExit(tile) && IsTunnelBridgePBS(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_RED);
2477 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2478 * @param v %Train owning the reservation.
2479 * @param tile Tile with reservation to clear.
2480 * @param track_dir Track direction to clear.
2482 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir, bool clear_unsignaled_other_end = false)
2484 DiagDirection dir = TrackdirToExitdir(track_dir);
2486 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2487 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2488 bool free = TunnelBridgeIsFree(tile, end, v).Succeeded();
2489 UnreserveBridgeTunnelTile(tile);
2491 if (IsTunnelBridgeWithSignalSimulation(tile)) {
2492 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2493 HandleLastTunnelBridgeSignals(tile, end, dir, free);
2496 else if (clear_unsignaled_other_end)
2498 UnreserveBridgeTunnelTile(end);
2501 if (_settings_client.gui.show_track_reservation) {
2502 MarkTileDirtyByTile(tile);
2503 MarkTileDirtyByTile(end);
2505 } else if (IsRailStationTile(tile)) {
2506 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2507 /* If the new tile is not a further tile of the same station, we
2508 * clear the reservation for the whole platform. */
2509 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2510 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2512 } else {
2513 /* Any other tile */
2514 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2519 * Free the reserved path in front of a vehicle.
2520 * @param v %Train owning the reserved path.
2521 * @param origin %Tile to start clearing (if #INVALID_TILE, use the current tile of \a v).
2522 * @param orig_td Track direction (if #INVALID_TRACKDIR, use the track direction of \a v).
2524 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
2526 assert(v->IsFrontEngine());
2528 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
2529 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
2530 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2531 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2533 /* Can't be holding a reservation if we enter a depot. */
2534 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2535 if (v->track == TRACK_BIT_DEPOT) {
2536 /* Front engine is in a depot. We enter if some part is not in the depot. */
2537 for (const Train *u = v; u != NULL; u = u->Next()) {
2538 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2541 /* Don't free reservation if it's not ours. */
2542 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2544 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2545 while (ft.Follow(tile, td)) {
2546 tile = ft.m_new_tile;
2547 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2548 td = RemoveFirstTrackdir(&bits);
2549 assert(bits == TRACKDIR_BIT_NONE);
2551 if (!IsValidTrackdir(td)) break;
2553 if (IsTileType(tile, MP_RAILWAY)) {
2554 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2555 /* Conventional signal along trackdir: remove reservation and stop. */
2556 UnreserveRailTrack(tile, TrackdirToTrack(td));
2557 break;
2559 if (HasPbsSignalOnTrackdir(tile, td)) {
2560 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2561 /* Red PBS signal? Can't be our reservation, would be green then. */
2562 break;
2563 } else {
2564 /* Turn the signal back to red. */
2565 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2566 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2568 /* notify logic signals of the state change */
2569 SignalStateChanged(tile, TrackdirToTrack(td), 1);
2571 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2572 break;
2575 else if (IsTunnelBridgeWithSignalSimulation(tile)) {
2576 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2577 bool free = TunnelBridgeIsFree(tile, end, v).Succeeded();
2579 if (!free && GetTunnelBridgeDirection(tile) == ReverseDiagDir(TrackdirToExitdir(td))) break;
2582 /* Don't free first station/bridge/tunnel if we are on it. */
2583 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);
2585 free_tile = true;
2589 static const byte _initial_tile_subcoord[6][4][3] = {
2590 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2591 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2592 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2593 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2594 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2595 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2599 * Perform pathfinding for a train.
2601 * @param v The train
2602 * @param tile The tile the train is about to enter
2603 * @param enterdir Diagonal direction the train is coming from
2604 * @param tracks Usable tracks on the new tile
2605 * @param path_found [out] Whether a path has been found or not.
2606 * @param do_track_reservation Path reservation is requested
2607 * @param dest [out] State and destination of the requested path
2608 * @return The best track the train should follow
2610 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2612 switch (_settings_game.pf.pathfinder_for_trains) {
2613 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2614 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2616 default: NOT_REACHED();
2621 * Extend a train path as far as possible. Stops on encountering a safe tile,
2622 * another reservation or a track choice.
2623 * @param v The train.
2624 * @param origin The tile from which the reservation have to be extended
2625 * @param new_tracks [out] Tracks to choose from when encountering a choice
2626 * @param enterdir [out] The direction from which the choice tile is to be entered
2627 * @return INVALID_TILE indicates that the reservation failed.
2629 static PBSTileInfo ExtendTrainReservation(const Train *v, const PBSTileInfo &origin, TrackBits *new_tracks, DiagDirection *enterdir)
2631 CFollowTrackRail ft(v);
2633 TileIndex tile = origin.tile;
2634 Trackdir cur_td = origin.trackdir;
2635 while (ft.Follow(tile, cur_td)) {
2636 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2637 /* Possible signal tile. */
2638 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2641 if (_settings_game.pf.forbid_90_deg) {
2642 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2643 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2646 /* Station, depot or waypoint are a possible target. */
2647 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2648 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2649 /* Choice found or possible target encountered.
2650 * On finding a possible target, we need to stop and let the pathfinder handle the
2651 * remaining path. This is because we don't know if this target is in one of our
2652 * orders, so we might cause pathfinding to fail later on if we find a choice.
2653 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2654 * a wrong path not leading to our next destination. */
2655 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2657 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2658 * actually starts its search at the first unreserved tile. */
2659 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2661 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2662 if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2663 if (enterdir != NULL) *enterdir = ft.m_exitdir;
2664 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2667 tile = ft.m_new_tile;
2668 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2670 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2671 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2672 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2673 /* Safe position is all good, path valid and okay. */
2674 return PBSTileInfo(tile, cur_td, true);
2677 if (!TryReserveRailTrackdir(tile, cur_td)) break;
2680 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2681 /* End of line, path valid and okay. */
2682 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2685 /* Sorry, can't reserve path, back out. */
2686 tile = origin.tile;
2687 cur_td = origin.trackdir;
2688 TileIndex stopped = ft.m_old_tile;
2689 Trackdir stopped_td = ft.m_old_td;
2690 while (tile != stopped || cur_td != stopped_td) {
2691 if (!ft.Follow(tile, cur_td)) break;
2693 if (_settings_game.pf.forbid_90_deg) {
2694 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2695 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2697 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2699 tile = ft.m_new_tile;
2700 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2702 UnreserveRailTrackdir(tile, cur_td);
2705 /* Path invalid. */
2706 return PBSTileInfo();
2710 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2711 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2713 * @param v The vehicle.
2714 * @param tile The tile the search should start from.
2715 * @param td The trackdir the search should start from.
2716 * @param override_railtype Whether all physically compatible railtypes should be followed.
2717 * @return True if a path to a safe stopping tile could be reserved.
2719 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
2721 switch (_settings_game.pf.pathfinder_for_trains) {
2722 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2723 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2725 default: NOT_REACHED();
2729 /** This class will save the current order of a vehicle and restore it on destruction. */
2730 class VehicleOrderSaver {
2731 private:
2732 Train *v;
2733 Order old_order;
2734 TileIndex old_dest_tile;
2735 StationID old_last_station_visited;
2736 VehicleOrderID index;
2737 bool suppress_implicit_orders;
2739 public:
2740 VehicleOrderSaver(Train *_v) :
2741 v(_v),
2742 old_order(_v->current_order),
2743 old_dest_tile(_v->dest_tile),
2744 old_last_station_visited(_v->last_station_visited),
2745 index(_v->cur_real_order_index),
2746 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2750 ~VehicleOrderSaver()
2752 this->v->current_order = this->old_order;
2753 this->v->dest_tile = this->old_dest_tile;
2754 this->v->last_station_visited = this->old_last_station_visited;
2755 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2759 * Set the current vehicle order to the next order in the order list.
2760 * @param skip_first Shall the first (i.e. active) order be skipped?
2761 * @return True if a suitable next order could be found.
2763 bool SwitchToNextOrder(bool skip_first)
2765 if (this->v->GetNumOrders() == 0) return false;
2767 if (skip_first) ++this->index;
2769 int depth = 0;
2770 bool has_manual_depot_order = (HasBit(v->vehicle_flags, VF_SHOULD_GOTO_DEPOT) || HasBit(v->vehicle_flags, VF_SHOULD_SERVICE_AT_DEPOT));
2772 do {
2773 /* Wrap around. */
2774 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2776 Order *order = this->v->GetOrder(this->index);
2777 assert(order != NULL);
2779 switch (order->GetType()) {
2780 case OT_GOTO_DEPOT:
2781 /* Skip service in depot orders when the train doesn't need service. */
2782 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !(this->v->NeedsServicing() || has_manual_depot_order)) break;
2783 FALLTHROUGH;
2784 case OT_GOTO_STATION:
2785 case OT_GOTO_WAYPOINT:
2786 this->v->current_order = *order;
2787 return UpdateOrderDest(this->v, order, 0, true);
2788 case OT_CONDITIONAL: {
2789 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2790 if (next != INVALID_VEH_ORDER_ID) {
2791 depth++;
2792 this->index = next;
2793 /* Don't increment next, so no break here. */
2794 continue;
2796 break;
2798 default:
2799 break;
2801 /* Don't increment inside the while because otherwise conditional
2802 * orders can lead to an infinite loop. */
2803 ++this->index;
2804 depth++;
2805 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2807 return false;
2812 * This is called to retrieve the previous signal, as required
2813 * This is not run all the time as it is somewhat expensive and most restrictions will not test for the previous signal
2815 static TileIndex ChooseTrainTrackTraceRestrictPreviousSignalCallback(const Train *v, const void *)
2817 // scan forwards from vehicle position, for the case that train is waiting at/approaching PBS signal
2819 TileIndex tile = v->tile;
2820 Trackdir trackdir = v->GetVehicleTrackdir();
2822 CFollowTrackRail ft(v);
2824 for (;;) {
2825 if (IsTileType(tile, MP_RAILWAY) && HasSignalOnTrackdir(tile, trackdir)) {
2826 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2827 // found PBS signal
2828 return tile;
2829 } else {
2830 // wrong type of signal
2831 return INVALID_TILE;
2835 // advance to next tile
2836 if (!ft.Follow(tile, trackdir)) {
2837 // ran out of track
2838 return INVALID_TILE;
2841 if (KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2842 // reached a junction tile
2843 return INVALID_TILE;
2846 tile = ft.m_new_tile;
2847 trackdir = FindFirstTrackdir(ft.m_new_td_bits);
2851 static bool HasLongReservePbsSignalOnTrackdir(Train* v, TileIndex tile, Trackdir trackdir)
2853 if (HasPbsSignalOnTrackdir(tile, trackdir)) {
2854 if (IsRestrictedSignal(tile)) {
2855 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(tile, TrackdirToTrack(trackdir));
2856 if (prog && prog->actions_used_flags & TRPAUF_LONG_RESERVE) {
2857 TraceRestrictProgramResult out;
2858 prog->Execute(v, TraceRestrictProgramInput(tile, trackdir, &ChooseTrainTrackTraceRestrictPreviousSignalCallback, nullptr), out);
2859 if (out.flags & TRPRF_LONG_RESERVE) {
2860 return true;
2866 return false;
2870 * Choose a track and reserve if necessary
2872 * @param v The vehicle
2873 * @param tile The tile from which to start
2874 * @param enterdir
2875 * @param tracks
2876 * @param force_res Force a reservation to be made
2877 * @param p_got_reservation [out] If the train has a reservation
2878 * @param mark_stuck The train has to be marked as stuck when needed
2879 * @return The track the train should take.
2881 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *p_got_reservation, bool mark_stuck)
2883 Track best_track = INVALID_TRACK;
2884 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2885 bool changed_signal = false;
2886 bool got_reservation = false;
2887 if (p_got_reservation != NULL) *p_got_reservation = got_reservation;
2889 assert((tracks & ~TRACK_BIT_MASK) == 0);
2891 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2892 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2893 /* Do we have a suitable reserved track? */
2894 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2896 /* Quick return in case only one possible track is available */
2897 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2898 Track track = FindFirstTrack(tracks);
2899 /* We need to check for signals only here, as a junction tile can't have signals. */
2900 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2901 if (IsRestrictedSignal(tile) && v->force_proceed != TFP_SIGNAL) {
2902 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(tile, track);
2903 if (prog && prog->actions_used_flags & (TRPAUF_WAIT_AT_PBS | TRPAUF_SLOT_ACQUIRE)) {
2904 TraceRestrictProgramResult out;
2905 TraceRestrictProgramInput input(tile, TrackEnterdirToTrackdir(track, enterdir), NULL, NULL);
2906 input.permitted_slot_operations = TRPISP_ACQUIRE;
2907 prog->Execute(v, input, out);
2908 if (out.flags & TRPRF_WAIT_AT_PBS) {
2909 if (mark_stuck) MarkTrainAsStuck(v, true);
2910 return track;
2914 ClrBit(v->flags, VRF_WAITING_RESTRICTION);
2916 do_track_reservation = true;
2917 changed_signal = true;
2918 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2920 /* notify logic signals of the state change */
2921 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(track, enterdir)), 1);
2922 } else if (!do_track_reservation) {
2923 return track;
2925 best_track = track;
2928 PBSTileInfo origin = FollowTrainReservation(v);
2929 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2930 DiagDirection dest_enterdir = enterdir;
2931 if (do_track_reservation) {
2932 res_dest = ExtendTrainReservation(v, origin, &tracks, &dest_enterdir);
2933 if (res_dest.tile == INVALID_TILE) {
2934 /* Reservation failed? */
2935 if (mark_stuck) MarkTrainAsStuck(v);
2936 if (changed_signal) {
2937 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2939 /* notify logic signals of the state change */
2940 SignalStateChanged(tile, TrackdirToTrack(TrackEnterdirToTrackdir(best_track, enterdir)), 1);
2942 return FindFirstTrack(tracks);
2945 if (res_dest.okay) {
2946 CFollowTrackRail ft(v);
2947 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
2948 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
2950 if (!HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
2951 /* Got a valid reservation that ends at a safe target, quick exit. */
2952 if (p_got_reservation != NULL) *p_got_reservation = true;
2953 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
2954 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2955 return best_track;
2960 /* Check if the train needs service here, so it has a chance to always find a depot.
2961 * Also check if the current order is a service order so we don't reserve a path to
2962 * the destination but instead to the next one if service isn't needed. */
2963 CheckIfTrainNeedsService(v);
2964 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2967 /* Save the current train order. The destructor will restore the old order on function exit. */
2968 VehicleOrderSaver orders(v);
2970 /* If the current tile is the destination of the current order and
2971 * a reservation was requested, advance to the next order.
2972 * Don't advance on a depot order as depots are always safe end points
2973 * for a path and no look-ahead is necessary. This also avoids a
2974 * problem with depot orders not part of the order list when the
2975 * order list itself is empty. */
2976 if (v->current_order.IsType(OT_LEAVESTATION)) {
2977 orders.SwitchToNextOrder(false);
2978 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2979 v->current_order.IsType(OT_GOTO_STATION) ?
2980 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2981 v->tile == v->dest_tile))) {
2982 orders.SwitchToNextOrder(true);
2985 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2986 /* Pathfinders are able to tell that route was only 'guessed'. */
2987 bool path_found = true;
2988 TileIndex new_tile = res_dest.tile;
2990 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2991 if (new_tile == tile) best_track = next_track;
2992 v->HandlePathfindingResult(path_found);
2995 /* No track reservation requested -> finished. */
2996 if (!do_track_reservation) return best_track;
2998 /* A path was found, but could not be reserved. */
2999 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
3000 if (mark_stuck) MarkTrainAsStuck(v);
3001 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3002 return best_track;
3005 /* No possible reservation target found, we are probably lost. */
3006 if (res_dest.tile == INVALID_TILE) {
3007 /* Try to find any safe destination. */
3008 PBSTileInfo path_end = FollowTrainReservation(v);
3009 if (TryReserveSafeTrack(v, path_end.tile, path_end.trackdir, false)) {
3010 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
3011 best_track = FindFirstTrack(res);
3012 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
3013 // Use p_got_reservation because were going to return
3014 if (p_got_reservation != NULL) *p_got_reservation = true;
3015 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
3016 } else {
3017 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3018 if (mark_stuck) MarkTrainAsStuck(v);
3020 return best_track;
3023 got_reservation = true;
3025 /* Reservation target found and free, check if it is safe. */
3026 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
3027 /* Extend reservation until we have found a safe position. */
3028 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
3029 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
3030 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
3031 if (_settings_game.pf.forbid_90_deg) {
3032 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
3035 /* Get next order with destination. */
3036 if (orders.SwitchToNextOrder(true)) {
3037 PBSTileInfo cur_dest;
3038 bool path_found;
3039 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
3040 if (cur_dest.tile != INVALID_TILE) {
3041 res_dest = cur_dest;
3042 if (res_dest.okay) continue;
3043 /* Path found, but could not be reserved. */
3044 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3045 if (mark_stuck) MarkTrainAsStuck(v);
3046 got_reservation = false;
3047 changed_signal = false;
3048 break;
3051 /* No order or no safe position found, try any position. */
3052 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
3053 FreeTrainTrackReservation(v, origin.tile, origin.trackdir);
3054 if (mark_stuck) MarkTrainAsStuck(v);
3055 got_reservation = false;
3056 changed_signal = false;
3058 break;
3061 if (got_reservation) {
3062 CFollowTrackRail ft(v);
3063 if (ft.Follow(res_dest.tile, res_dest.trackdir)) {
3064 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
3066 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
3067 // We reserved up to a LR signal, reserve past it as well. recursion
3068 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), force_res, NULL, mark_stuck);
3073 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
3075 if (changed_signal) MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
3076 if (p_got_reservation != NULL) *p_got_reservation = got_reservation;
3078 return best_track;
3082 * Try to reserve a path to a safe position.
3084 * @param v The vehicle
3085 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
3086 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
3087 * @return True if a path could be reserved.
3089 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
3091 assert(v->IsFrontEngine());
3093 /* We have to handle depots specially as the track follower won't look
3094 * at the depot tile itself but starts from the next tile. If we are still
3095 * inside the depot, a depot reservation can never be ours. */
3096 if (v->track == TRACK_BIT_DEPOT) {
3097 if (HasDepotReservation(v->tile)) {
3098 if (mark_as_stuck) MarkTrainAsStuck(v);
3099 return false;
3100 } else {
3101 /* Depot not reserved, but the next tile might be. */
3102 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
3103 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
3107 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(v->tile) &&
3108 DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile)) == v->track) {
3109 // prevent any attempt to reserve the wrong way onto a tunnel/bridge exit
3110 return false;
3113 Vehicle *other_train = NULL;
3114 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
3115 /* The path we are driving on is already blocked by some other train.
3116 * This can only happen in certain situations when mixing path and
3117 * block signals or when changing tracks and/or signals.
3118 * Exit here as doing any further reservations will probably just
3119 * make matters worse. */
3120 if (other_train != NULL && other_train->index != v->index) {
3121 if (mark_as_stuck) MarkTrainAsStuck(v);
3122 return false;
3124 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
3125 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
3126 /* Can't be stuck then. */
3127 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3128 ClrBit(v->flags, VRF_TRAIN_STUCK);
3129 return true;
3132 /* If we are in a depot, tentatively reserve the depot. */
3133 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) {
3134 SetDepotReservation(v->tile, true);
3135 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile, ZOOM_LVL_DRAW_MAP);
3138 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
3139 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
3140 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
3142 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
3144 bool res_made = false;
3145 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
3147 if (!res_made) {
3148 /* Free the depot reservation as well. */
3149 if (v->track == TRACK_BIT_DEPOT && v->tile == origin.tile) SetDepotReservation(v->tile, false);
3150 return false;
3153 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
3154 v->wait_counter = 0;
3155 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3157 ClrBit(v->flags, VRF_TRAIN_STUCK);
3158 return true;
3162 static bool CheckReverseTrain(const Train *v)
3164 if (_settings_game.difficulty.line_reverse_mode != 0 ||
3165 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
3166 !(v->direction & 1)) {
3167 return false;
3170 assert(v->track != TRACK_BIT_NONE);
3172 switch (_settings_game.pf.pathfinder_for_trains) {
3173 case VPF_NPF: return NPFTrainCheckReverse(v);
3174 case VPF_YAPF: return YapfTrainCheckReverse(v);
3176 default: NOT_REACHED();
3181 * Get the location of the next station to visit.
3182 * @param station Next station to visit.
3183 * @return Location of the new station.
3185 TileIndex Train::GetOrderStationLocation(StationID station)
3187 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
3189 const Station *st = Station::Get(station);
3190 if (!(st->facilities & FACIL_TRAIN)) {
3191 /* The destination station has no trainstation tiles. */
3192 this->IncrementRealOrderIndex();
3193 return 0;
3196 return st->xy;
3199 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
3200 void Train::MarkDirty()
3202 Train *v = this;
3203 do {
3204 v->colourmap = PAL_NONE;
3205 v->UpdateViewport(true, false);
3206 } while ((v = v->Next()) != NULL);
3208 /* need to update acceleration and cached values since the goods on the train changed. */
3209 this->CargoChanged();
3210 this->UpdateAcceleration();
3214 * This function looks at the vehicle and updates its speed (cur_speed
3215 * and subspeed) variables. Furthermore, it returns the distance that
3216 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
3217 * the distance to drive before moving a step on the map.
3218 * @return distance to drive.
3220 int Train::UpdateSpeed()
3222 switch (_settings_game.vehicle.train_acceleration_model) {
3223 default: NOT_REACHED();
3224 case AM_ORIGINAL:
3225 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
3227 case AM_REALISTIC:
3228 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
3233 * Trains enters a station, send out a news item if it is the first train, and start loading.
3234 * @param v Train that entered the station.
3235 * @param station Station visited.
3237 static void TrainEnterStation(Train *v, StationID station)
3239 v->last_station_visited = station;
3241 /* check if a train ever visited this station before */
3242 Station *st = Station::Get(station);
3243 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
3244 st->had_vehicle_of_type |= HVOT_TRAIN;
3245 SetDParam(0, st->index);
3246 AddVehicleNewsItem(
3247 STR_NEWS_FIRST_TRAIN_ARRIVAL,
3248 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
3249 v->index,
3250 st->index
3252 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
3253 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
3256 v->force_proceed = TFP_NONE;
3257 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3259 v->BeginLoading();
3261 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
3262 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
3265 /* Check if the vehicle is compatible with the specified tile */
3266 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
3268 return IsTileOwner(tile, v->owner) &&
3269 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
3272 /** Data structure for storing engine speed changes of an acceleration type. */
3273 struct AccelerationSlowdownParams {
3274 byte small_turn; ///< Speed change due to a small turn.
3275 byte large_turn; ///< Speed change due to a large turn.
3276 byte z_up; ///< Fraction to remove when moving up.
3277 byte z_down; ///< Fraction to add when moving down.
3280 /** Speed update fractions for each acceleration type. */
3281 static const AccelerationSlowdownParams _accel_slowdown[] = {
3282 /* normal accel */
3283 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
3284 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
3285 {0, 256 / 2, 256 / 4, 2}, ///< maglev
3289 * Modify the speed of the vehicle due to a change in altitude.
3290 * @param v %Train to update.
3291 * @param old_z Previous height.
3293 static inline void AffectSpeedByZChange(Train *v, int old_z)
3295 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3297 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3299 if (old_z < v->z_pos) {
3300 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3301 } else {
3302 uint16 spd = v->cur_speed + asp->z_down;
3303 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3307 enum TrainMovedChangeSignalEnum {
3308 CHANGED_NOTHING, ///< No special signals were changed
3309 CHANGED_NORMAL_TO_PBS_BLOCK, ///< A PBS block with a non-PBS signal facing us
3310 CHANGED_LR_PBS ///< A long reserve PBS signal
3313 static TrainMovedChangeSignalEnum TrainMovedChangeSignal(Train* v, TileIndex tile, DiagDirection dir)
3315 if (IsTileType(tile, MP_RAILWAY) &&
3316 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
3317 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
3318 Trackdir trackdir = FindFirstTrackdir(tracks);
3319 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3320 /* A PBS block with a non-PBS signal facing us? */
3321 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return CHANGED_NORMAL_TO_PBS_BLOCK;
3323 if (HasLongReservePbsSignalOnTrackdir(v, tile, trackdir)) return CHANGED_LR_PBS;
3327 if (IsTileType(tile, MP_TUNNELBRIDGE) && IsTunnelBridgeSignalSimulationExit(tile) && GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
3328 if (UpdateSignalsOnSegment(tile, dir, GetTileOwner(tile)) == SIGSEG_PBS) {
3329 return CHANGED_NORMAL_TO_PBS_BLOCK;
3333 return CHANGED_NOTHING;
3336 /** Tries to reserve track under whole train consist. */
3337 void Train::ReserveTrackUnderConsist() const
3339 for (const Train *u = this; u != NULL; u = u->Next()) {
3340 switch (u->track) {
3341 case TRACK_BIT_WORMHOLE:
3342 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3343 break;
3344 case TRACK_BIT_DEPOT:
3345 break;
3346 default:
3347 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3348 break;
3354 * The train vehicle crashed!
3355 * Update its status and other parts around it.
3356 * @param flooded Crash was caused by flooding.
3357 * @return Number of people killed.
3359 uint Train::Crash(bool flooded)
3361 uint pass = 0;
3362 if (this->IsFrontEngine()) {
3363 pass += 2; // driver
3365 /* Remove the reserved path in front of the train if it is not stuck.
3366 * Also clear all reserved tracks the train is currently on. */
3367 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3368 for (const Train *v = this; v != NULL; v = v->Next()) {
3369 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3370 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3371 /* ClearPathReservation will not free the wormhole exit
3372 * if the train has just entered the wormhole. */
3373 UnreserveBridgeTunnelTile(GetOtherTunnelBridgeEnd(v->tile));
3377 /* we may need to update crossing we were approaching,
3378 * but must be updated after the train has been marked crashed */
3379 TileIndex crossing = TrainApproachingCrossingTile(this);
3380 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3382 /* Remove the loading indicators (if any) */
3383 HideFillingPercent(&this->fill_percent_te_id);
3386 pass += this->GroundVehicleBase::Crash(flooded);
3388 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3389 return pass;
3393 * Marks train as crashed and creates an AI event.
3394 * Doesn't do anything if the train is crashed already.
3395 * @param v first vehicle of chain
3396 * @return number of victims (including 2 drivers; zero if train was already crashed)
3398 static uint TrainCrashed(Train *v)
3400 uint num = 0;
3402 /* do not crash train twice */
3403 if (!(v->vehstatus & VS_CRASHED)) {
3404 num = v->Crash();
3405 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3406 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3409 /* Try to re-reserve track under already crashed train too.
3410 * Crash() clears the reservation! */
3411 v->ReserveTrackUnderConsist();
3413 return num;
3416 /** Temporary data storage for testing collisions. */
3417 struct TrainCollideChecker {
3418 Train *v; ///< %Vehicle we are testing for collision.
3419 uint num; ///< Total number of victims if train collided.
3423 * Collision test function.
3424 * @param v %Train vehicle to test collision with.
3425 * @param data %Train being examined.
3426 * @return \c NULL (always continue search)
3428 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3430 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3432 /* not a train or in depot */
3433 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
3435 /* do not crash into trains of another company. */
3436 if (v->owner != tcc->v->owner) return NULL;
3438 /* get first vehicle now to make most usual checks faster */
3439 Train *coll = Train::From(v)->First();
3441 /* can't collide with own wagons */
3442 if (coll == tcc->v) return NULL;
3444 int x_diff = v->x_pos - tcc->v->x_pos;
3445 int y_diff = v->y_pos - tcc->v->y_pos;
3447 /* Do fast calculation to check whether trains are not in close vicinity
3448 * and quickly reject trains distant enough for any collision.
3449 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3450 * Differences are then ORed and then we check for any higher bits */
3451 uint hash = (y_diff + 7) | (x_diff + 7);
3452 if (hash & ~15) return NULL;
3454 /* Slower check using multiplication */
3455 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3456 if (x_diff * x_diff + y_diff * y_diff >= min_diff * min_diff) return NULL;
3458 /* Happens when there is a train under bridge next to bridge head */
3459 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
3461 /* crash both trains */
3462 tcc->num += TrainCrashed(tcc->v);
3463 tcc->num += TrainCrashed(coll);
3465 return NULL; // continue searching
3469 * Checks whether the specified train has a collision with another vehicle. If
3470 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3471 * Reports the incident in a flashy news item, modifies station ratings and
3472 * plays a sound.
3473 * @param v %Train to test.
3475 static bool CheckTrainCollision(Train *v)
3477 /* can't collide in depot */
3478 if (v->track == TRACK_BIT_DEPOT) return false;
3480 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3482 TrainCollideChecker tcc;
3483 tcc.v = v;
3484 tcc.num = 0;
3486 /* find colliding vehicles */
3487 if (v->track == TRACK_BIT_WORMHOLE) {
3488 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3489 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3490 } else {
3491 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3494 /* any dead -> no crash */
3495 if (tcc.num == 0) return false;
3497 SetDParam(0, tcc.num);
3498 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3500 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3501 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3502 return true;
3505 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3507 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
3509 Train *t = Train::From(v);
3510 DiagDirection exitdir = *(DiagDirection *)data;
3512 /* not front engine of a train, inside wormhole or depot, crashed */
3513 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
3515 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
3517 return t;
3520 struct FindSpaceBetweenTrainsChecker {
3521 int32 pos;
3522 uint16 distance;
3523 DirectionByte direction;
3526 /** Find train in front and keep distance between trains in tunnel/bridge. */
3527 static Vehicle *FindSpaceBetweenTrainsEnum(Vehicle *v, void *data)
3529 /* Don't look at wagons between front and back of train. */
3530 if (v->type != VEH_TRAIN || (v->Previous() != NULL && v->Next() != NULL)) return NULL;
3532 const FindSpaceBetweenTrainsChecker *checker = (FindSpaceBetweenTrainsChecker*)data;
3533 int32 a, b = 0;
3535 switch (checker->direction) {
3536 default: NOT_REACHED();
3537 case DIR_NE: a = checker->pos; b = v->x_pos; break;
3538 case DIR_SE: a = v->y_pos; b = checker->pos; break;
3539 case DIR_SW: a = v->x_pos; b = checker->pos; break;
3540 case DIR_NW: a = checker->pos; b = v->y_pos; break;
3543 if (a > b && a <= (b + (int)(checker->distance)) + (int)(TILE_SIZE)-1) return v;
3544 return NULL;
3547 static bool IsTooCloseBehindTrain(Vehicle *v, TileIndex tile, uint16 distance, bool check_endtile)
3549 Train *t = Train::From(v);
3551 if (t->force_proceed != 0) return false;
3553 FindSpaceBetweenTrainsChecker checker;
3554 checker.distance = distance;
3555 checker.direction = t->direction;
3556 switch (checker.direction) {
3557 default: NOT_REACHED();
3558 case DIR_NE: checker.pos = (TileX(tile) * TILE_SIZE) + TILE_UNIT_MASK; break;
3559 case DIR_SE: checker.pos = (TileY(tile) * TILE_SIZE); break;
3560 case DIR_SW: checker.pos = (TileX(tile) * TILE_SIZE); break;
3561 case DIR_NW: checker.pos = (TileY(tile) * TILE_SIZE) + TILE_UNIT_MASK; break;
3564 if (HasVehicleOnPos(t->tile, &checker, &FindSpaceBetweenTrainsEnum)) {
3565 /* Revert train if not going with tunnel direction. */
3566 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3567 SetBit(t->flags, VRF_REVERSING);
3569 return true;
3571 /* Cover blind spot at end of tunnel bridge. */
3572 if (check_endtile){
3573 if (HasVehicleOnPos(GetOtherTunnelBridgeEnd(t->tile), &checker, &FindSpaceBetweenTrainsEnum)) {
3574 /* Revert train if not going with tunnel direction. */
3575 if (DirToDiagDir(t->direction) != GetTunnelBridgeDirection(t->tile)) {
3576 SetBit(t->flags, VRF_REVERSING);
3578 return true;
3582 return false;
3585 static bool CheckTrainStayInWormHolePathReserve(Train *t, TileIndex tile)
3587 TileIndex veh_orig = t->tile;
3588 t->tile = tile;
3589 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3590 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3591 TrackdirBits reserved = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(ft.m_new_tile));
3592 if (reserved == TRACKDIR_BIT_NONE) {
3593 /* next tile is not reserved, so reserve the exit tile */
3594 SetTunnelBridgeReservation(tile, true);
3597 bool ok = TryPathReserve(t);
3598 t->tile = veh_orig;
3599 if (ok && IsTunnelBridgePBS(tile)) SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
3600 return ok;
3603 /** Simulate signals in tunnel - bridge. */
3604 static bool CheckTrainStayInWormHole(Train *t, TileIndex tile)
3606 if (t->force_proceed != 0) return false;
3608 /* When not exit reverse train. */
3609 if (!IsTunnelBridgeSignalSimulationExit(tile)) {
3610 SetBit(t->flags, VRF_REVERSING);
3611 return true;
3613 SigSegState seg_state = (_settings_game.pf.reserve_paths || IsTunnelBridgePBS(tile)) ? SIGSEG_PBS : UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, t->owner);
3614 if (seg_state != SIGSEG_PBS) {
3615 CFollowTrackRail ft(GetTileOwner(tile), GetRailTypeInfo(t->railtype)->compatible_railtypes);
3616 if (ft.Follow(tile, DiagDirToDiagTrackdir(ReverseDiagDir(GetTunnelBridgeDirection(tile))))) {
3617 if (ft.m_new_td_bits != TRACKDIR_BIT_NONE && KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
3618 Trackdir td = FindFirstTrackdir(ft.m_new_td_bits);
3619 if (HasPbsSignalOnTrackdir(ft.m_new_tile, td)) {
3620 /* immediately after the exit, there is a PBS signal, switch to PBS mode */
3621 seg_state = SIGSEG_PBS;
3626 if (seg_state == SIGSEG_FULL || (seg_state == SIGSEG_PBS && !CheckTrainStayInWormHolePathReserve(t, tile))) {
3627 t->vehstatus |= VS_TRAIN_SLOWING;
3628 return true;
3631 return false;
3634 static void HandleSignalBehindTrain(Train *v, int signal_number)
3636 TileIndex tile;
3637 switch (v->direction) {
3638 default: NOT_REACHED();
3639 case DIR_NE: tile = TileVirtXY(v->x_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3640 case DIR_SE: tile = TileVirtXY(v->x_pos, v->y_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) ); break;
3641 case DIR_SW: tile = TileVirtXY(v->x_pos - (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals), v->y_pos); break;
3642 case DIR_NW: tile = TileVirtXY(v->x_pos, v->y_pos + (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals)); break;
3645 if(tile == v->tile) {
3646 /* Flip signal on ramp. */
3647 if (IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
3648 SetTunnelBridgeSignalState(tile, SIGNAL_STATE_GREEN);
3649 MarkTileDirtyByTile(tile);
3651 } else if (IsBridge(v->tile) && signal_number >= 0) {
3652 SetBridgeEntranceSimulatedSignalState(v->tile, signal_number, SIGNAL_STATE_GREEN);
3653 MarkTileDirtyByTile(tile);
3657 static inline void IncreaseTrackUsage(TileIndex ti, Track track_piece)
3659 if (!IsTileType(ti, MP_RAILWAY))
3660 return;
3661 if (!IsPlainRailTile(ti))
3662 return;
3664 /* ignore track_piece, 1 state per tile */
3665 byte age = GetRailAge(ti);
3667 static byte train_clean_strength = 32;
3669 if (age <= train_clean_strength)
3670 age = 0;
3671 else
3672 age -= train_clean_strength;
3674 byte old_growth = GetTrackGrowthPhase(ti);
3676 SetRailAge(ti, age);
3678 /* If rounded growth amount changes, redraw */
3679 if (GetTrackGrowthPhase(ti) != old_growth)
3680 MarkTileDirtyByTile(ti);
3683 uint16 ReversingDistanceTargetSpeed(const Train *v)
3685 int target_speed;
3686 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC) {
3687 target_speed = ((v->reverse_distance - 1) * 5) / 2;
3689 else {
3690 target_speed = (v->reverse_distance - 1) * 10 - 5;
3692 return max(0, target_speed);
3696 * Move a vehicle chain one movement stop forwards.
3697 * @param v First vehicle to move.
3698 * @param nomove Stop moving this and all following vehicles.
3699 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3700 * @return True if the vehicle could be moved forward, false otherwise.
3702 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3704 Train *first = v->First();
3705 Train *prev;
3706 bool direction_changed = false; // has direction of any part changed?
3708 if (reverse && v->reverse_distance == 1) {
3709 goto reverse_train_direction;
3712 if (v->reverse_distance > 1) {
3713 uint16 spd = ReversingDistanceTargetSpeed(v);
3714 if (spd < v->cur_speed) v->cur_speed = spd;
3717 /* For every vehicle after and including the given vehicle */
3718 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3719 DiagDirection enterdir = DIAGDIR_BEGIN;
3720 bool update_signals_crossing = false; // will we update signals or crossing state?
3722 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3723 if (v->track != TRACK_BIT_WORMHOLE) {
3724 /* Not inside tunnel */
3725 if (gp.old_tile == gp.new_tile) {
3726 /* Staying in the old tile */
3727 if (v->track == TRACK_BIT_DEPOT) {
3728 /* Inside depot */
3729 gp.x = v->x_pos;
3730 gp.y = v->y_pos;
3731 v->reverse_distance = 0;
3732 } else {
3733 /* Not inside depot */
3735 /* Reverse when we are at the end of the track already, do not move to the new position */
3736 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3738 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3739 if (HasBit(r, VETS_CANNOT_ENTER)) {
3740 goto invalid_rail;
3742 if (HasBit(r, VETS_ENTERED_STATION)) {
3743 /* The new position is the end of the platform */
3744 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3747 } else {
3748 /* A new tile is about to be entered. */
3750 /* Determine what direction we're entering the new tile from */
3751 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3752 assert(IsValidDiagDirection(enterdir));
3754 /* Get the status of the tracks in the new tile and mask
3755 * away the bits that aren't reachable. */
3756 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3757 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3759 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3760 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3762 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3763 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
3764 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3765 * can be switched on halfway a turn */
3766 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3769 if (bits == TRACK_BIT_NONE)
3770 goto invalid_rail;
3772 /* Check if the new tile constrains tracks that are compatible
3773 * with the current train, if not, bail out. */
3774 if (!CheckCompatibleRail(v, gp.new_tile))
3775 goto invalid_rail;
3777 TrackBits chosen_track;
3778 if (prev == NULL) {
3779 /* Currently the locomotive is active. Determine which one of the
3780 * available tracks to choos/// e */
3781 Track chosen_track_num = ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true);
3782 chosen_track = TrackToTrackBits(chosen_track_num);
3783 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3785 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3786 /* For each signal we find decrease the counter by one.
3787 * We start at two, so the first signal we pass decreases
3788 * this to one, then if we reach the next signal it is
3789 * decreased to zero and we won't pass that new signal. */
3790 Trackdir dir = FindFirstTrackdir(trackdirbits);
3791 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3792 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3793 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3794 /* However, we do not want to be stopped by PBS signals
3795 * entered via the back. */
3796 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3797 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3801 /* Check if it's a red signal and that force proceed is not clicked. */
3802 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3803 /* In front of a red signal */
3804 Trackdir i = FindFirstTrackdir(trackdirbits);
3806 /* Don't handle stuck trains here. */
3807 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3809 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3810 v->cur_speed = 0;
3811 v->subspeed = 0;
3812 v->progress = 255 - 100;
3813 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
3814 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3815 v->cur_speed = 0;
3816 v->subspeed = 0;
3817 v->progress = 255 - 10;
3818 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3819 DiagDirection exitdir = TrackdirToExitdir(i);
3820 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3822 exitdir = ReverseDiagDir(exitdir);
3824 /* check if a train is waiting on the other side */
3825 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3829 /* If we would reverse but are currently in a PBS block and
3830 * reversing of stuck trains is disabled, don't reverse.
3831 * This does not apply if the reason for reversing is a one-way
3832 * signal blocking us, because a train would then be stuck forever. */
3833 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3834 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3835 v->wait_counter = 0;
3836 return false;
3838 goto reverse_train_direction;
3839 } else {
3840 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3842 if (IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile) && IsRestrictedSignal(gp.new_tile)) {
3843 const Trackdir dir = FindFirstTrackdir(trackdirbits);
3844 if (HasSignalOnTrack(gp.new_tile, TrackdirToTrack(dir))) {
3845 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(gp.new_tile, TrackdirToTrack(dir));
3846 if (prog && prog->actions_used_flags & (TRPAUF_SLOT_ACQUIRE | TRPAUF_SLOT_RELEASE_FRONT)) {
3847 TraceRestrictProgramResult out;
3848 TraceRestrictProgramInput input(gp.new_tile, dir, NULL, NULL);
3849 input.permitted_slot_operations = TRPISP_ACQUIRE | TRPISP_RELEASE_FRONT;
3850 prog->Execute(v, input, out);
3855 IncreaseTrackUsage(gp.new_tile, chosen_track_num);
3856 } else {
3857 /* The wagon is active, simply follow the prev vehicle. */
3858 if (prev->tile == gp.new_tile) {
3859 /* Choose the same track as prev */
3860 if (prev->track == TRACK_BIT_WORMHOLE) {
3861 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3862 * However, just choose the track into the wormhole. */
3863 assert(IsTunnel(prev->tile));
3864 chosen_track = bits;
3865 } else {
3866 chosen_track = prev->track;
3868 } else {
3869 /* Choose the track that leads to the tile where prev is.
3870 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3871 * I.e. when the tile between them has only space for a single vehicle like
3872 * 1) horizontal/vertical track tiles and
3873 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3874 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3876 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3877 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3878 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3879 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3880 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3882 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3883 assert(IsValidDiagDirection(exitdir));
3884 chosen_track = _connecting_track[enterdir][exitdir];
3886 chosen_track &= bits;
3889 /* Make sure chosen track is a valid track */
3890 assert(
3891 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3892 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3893 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3895 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3896 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3897 gp.x = (gp.x & ~0xF) | b[0];
3898 gp.y = (gp.y & ~0xF) | b[1];
3899 Direction chosen_dir = (Direction)b[2];
3901 /* Call the landscape function and tell it that the vehicle entered the tile */
3902 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3903 if (HasBit(r, VETS_CANNOT_ENTER)) {
3904 goto invalid_rail;
3907 if (IsTunnelBridgeWithSignalSimulation(gp.new_tile)) {
3908 /* If red signal stop. */
3909 if (v->IsFrontEngine() && v->force_proceed == 0) {
3910 if (IsTunnelBridgeSignalSimulationEntrance(gp.new_tile) && GetTunnelBridgeSignalState(gp.new_tile) == SIGNAL_STATE_RED) {
3911 v->cur_speed = 0;
3912 v->vehstatus |= VS_TRAIN_SLOWING;
3913 return false;
3915 if (IsTunnelBridgeSignalSimulationExit(gp.new_tile)) {
3916 v->cur_speed = 0;
3917 goto invalid_rail;
3919 /* Flip signal on tunnel entrance tile red. */
3920 SetTunnelBridgeSignalState(gp.new_tile, SIGNAL_STATE_RED);
3921 MarkTileDirtyByTile(gp.new_tile);
3925 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3926 Track track = FindFirstTrack(chosen_track);
3927 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3928 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3929 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3930 MarkTileDirtyByTile(gp.new_tile);
3932 /* notify logic signals of the state change */
3933 SignalStateChanged(gp.new_tile, TrackdirToTrack(tdir), 1);
3936 /* Clear any track reservation when the last vehicle leaves the tile */
3937 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir(), true);
3939 v->tile = gp.new_tile;
3941 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3942 v->First()->ConsistChanged(CCF_TRACK);
3945 v->track = chosen_track;
3946 assert(v->track);
3949 /* We need to update signal status, but after the vehicle position hash
3950 * has been updated by UpdateInclination() */
3951 update_signals_crossing = true;
3953 if (chosen_dir != v->direction) {
3954 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3955 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3956 DirDiff diff = DirDifference(v->direction, chosen_dir);
3957 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3959 direction_changed = true;
3960 v->direction = chosen_dir;
3963 if (v->IsFrontEngine()) {
3964 v->wait_counter = 0;
3966 /* If we are approaching a crossing that is reserved, play the sound now. */
3967 TileIndex crossing = TrainApproachingCrossingTile(v);
3969 if (crossing != INVALID_TILE)
3971 RailTypeLabel railTypeLabel = GetRailTypeInfo(GetTileRailType(crossing))->label;
3972 bool is_no_sound_rail_type = (railTypeLabel == _planning_tracks_label || railTypeLabel == _pipeline_tracks_label || railTypeLabel == _wires_tracks_label);
3974 if (HasCrossingReservation(crossing) && _settings_client.sound.ambient && !is_no_sound_rail_type)
3975 SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3978 /* Always try to extend the reservation when entering a tile. */
3979 CheckNextTrainTile(v);
3982 if (HasBit(r, VETS_ENTERED_STATION)) {
3983 /* The new position is the location where we want to stop */
3984 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3987 } else {
3988 /* Handle signal simulation on tunnel/bridge. */
3989 TileIndex old_tile = TileVirtXY(v->x_pos, v->y_pos);
3990 if (old_tile != gp.new_tile && IsTunnelBridgeWithSignalSimulation(v->tile) && (v->IsFrontEngine() || v->Next() == NULL)) {
3991 if (old_tile == v->tile) {
3992 if (v->IsFrontEngine() && v->force_proceed == 0 && IsTunnelBridgeSignalSimulationExit(v->tile))
3993 goto invalid_rail;
3994 /* Entered wormhole set counters. */
3995 v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE;
3996 v->tunnel_bridge_signal_num = 0;
3999 uint distance = v->wait_counter;
4000 bool leaving = false;
4001 if (distance == 0) v->wait_counter = (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals);
4003 if (v->IsFrontEngine()) {
4004 /* Check if track in front is free and see if we can leave wormhole. */
4005 int z = GetSlopePixelZ(gp.x, gp.y) - v->z_pos;
4006 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && !(abs(z) > 2)) {
4007 if (CheckTrainStayInWormHole(v, gp.new_tile)) {
4008 v->cur_speed = 0;
4009 return false;
4011 leaving = true;
4012 } else {
4013 if (IsTooCloseBehindTrain(v, gp.new_tile, v->wait_counter, distance == 0)) {
4014 if (distance == 0) v->wait_counter = 0;
4015 v->cur_speed = 0;
4016 v->vehstatus |= VS_TRAIN_SLOWING;
4017 return false;
4019 /* flip signal in front to red on bridges*/
4020 if (distance == 0 && IsBridge(v->tile)) {
4021 SetBridgeEntranceSimulatedSignalState(v->tile, v->tunnel_bridge_signal_num, SIGNAL_STATE_RED);
4022 MarkTileDirtyByTile(gp.new_tile);
4026 if (v->Next() == NULL) {
4027 if (v->tunnel_bridge_signal_num > 0 && distance == (TILE_SIZE * _settings_game.construction.simulated_wormhole_signals) - TILE_SIZE) HandleSignalBehindTrain(v, v->load_unload_ticks - 2);
4028 if (old_tile == v->tile) {
4029 /* We left ramp into wormhole. */
4030 v->x_pos = gp.x;
4031 v->y_pos = gp.y;
4032 UpdateSignalsOnSegment(old_tile, INVALID_DIAGDIR, v->owner);
4033 UnreserveBridgeTunnelTile(old_tile);
4036 if (distance == 0) v->tunnel_bridge_signal_num++;
4037 v->wait_counter -= TILE_SIZE;
4039 if (leaving) { // Reset counters.
4040 v->force_proceed = 0;
4041 v->wait_counter = 0;
4042 v->tunnel_bridge_signal_num = 0;
4043 v->x_pos = gp.x;
4044 v->y_pos = gp.y;
4045 v->UpdatePosition();
4046 v->UpdateViewport(false, false);
4047 UpdateSignalsOnSegment(gp.new_tile, INVALID_DIAGDIR, v->owner);
4048 continue;
4052 if (old_tile == gp.new_tile && IsTunnelBridgeWithSignalSimulation(v->tile) && v->IsFrontEngine()) {
4053 TileIndex next_tile = old_tile + TileOffsByDir(v->direction);
4054 bool is_exit = false;
4055 if (IsTileType(next_tile, MP_TUNNELBRIDGE) && IsTunnelBridgeWithSignalSimulation(next_tile) &&
4056 ReverseDiagDir(GetTunnelBridgeDirection(next_tile)) == DirToDiagDir(v->direction)) {
4057 if (IsBridge(next_tile) && IsBridge(v->tile)) {
4058 // bridge ramp facing towards us
4059 is_exit = true;
4060 } else if (IsTunnel(next_tile) && IsTunnel(v->tile)) {
4061 // tunnel exit at same height
4062 is_exit = (GetTileZ(next_tile) == GetTileZ(v->tile));
4065 if (is_exit) {
4066 if (CheckTrainStayInWormHole(v, next_tile)) {
4067 TrainApproachingLineEnd(v, true, false);
4069 } else if (v->wait_counter == 0) {
4070 if (IsTooCloseBehindTrain(v, next_tile, TILE_SIZE * _settings_game.construction.simulated_wormhole_signals, true)) {
4071 TrainApproachingLineEnd(v, true, false);
4076 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
4077 /* Perform look-ahead on tunnel exit. */
4078 if (v->IsFrontEngine()) {
4079 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
4080 CheckNextTrainTile(v);
4082 /* Prevent v->UpdateInclination() being called with wrong parameters.
4083 * This could happen if the train was reversed inside the tunnel/bridge. */
4084 if (gp.old_tile == gp.new_tile) {
4085 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
4087 } else {
4088 v->x_pos = gp.x;
4089 v->y_pos = gp.y;
4090 v->UpdatePosition();
4091 if (HasBit(v->gv_flags, GVF_CHUNNEL_BIT)) {
4092 /* update the Z position of the vehicle */
4093 int old_z = v->UpdateInclination(false, false, true);
4095 if (prev == NULL) {
4096 /* This is the first vehicle in the train */
4097 AffectSpeedByZChange(v, old_z);
4100 if (v->IsDrawn()) v->Vehicle::UpdateViewport(true);
4101 continue;
4105 /* update image of train, as well as delta XY */
4106 v->UpdateDeltaXY(v->direction);
4108 v->x_pos = gp.x;
4109 v->y_pos = gp.y;
4110 v->UpdatePosition();
4111 if (v->reverse_distance > 1) {
4112 v->reverse_distance--;
4115 /* update the Z position of the vehicle */
4116 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false, v->track == TRACK_BIT_WORMHOLE);
4118 if (prev == NULL) {
4119 /* This is the first vehicle in the train */
4120 AffectSpeedByZChange(v, old_z);
4123 if (update_signals_crossing) {
4124 if (v->IsFrontEngine()) {
4125 switch(TrainMovedChangeSignal(v, gp.new_tile, enterdir)) {
4126 case CHANGED_NORMAL_TO_PBS_BLOCK:
4127 /* We are entering a block with PBS signals right now, but
4128 * not through a PBS signal. This means we don't have a
4129 * reservation right now. As a conventional signal will only
4130 * ever be green if no other train is in the block, getting
4131 * a path should always be possible. If the player built
4132 * such a strange network that it is not possible, the train
4133 * will be marked as stuck and the player has to deal with
4134 * the problem. */
4135 if ((!HasReservedTracks(gp.new_tile, v->track) &&
4136 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
4137 !TryPathReserve(v)) {
4138 MarkTrainAsStuck(v);
4141 break;
4142 case CHANGED_LR_PBS:
4144 /* We went past a long reserve PBS signal. Try to extend the
4145 * reservation if reserving failed at another LR signal. */
4146 PBSTileInfo origin = FollowTrainReservation(v);
4147 CFollowTrackRail ft(v);
4149 if (ft.Follow(origin.tile, origin.trackdir)) {
4150 Trackdir new_td = FindFirstTrackdir(ft.m_new_td_bits);
4152 if (HasLongReservePbsSignalOnTrackdir(v, ft.m_new_tile, new_td)) {
4153 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, TrackdirBitsToTrackBits(ft.m_new_td_bits), true, NULL, false);
4157 break;
4159 default: break;
4163 /* Signals can only change when the first
4164 * (above) or the last vehicle moves. */
4165 if (v->Next() == NULL) {
4166 TrainMovedChangeSignal(v, gp.old_tile, ReverseDiagDir(enterdir));
4167 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
4169 if (IsTileType(gp.old_tile, MP_RAILWAY) && HasSignals(gp.old_tile) && IsRestrictedSignal(gp.old_tile)) {
4170 const TrackdirBits rev_tracks = TrackBitsToTrackdirBits(GetTrackBits(gp.old_tile)) & DiagdirReachesTrackdirs(ReverseDiagDir(enterdir));
4171 const Trackdir rev_trackdir = FindFirstTrackdir(rev_tracks);
4172 const Track track = TrackdirToTrack(rev_trackdir);
4173 if (HasSignalOnTrack(gp.old_tile, track)) {
4174 const TraceRestrictProgram *prog = GetExistingTraceRestrictProgram(gp.old_tile, track);
4175 if (prog && prog->actions_used_flags & TRPAUF_SLOT_RELEASE_BACK) {
4176 TraceRestrictProgramResult out;
4177 TraceRestrictProgramInput input(gp.old_tile, ReverseTrackdir(rev_trackdir), NULL, NULL);
4178 input.permitted_slot_operations = TRPISP_RELEASE_BACK;
4179 prog->Execute(first, input, out);
4186 /* Do not check on every tick to save some computing time. */
4187 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
4190 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
4192 return true;
4194 invalid_rail:
4195 /* We've reached end of line?? */
4196 if (prev != NULL) error("Disconnecting train");
4198 reverse_train_direction:
4199 if (reverse) {
4200 v->wait_counter = 0;
4201 v->cur_speed = 0;
4202 v->subspeed = 0;
4203 ReverseTrainDirection(v);
4206 return false;
4210 * Collect trackbits of all crashed train vehicles on a tile
4211 * @param v Vehicle passed from Find/HasVehicleOnPos()
4212 * @param data trackdirbits for the result
4213 * @return NULL to iterate over all vehicles on the tile.
4215 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
4217 TrackBits *trackbits = (TrackBits *)data;
4219 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
4220 TrackBits train_tbits = Train::From(v)->track;
4221 if (train_tbits == TRACK_BIT_WORMHOLE) {
4222 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4223 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
4224 } else if (train_tbits != TRACK_BIT_DEPOT) {
4225 *trackbits |= train_tbits;
4229 return NULL;
4233 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
4234 * train, then goes to the last wagon and deletes that. Each call to this function
4235 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
4236 * or inside a tunnel/bridge, recalculate the signals as they might need updating
4237 * @param v the Vehicle of which last wagon is to be removed
4239 static void DeleteLastWagon(Train *v)
4241 Train *first = v->First();
4243 /* Go to the last wagon and delete the link pointing there
4244 * *u is then the one-before-last wagon, and *v the last
4245 * one which will physically be removed */
4246 Train *u = v;
4247 for (; v->Next() != NULL; v = v->Next()) u = v;
4248 u->SetNext(NULL);
4250 if (first != v) {
4251 /* Recalculate cached train properties */
4252 first->ConsistChanged(CCF_ARRANGE);
4253 /* Update the depot window if the first vehicle is in depot -
4254 * if v == first, then it is updated in PreDestructor() */
4255 if (first->track == TRACK_BIT_DEPOT) {
4256 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
4258 v->last_station_visited = first->last_station_visited; // for PreDestructor
4261 /* 'v' shouldn't be accessed after it has been deleted */
4262 TrackBits trackbits = v->track;
4263 TileIndex tile = v->tile;
4264 Owner owner = v->owner;
4266 delete v;
4267 v = NULL; // make sure nobody will try to read 'v' anymore
4269 if (trackbits == TRACK_BIT_WORMHOLE) {
4270 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
4271 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
4274 Track track = TrackBitsToTrack(trackbits);
4275 if (HasReservedTracks(tile, trackbits)) {
4276 UnreserveRailTrack(tile, track);
4278 /* If there are still crashed vehicles on the tile, give the track reservation to them */
4279 TrackBits remaining_trackbits = TRACK_BIT_NONE;
4280 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
4282 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
4283 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
4284 Track t;
4285 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
4288 /* check if the wagon was on a road/rail-crossing */
4289 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
4291 /* Update signals */
4292 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4293 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4294 if (IsTunnelBridgeWithSignalSimulation(tile)) {
4295 TileIndex end = GetOtherTunnelBridgeEnd(tile);
4296 UpdateSignalsOnSegment(end, INVALID_DIAGDIR, owner);
4297 bool is_entrance = IsTunnelBridgeSignalSimulationEntrance(tile);
4298 TileIndex entrance = is_entrance ? tile : end;
4299 if (TunnelBridgeIsFree(tile, end, nullptr).Succeeded()) {
4300 if (IsBridge(entrance)) {
4301 SetAllBridgeEntranceSimulatedSignalsGreen(entrance);
4302 MarkBridgeDirty(entrance, ZOOM_LVL_DRAW_MAP);
4304 if (IsTunnelBridgeSignalSimulationEntrance(entrance) && GetTunnelBridgeSignalState(entrance) == SIGNAL_STATE_RED) {
4305 SetTunnelBridgeSignalState(entrance, SIGNAL_STATE_GREEN);
4306 MarkTileDirtyByTile(entrance);
4310 } else if (IsRailDepotTile(tile)) {
4311 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
4312 } else {
4313 SetSignalsOnBothDir(tile, track, owner);
4318 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
4319 * @param v First crashed vehicle.
4321 static void ChangeTrainDirRandomly(Train *v)
4323 static const DirDiff delta[] = {
4324 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
4327 do {
4328 /* We don't need to twist around vehicles if they're not visible */
4329 if (!(v->vehstatus & VS_HIDDEN)) {
4330 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
4331 /* Refrain from updating the z position of the vehicle when on
4332 * a bridge, because UpdateInclination() will put the vehicle under
4333 * the bridge in that case */
4334 if (v->track != TRACK_BIT_WORMHOLE) {
4335 v->UpdatePosition();
4336 v->UpdateInclination(false, true);
4337 } else {
4338 v->UpdateViewport(false, true);
4341 } while ((v = v->Next()) != NULL);
4345 * Handle a crashed train.
4346 * @param v First train vehicle.
4347 * @return %Vehicle chain still exists.
4349 static bool HandleCrashedTrain(Train *v)
4351 int state = ++v->crash_anim_pos;
4353 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
4354 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
4357 uint32 r;
4358 if (state <= 200 && Chance16R(1, 7, r)) {
4359 int index = (r * 10 >> 16);
4361 Vehicle *u = v;
4362 do {
4363 if (--index < 0) {
4364 r = Random();
4366 CreateEffectVehicleRel(u,
4367 GB(r, 8, 3) + 2,
4368 GB(r, 16, 3) + 2,
4369 GB(r, 0, 3) + 5,
4370 EV_EXPLOSION_SMALL);
4371 break;
4373 } while ((u = u->Next()) != NULL);
4376 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
4378 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
4379 bool ret = v->Next() != NULL;
4380 DeleteLastWagon(v);
4381 return ret;
4384 return true;
4387 /** Maximum speeds for train that is broken down or approaching line end */
4388 static const uint16 _breakdown_speeds[16] = {
4389 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
4394 * Train is approaching line end, slow down and possibly reverse
4396 * @param v front train engine
4397 * @param signal not line end, just a red signal
4398 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4399 * @return true iff we did NOT have to reverse
4401 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
4403 /* Calc position within the current tile */
4404 uint x = v->x_pos & 0xF;
4405 uint y = v->y_pos & 0xF;
4407 /* for diagonal directions, 'x' will be 0..15 -
4408 * for other directions, it will be 1, 3, 5, ..., 15 */
4409 switch (v->direction) {
4410 case DIR_N : x = ~x + ~y + 25; break;
4411 case DIR_NW: x = y; FALLTHROUGH;
4412 case DIR_NE: x = ~x + 16; break;
4413 case DIR_E : x = ~x + y + 9; break;
4414 case DIR_SE: x = y; break;
4415 case DIR_S : x = x + y - 7; break;
4416 case DIR_W : x = ~y + x + 9; break;
4417 default: break;
4420 /* Do not reverse when approaching red signal. Make sure the vehicle's front
4421 * does not cross the tile boundary when we do reverse, but as the vehicle's
4422 * location is based on their center, use half a vehicle's length as offset.
4423 * Multiply the half-length by two for straight directions to compensate that
4424 * we only get odd x offsets there. */
4425 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
4426 /* we are too near the tile end, reverse now */
4427 v->cur_speed = 0;
4428 if (reverse) ReverseTrainDirection(v);
4429 return false;
4432 /* slow down */
4433 v->vehstatus |= VS_TRAIN_SLOWING;
4434 uint16 break_speed = _breakdown_speeds[x & 0xF];
4435 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4437 return true;
4442 * Determines whether train would like to leave the tile
4443 * @param v train to test
4444 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
4446 static bool TrainCanLeaveTile(const Train *v)
4448 /* Exit if inside a tunnel/bridge or a depot */
4449 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
4451 TileIndex tile = v->tile;
4453 /* entering a tunnel/bridge? */
4454 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
4455 DiagDirection dir = GetTunnelBridgeDirection(tile);
4456 if (DiagDirToDir(dir) == v->direction) return false;
4459 /* entering a depot? */
4460 if (IsRailDepotTile(tile)) {
4461 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
4462 if (DiagDirToDir(dir) == v->direction) return false;
4465 return true;
4470 * Determines whether train is approaching a rail-road crossing
4471 * (thus making it barred)
4472 * @param v front engine of train
4473 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
4474 * @pre v in non-crashed front engine
4476 static TileIndex TrainApproachingCrossingTile(const Train *v)
4478 assert(v->IsFrontEngine());
4479 assert(!(v->vehstatus & VS_CRASHED));
4481 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
4483 DiagDirection dir = TrainExitDir(v->direction, v->track);
4484 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4486 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
4487 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
4488 !CheckCompatibleRail(v, tile)) {
4489 return INVALID_TILE;
4492 return tile;
4497 * Checks for line end. Also, bars crossing at next tile if needed
4499 * @param v vehicle we are checking
4500 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
4501 * @return true iff we did NOT have to reverse
4503 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
4505 /* First, handle broken down train */
4507 int t = v->breakdown_ctr;
4508 if (t > 1) {
4509 v->vehstatus |= VS_TRAIN_SLOWING;
4511 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
4512 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
4513 } else {
4514 v->vehstatus &= ~VS_TRAIN_SLOWING;
4517 if (!TrainCanLeaveTile(v)) return true;
4519 /* Determine the non-diagonal direction in which we will exit this tile */
4520 DiagDirection dir = TrainExitDir(v->direction, v->track);
4521 /* Calculate next tile */
4522 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
4524 /* Determine the track status on the next tile */
4525 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
4526 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
4528 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
4529 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
4531 /* We are sure the train is not entering a depot, it is detected above */
4533 /* mask unreachable track bits if we are forbidden to do 90deg turns */
4534 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
4535 if (_settings_game.pf.forbid_90_deg) {
4536 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
4539 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
4540 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
4541 return TrainApproachingLineEnd(v, false, reverse);
4544 /* approaching red signal */
4545 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
4547 /* approaching a rail/road crossing? then make it red */
4548 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
4550 if (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL &&
4551 IsTunnelBridgeSignalSimulationEntrance(tile) && GetTunnelBridgeSignalState(tile) == SIGNAL_STATE_RED) {
4552 return TrainApproachingLineEnd(v, true, reverse);
4555 return true;
4558 /* Calculate the summed up value of all parts of a train */
4559 Money Train::CalculateCurrentOverallValue() const
4561 Money ovr_value = 0;
4562 const Train *v = this;
4563 do {
4564 ovr_value += v->value;
4565 } while ( (v=v->GetNextVehicle()) != NULL );
4566 return ovr_value;
4569 static bool TrainLocoHandler(Train *v, bool mode)
4571 /* train has crashed? */
4572 if (v->vehstatus & VS_CRASHED) {
4573 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
4576 if (v->force_proceed != TFP_NONE) {
4577 ClrBit(v->flags, VRF_TRAIN_STUCK);
4578 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4581 /* train is broken down? */
4582 if (v->HandleBreakdown()) return true;
4584 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
4585 ReverseTrainDirection(v);
4588 /* exit if train is stopped */
4589 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
4591 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
4592 if (ProcessOrders(v) && CheckReverseTrain(v)) {
4593 v->wait_counter = 0;
4594 v->cur_speed = 0;
4595 v->subspeed = 0;
4596 ClrBit(v->flags, VRF_LEAVING_STATION);
4597 ReverseTrainDirection(v);
4598 return true;
4599 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
4600 /* Try to reserve a path when leaving the station as we
4601 * might not be marked as wanting a reservation, e.g.
4602 * when an overlength train gets turned around in a station. */
4603 DiagDirection dir = TrainExitDir(v->direction, v->track);
4604 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
4606 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
4607 TryPathReserve(v, true, true);
4609 ClrBit(v->flags, VRF_LEAVING_STATION);
4612 v->HandleLoading(mode);
4614 if (v->current_order.IsType(OT_LOADING)) return true;
4616 if (CheckTrainStayInDepot(v)) return true;
4618 if (!mode) v->ShowVisualEffect();
4620 /* We had no order but have an order now, do look ahead. */
4621 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4622 CheckNextTrainTile(v);
4625 /* Handle stuck trains. */
4626 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
4627 ++v->wait_counter;
4629 /* Should we try reversing this tick if still stuck? */
4630 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4632 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4633 if (!TryPathReserve(v)) {
4634 /* Still stuck. */
4635 if (turn_around) ReverseTrainDirection(v);
4637 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
4638 /* Show message to player. */
4639 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4640 SetDParam(0, v->index);
4641 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
4643 v->wait_counter = 0;
4645 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4646 if (v->force_proceed == TFP_NONE) return true;
4647 ClrBit(v->flags, VRF_TRAIN_STUCK);
4648 v->wait_counter = 0;
4649 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4653 if (v->current_order.IsType(OT_LEAVESTATION)) {
4654 v->current_order.Free();
4655 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4656 return true;
4659 int j = v->UpdateSpeed();
4661 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4662 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
4663 /* If we manually stopped, we're not force-proceeding anymore. */
4664 v->force_proceed = TFP_NONE;
4665 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4668 int adv_spd = v->GetAdvanceDistance();
4669 if (j < adv_spd) {
4670 /* if the vehicle has speed 0, update the last_speed field. */
4671 if (v->cur_speed == 0) v->SetLastSpeed();
4672 } else {
4673 TrainCheckIfLineEnds(v);
4674 /* Loop until the train has finished moving. */
4675 for (;;) {
4676 j -= adv_spd;
4677 TrainController(v, NULL);
4678 /* Don't continue to move if the train crashed. */
4679 if (CheckTrainCollision(v)) break;
4680 /* Determine distance to next map position */
4681 adv_spd = v->GetAdvanceDistance();
4683 /* No more moving this tick */
4684 if (j < adv_spd || v->cur_speed == 0) break;
4686 OrderType order_type = v->current_order.GetType();
4687 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4688 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4689 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
4690 IsTileType(v->tile, MP_STATION) &&
4691 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4692 ProcessOrders(v);
4695 v->SetLastSpeed();
4698 for (Train *u = v; u != NULL; u = u->Next()) {
4699 if (!(u->IsDrawn())) continue;
4701 u->UpdateViewport(false, false);
4704 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4706 return true;
4710 * Get running cost for the train consist.
4711 * @return Yearly running costs.
4713 Money Train::GetRunningCost() const
4715 Money cost = 0;
4716 const Train *v = this;
4718 do {
4719 const Engine *e = v->GetEngine();
4720 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4722 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4723 if (cost_factor == 0) continue;
4725 /* Halve running cost for multiheaded parts */
4726 if (v->IsMultiheaded()) cost_factor /= 2;
4728 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4729 } while ((v = v->GetNextVehicle()) != NULL);
4731 return cost;
4735 * Update train vehicle data for a tick.
4736 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
4738 bool Train::Tick()
4740 this->tick_counter++;
4742 if (this->IsFrontEngine()) {
4743 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot()) || this->cur_speed > 0) this->running_ticks++;
4745 this->current_order_time++;
4747 if (!TrainLocoHandler(this, false)) return false;
4749 return TrainLocoHandler(this, true);
4750 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4751 /* Delete flooded standalone wagon chain */
4752 if (++this->crash_anim_pos >= 4400) {
4753 delete this;
4754 return false;
4758 return true;
4762 * Check whether a train needs service, and if so, find a depot or service it.
4763 * @return v %Train to check.
4765 static void CheckIfTrainNeedsService(Train *v)
4767 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4768 if (v->IsChainInDepot()) {
4769 VehicleServiceInDepot(v);
4770 return;
4773 uint max_penalty;
4774 switch (_settings_game.pf.pathfinder_for_trains) {
4775 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
4776 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
4777 default: NOT_REACHED();
4780 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4781 /* Only go to the depot if it is not too far out of our way. */
4782 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4783 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4784 /* If we were already heading for a depot but it has
4785 * suddenly moved farther away, we continue our normal
4786 * schedule? */
4787 v->current_order.MakeDummy();
4788 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4790 return;
4793 DepotID depot = GetDepotIndex(tfdd.tile);
4795 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4796 v->current_order.GetDestination() != depot &&
4797 !Chance16(3, 16)) {
4798 return;
4801 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4802 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
4803 v->dest_tile = tfdd.tile;
4804 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4807 /** Update day counters of the train vehicle. */
4808 void Train::OnNewDay()
4810 AgeVehicle(this);
4812 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4814 if (this->IsFrontEngine()) {
4815 CheckVehicleBreakdown(this);
4817 CheckIfTrainNeedsService(this);
4819 CheckOrders(this);
4821 /* update destination */
4822 if (this->current_order.IsType(OT_GOTO_STATION)) {
4823 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4824 if (tile != INVALID_TILE) this->dest_tile = tile;
4827 if (this->running_ticks != 0) {
4828 /* running costs */
4829 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4831 this->profit_this_year -= cost.GetCost();
4832 this->running_ticks = 0;
4834 SubtractMoneyFromCompanyFract(this->owner, cost);
4836 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4837 SetWindowClassesDirty(WC_TRAINS_LIST);
4843 * Get the tracks of the train vehicle.
4844 * @return Current tracks of the vehicle.
4846 Trackdir Train::GetVehicleTrackdir() const
4848 if (this->vehstatus & VS_CRASHED)
4849 return INVALID_TRACKDIR;
4851 if (this->track == TRACK_BIT_DEPOT) {
4852 /* We'll assume the train is facing outwards */
4853 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4856 if (this->track == TRACK_BIT_WORMHOLE) {
4857 /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4858 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4861 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4865 /* Get the pixel-width of the image that is used for the train vehicle
4866 * @return: the image width number in pixel
4868 int GetDisplayImageWidth(Train *t, Point *offset)
4870 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
4871 int vehicle_pitch = 0;
4873 const Engine *e = Engine::Get(t->engine_type);
4874 if (e->grf_prop.grffile != NULL && is_custom_sprite(e->u.rail.image_index)) {
4875 reference_width = e->grf_prop.grffile->traininfo_vehicle_width;
4876 vehicle_pitch = e->grf_prop.grffile->traininfo_vehicle_pitch;
4879 if (offset != NULL) {
4880 offset->x = reference_width / 2;
4881 offset->y = vehicle_pitch;
4883 //printf(" refwid:%d gdiw.cachedvehlen(%d):%d ", reference_width, this->engine_type, this->gcache.cached_veh_length);
4884 return t->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH;
4887 Train* CmdBuildVirtualRailWagon(const Engine *e)
4889 const RailVehicleInfo *rvi = &e->u.rail;
4891 Train *v = new Train();
4893 v->x_pos = 0;
4894 v->y_pos = 0;
4896 v->spritenum = rvi->image_index;
4898 v->engine_type = e->index;
4899 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4901 v->direction = DIR_W;
4902 v->tile = 0;//INVALID_TILE;
4904 v->owner = _current_company;
4905 v->track = TRACK_BIT_DEPOT;
4906 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
4908 v->SetWagon();
4909 v->SetFreeWagon();
4911 v->cargo_type = e->GetDefaultCargoType();
4912 v->cargo_cap = rvi->capacity;
4914 v->railtype = rvi->railtype;
4916 v->build_year = _cur_year;
4917 v->sprite_seq.Set(SPR_IMG_QUERY);
4918 v->random_bits = VehicleRandomBits();
4920 v->group_id = DEFAULT_GROUP;
4922 AddArticulatedParts(v);
4924 // Make sure we set EVERYTHING to virtual, even articulated parts.
4925 for (Train* train_part = v; train_part != NULL; train_part = train_part->Next()) {
4926 train_part->SetVirtual();
4929 _new_vehicle_id = v->index;
4931 v->UpdateViewport(true, false);
4933 v->First()->ConsistChanged(CCF_ARRANGE);
4935 CheckConsistencyOfArticulatedVehicle(v);
4937 return v;
4940 Train* CmdBuildVirtualRailVehicle(EngineID eid, bool lax_engine_check, StringID &error)
4942 if (lax_engine_check) {
4943 const Engine *e = Engine::GetIfValid(eid);
4944 if (e == NULL || e->type != VEH_TRAIN) {
4945 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4946 return NULL;
4949 else {
4950 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
4951 error = STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN;
4952 return NULL;
4956 const Engine* e = Engine::Get(eid);
4957 const RailVehicleInfo *rvi = &e->u.rail;
4959 int num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false);
4960 if (!Train::CanAllocateItem(num_vehicles)) {
4961 error = STR_ERROR_TOO_MANY_VEHICLES_IN_GAME;
4962 return nullptr;
4965 if (rvi->railveh_type == RAILVEH_WAGON)
4966 return CmdBuildVirtualRailWagon(e);
4968 Train *v = new Train();
4970 v->x_pos = 0;
4971 v->y_pos = 0;
4973 v->direction = DIR_W;
4974 v->tile = 0;//INVALID_TILE;
4975 v->owner = _current_company;
4976 v->track = TRACK_BIT_DEPOT;
4977 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
4978 v->spritenum = rvi->image_index;
4979 v->cargo_type = e->GetDefaultCargoType();
4980 v->cargo_cap = rvi->capacity;
4981 v->last_station_visited = INVALID_STATION;
4983 v->engine_type = e->index;
4984 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
4986 v->reliability = e->reliability;
4987 v->reliability_spd_dec = e->reliability_spd_dec;
4988 v->max_age = e->GetLifeLengthInDays();
4990 v->railtype = rvi->railtype;
4991 _new_vehicle_id = v->index;
4993 v->build_year = _cur_year;
4994 v->sprite_seq.Set(SPR_IMG_QUERY);
4995 v->random_bits = VehicleRandomBits();
4997 v->group_id = DEFAULT_GROUP;
4999 v->SetFrontEngine();
5000 v->SetEngine();
5002 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
5003 AddRearEngineToMultiheadedTrain(v);
5004 } else {
5005 AddArticulatedParts(v);
5008 // Make sure we set EVERYTHING to virtual, even articulated parts.
5009 for (Train* train_part = v; train_part != NULL; train_part = train_part->Next()) {
5010 train_part->SetVirtual();
5013 v->UpdateViewport(true, false);
5015 v->ConsistChanged(CCF_ARRANGE);
5017 CheckConsistencyOfArticulatedVehicle(v);
5019 return v;
5023 * Build a virtual train vehicle.
5024 * @param tile unused
5025 * @param flags type of operation
5026 * @param p1 the engine ID to build
5027 * @param p2 unused
5028 * @param text unused
5029 * @return the cost of this operation or an error
5031 CommandCost CmdBuildVirtualRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
5033 EngineID eid = p1;
5035 if (!IsEngineBuildable(eid, VEH_TRAIN, _current_company)) {
5036 return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + VEH_TRAIN);
5039 bool should_execute = (flags & DC_EXEC) != 0;
5041 if (should_execute) {
5042 StringID err = INVALID_STRING_ID;
5043 Train* train = CmdBuildVirtualRailVehicle(eid, false, err);
5045 if (train == nullptr) {
5046 return_cmd_error(err);
5050 return CommandCost();
5054 * Replace a vehicle based on a template replacement order.
5055 * @param tile unused
5056 * @param flags type of operation
5057 * @param p1 the ID of the vehicle to replace.
5058 * @param p2 whether the vehicle should stay in the depot.
5059 * @param text unused
5060 * @return the cost of this operation or an error
5062 CommandCost CmdTemplateReplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
5064 VehicleID vehicle_id = p1;
5066 Vehicle* vehicle = Vehicle::GetIfValid(vehicle_id);
5068 if (vehicle == nullptr || vehicle->type != VEH_TRAIN)
5069 return CMD_ERROR;
5071 bool should_execute = (flags & DC_EXEC) != 0;
5073 if (!should_execute)
5074 return CommandCost();
5076 Train* incoming = Train::From(vehicle);
5077 bool stayInDepot = p2 != 0;
5079 Train *new_chain = 0,
5080 *remainder_chain = 0,
5081 *tmp_chain = 0;
5082 TemplateVehicle *tv = GetTemplateVehicleByGroupID(incoming->group_id);
5083 if (tv == nullptr) {
5084 return CMD_ERROR;
5087 CommandCost buy(EXPENSES_NEW_VEHICLES);
5088 CommandCost move_cost(EXPENSES_NEW_VEHICLES);
5089 CommandCost tmp_result(EXPENSES_NEW_VEHICLES);
5092 /* first some tests on necessity and sanity */
5093 if (tv == nullptr)
5094 return buy;
5096 EngineID eid = tv->engine_type;
5098 _new_vehicle_id = p1;
5100 bool need_replacement = !TrainMatchesTemplate(incoming, tv);
5101 bool need_refit = !TrainMatchesTemplateRefit(incoming, tv);
5102 bool use_refit = tv->refit_as_template;
5104 CargoID store_refit_ct = CT_INVALID;
5105 short store_refit_csubt = 0;
5106 // if a train shall keep its old refit, store the refit setting of its first vehicle
5107 if (!use_refit) {
5108 for (Train *getc = incoming; getc != NULL; getc = getc->GetNextUnit()) {
5109 if (getc->cargo_type != CT_INVALID) {
5110 store_refit_ct = getc->cargo_type;
5111 break;
5116 // TODO: set result status to success/no success before returning
5117 if (!need_replacement) {
5118 if (!need_refit || !use_refit) {
5119 /* before returning, release incoming train first if 2nd param says so */
5120 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
5121 return buy;
5124 else {
5125 CommandCost buyCost = TestBuyAllTemplateVehiclesInChain(tv, tile);
5126 if (!buyCost.Succeeded() || !CheckCompanyHasMoney(buyCost)) {
5127 if (!stayInDepot) incoming->vehstatus &= ~VS_STOPPED;
5129 if (!buyCost.Succeeded() && buyCost.GetErrorMessage() != INVALID_STRING_ID) {
5130 return buyCost;
5131 } else {
5132 return_cmd_error(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
5137 /* define replacement behavior */
5138 bool reuseDepot = tv->IsSetReuseDepotVehicles();
5139 bool keepRemainders = tv->IsSetKeepRemainingVehicles();
5141 if (need_replacement) {
5142 /// step 1: generate primary for newchain and generate remainder_chain
5143 // 1. primary of incoming might already fit the template
5144 // leave incoming's primary as is and move the rest to a free chain = remainder_chain
5145 // 2. needed primary might be one of incoming's member vehicles
5146 // 3. primary might be available as orphan vehicle in the depot
5147 // 4. we need to buy a new engine for the primary
5148 // all options other than 1. need to make sure to copy incoming's primary's status
5149 if (eid == incoming->engine_type) { // 1
5150 new_chain = incoming;
5151 remainder_chain = incoming->GetNextUnit();
5152 if (remainder_chain)
5153 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, remainder_chain->index | (1 << 20), INVALID_VEHICLE, 0));
5155 else if ((tmp_chain = ChainContainsEngine(eid, incoming)) && tmp_chain != NULL) { // 2
5156 // new_chain is the needed engine, move it to an empty spot in the depot
5157 new_chain = tmp_chain;
5158 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5159 remainder_chain = incoming;
5161 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, eid, incoming)) && tmp_chain != NULL) { // 3
5162 new_chain = tmp_chain;
5163 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5164 remainder_chain = incoming;
5166 else { // 4
5167 tmp_result = DoCommand(tile, eid, 0, flags, CMD_BUILD_VEHICLE);
5168 /* break up in case buying the vehicle didn't succeed */
5169 if (!tmp_result.Succeeded())
5170 return tmp_result;
5171 buy.AddCost(tmp_result);
5172 new_chain = Train::Get(_new_vehicle_id);
5173 /* make sure the newly built engine is not attached to any free wagons inside the depot */
5174 move_cost.AddCost(DoCommand(tile, new_chain->index, INVALID_VEHICLE, flags, CMD_MOVE_RAIL_VEHICLE));
5175 /* prepare the remainder chain */
5176 remainder_chain = incoming;
5178 // If we bought a new engine or reused one from the depot, copy some parameters from the incoming primary engine
5179 if (incoming != new_chain && flags == DC_EXEC) {
5180 CopyHeadSpecificThings(incoming, new_chain, flags);
5181 NeutralizeStatus(incoming);
5184 // additionally, if we don't want to use the template refit, refit as incoming
5185 // the template refit will be set further down, if we use it at all
5186 if (!use_refit) {
5187 uint32 cb = GetCmdRefitVeh(new_chain);
5188 DoCommand(new_chain->tile, new_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5193 /// step 2: fill up newchain according to the template
5194 // foreach member of template (after primary):
5195 // 1. needed engine might be within remainder_chain already
5196 // 2. needed engine might be orphaned within the depot (copy status)
5197 // 3. we need to buy (again) (copy status)
5198 TemplateVehicle *cur_tmpl = tv->GetNextUnit();
5199 Train *last_veh = new_chain;
5200 while (cur_tmpl) {
5201 // 1. engine contained in remainder chain
5202 if ((tmp_chain = ChainContainsEngine(cur_tmpl->engine_type, remainder_chain)) && tmp_chain != NULL) {
5203 // advance remainder_chain (if necessary) to not lose track of it
5204 if (tmp_chain == remainder_chain)
5205 remainder_chain = remainder_chain->GetNextUnit();
5206 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5208 // 2. engine contained somewhere else in the depot
5209 else if (reuseDepot && (tmp_chain = DepotContainsEngine(tile, cur_tmpl->engine_type, new_chain)) && tmp_chain != NULL) {
5210 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5212 // 3. must buy new engine
5213 else {
5214 tmp_result = DoCommand(tile, cur_tmpl->engine_type, 0, flags, CMD_BUILD_VEHICLE);
5215 if (!tmp_result.Succeeded()) {
5216 return tmp_result;
5218 buy.AddCost(tmp_result);
5219 tmp_chain = Train::Get(_new_vehicle_id);
5220 move_cost.AddCost(CmdMoveRailVehicle(tile, flags, tmp_chain->index, last_veh->index, 0));
5222 // TODO: is this enough ? might it be that we bought a new wagon here and it now has std refit ?
5223 if (need_refit && flags == DC_EXEC) {
5224 if (use_refit) {
5225 uint32 cb = GetCmdRefitVeh(tmp_chain);
5226 DoCommand(tmp_chain->tile, tmp_chain->index, cur_tmpl->cargo_type | cur_tmpl->cargo_subtype << 8 | 1 << 16 | (1 << 5), flags, cb);
5227 // old
5228 // CopyWagonStatus(cur_tmpl, tmp_chain);
5229 } else {
5230 uint32 cb = GetCmdRefitVeh(tmp_chain);
5231 DoCommand(tmp_chain->tile, tmp_chain->index, store_refit_ct | store_refit_csubt << 8 | 1 << 16 | (1 << 5), flags, cb);
5234 cur_tmpl = cur_tmpl->GetNextUnit();
5235 last_veh = tmp_chain;
5238 /* no replacement done */
5239 else {
5240 new_chain = incoming;
5242 /// step 3: reorder and neutralize the remaining vehicles from incoming
5243 // wagons remaining from remainder_chain should be filled up in as few freewagonchains as possible
5244 // each locos might be left as singular in the depot
5245 // neutralize each remaining engine's status
5247 // refit, only if the template option is set so
5248 if (use_refit && (need_refit || need_replacement)) {
5249 CmdRefitTrainFromTemplate(new_chain, tv, flags);
5252 if (new_chain && remainder_chain)
5253 for (Train *ct = remainder_chain; ct; ct = ct->GetNextUnit())
5254 TransferCargoForTrain(ct, new_chain);
5256 // point incoming to the newly created train so that starting/stopping from the calling function can be done
5257 incoming = new_chain;
5258 if (!stayInDepot && flags == DC_EXEC)
5259 new_chain->vehstatus &= ~VS_STOPPED;
5261 if (remainder_chain && keepRemainders && flags == DC_EXEC)
5262 BreakUpRemainders(remainder_chain);
5263 else if (remainder_chain) {
5264 buy.AddCost(DoCommand(tile, remainder_chain->index | (1 << 20), 0, flags, CMD_SELL_VEHICLE));
5267 /* Redraw main gui for changed statistics */
5268 SetWindowClassesDirty(WC_TEMPLATEGUI_MAIN);
5270 _new_vehicle_id = new_chain->index;
5272 return buy;