(svn r27756) -Codechange: Add StringTab enum
[openttd.git] / src / train_cmd.cpp
blob5502532232830692097a8f3731a720f8377026d8
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"
39 #include "table/strings.h"
40 #include "table/train_cmd.h"
42 #include "safeguards.h"
44 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
45 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
46 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
47 static TileIndex TrainApproachingCrossingTile(const Train *v);
48 static void CheckIfTrainNeedsService(Train *v);
49 static void CheckNextTrainTile(Train *v);
51 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
52 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
54 template <>
55 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
57 return image_index < lengthof(_engine_sprite_base);
60 /**
61 * Determine the side in which the train will leave the tile
63 * @param direction vehicle direction
64 * @param track vehicle track bits
65 * @return side of tile the train will leave
67 static inline DiagDirection TrainExitDir(Direction direction, TrackBits track)
69 static const TrackBits state_dir_table[DIAGDIR_END] = { TRACK_BIT_RIGHT, TRACK_BIT_LOWER, TRACK_BIT_LEFT, TRACK_BIT_UPPER };
71 DiagDirection diagdir = DirToDiagDir(direction);
73 /* Determine the diagonal direction in which we will exit this tile */
74 if (!HasBit(direction, 0) && track != state_dir_table[diagdir]) {
75 diagdir = ChangeDiagDir(diagdir, DIAGDIRDIFF_90LEFT);
78 return diagdir;
82 /**
83 * Return the cargo weight multiplier to use for a rail vehicle
84 * @param cargo Cargo type to get multiplier for
85 * @return Cargo weight multiplier
87 byte FreightWagonMult(CargoID cargo)
89 if (!CargoSpec::Get(cargo)->is_freight) return 1;
90 return _settings_game.vehicle.freight_trains;
93 /** Checks if lengths of all rail vehicles are valid. If not, shows an error message. */
94 void CheckTrainsLengths()
96 const Train *v;
97 bool first = true;
99 FOR_ALL_TRAINS(v) {
100 if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
101 for (const Train *u = v, *w = v->Next(); w != NULL; u = w, w = w->Next()) {
102 if (u->track != TRACK_BIT_DEPOT) {
103 if ((w->track != TRACK_BIT_DEPOT &&
104 max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
105 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
106 SetDParam(0, v->index);
107 SetDParam(1, v->owner);
108 ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
110 if (!_networking && first) {
111 first = false;
112 DoCommandP(0, PM_PAUSED_ERROR, 1, CMD_PAUSE);
114 /* Break so we warn only once for each train. */
115 break;
124 * Recalculates the cached stuff of a train. Should be called each time a vehicle is added
125 * to/removed from the chain, and when the game is loaded.
126 * Note: this needs to be called too for 'wagon chains' (in the depot, without an engine)
127 * @param allowed_changes Stuff that is allowed to change.
129 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
131 uint16 max_speed = UINT16_MAX;
133 assert(this->IsFrontEngine() || this->IsFreeWagon());
135 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
136 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
137 this->gcache.cached_total_length = 0;
138 this->compatible_railtypes = RAILTYPES_NONE;
140 bool train_can_tilt = true;
142 for (Train *u = this; u != NULL; u = u->Next()) {
143 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
145 /* Check the this->first cache. */
146 assert(u->First() == this);
148 /* update the 'first engine' */
149 u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
150 u->railtype = rvi_u->railtype;
152 if (u->IsEngine()) first_engine = u->engine_type;
154 /* Set user defined data to its default value */
155 u->tcache.user_def_data = rvi_u->user_def_data;
156 this->InvalidateNewGRFCache();
157 u->InvalidateNewGRFCache();
160 for (Train *u = this; u != NULL; u = u->Next()) {
161 /* Update user defined data (must be done before other properties) */
162 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
163 this->InvalidateNewGRFCache();
164 u->InvalidateNewGRFCache();
167 for (Train *u = this; u != NULL; u = u->Next()) {
168 const Engine *e_u = u->GetEngine();
169 const RailVehicleInfo *rvi_u = &e_u->u.rail;
171 if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
173 /* Cache wagon override sprite group. NULL is returned if there is none */
174 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
176 /* Reset colour map */
177 u->colourmap = PAL_NONE;
179 /* Update powered-wagon-status and visual effect */
180 u->UpdateVisualEffect(true);
182 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
183 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
184 /* wagon is powered */
185 SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
186 } else {
187 ClrBit(u->flags, VRF_POWEREDWAGON);
190 if (!u->IsArticulatedPart()) {
191 /* Do not count powered wagons for the compatible railtypes, as wagons always
192 have railtype normal */
193 if (rvi_u->power > 0) {
194 this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
197 /* Some electric engines can be allowed to run on normal rail. It happens to all
198 * existing electric engines when elrails are disabled and then re-enabled */
199 if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
200 u->railtype = RAILTYPE_RAIL;
201 u->compatible_railtypes |= RAILTYPES_RAIL;
204 /* max speed is the minimum of the speed limits of all vehicles in the consist */
205 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
206 uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
207 if (speed != 0) max_speed = min(speed, max_speed);
211 uint16 new_cap = e_u->DetermineCapacity(u);
212 if (allowed_changes & CCF_CAPACITY) {
213 /* Update vehicle capacity. */
214 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
215 u->refit_cap = min(new_cap, u->refit_cap);
216 u->cargo_cap = new_cap;
217 } else {
218 /* Verify capacity hasn't changed. */
219 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
221 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
223 /* check the vehicle length (callback) */
224 uint16 veh_len = CALLBACK_FAILED;
225 if (e_u->GetGRF() != NULL && e_u->GetGRF()->grf_version >= 8) {
226 /* Use callback 36 */
227 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
229 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
230 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
232 } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
233 /* Use callback 11 */
234 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
236 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
237 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
239 if (allowed_changes & CCF_LENGTH) {
240 /* Update vehicle length. */
241 u->gcache.cached_veh_length = veh_len;
242 } else {
243 /* Verify length hasn't changed. */
244 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
247 this->gcache.cached_total_length += u->gcache.cached_veh_length;
248 this->InvalidateNewGRFCache();
249 u->InvalidateNewGRFCache();
252 /* store consist weight/max speed in cache */
253 this->vcache.cached_max_speed = max_speed;
254 this->tcache.cached_tilt = train_can_tilt;
255 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
257 /* 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) */
258 this->CargoChanged();
260 if (this->IsFrontEngine()) {
261 this->UpdateAcceleration();
262 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
263 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
264 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
265 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
270 * Get the stop location of (the center) of the front vehicle of a train at
271 * a platform of a station.
272 * @param station_id the ID of the station where we're stopping
273 * @param tile the tile where the vehicle currently is
274 * @param v the vehicle to get the stop location of
275 * @param station_ahead 'return' the amount of 1/16th tiles in front of the train
276 * @param station_length 'return' the station length in 1/16th tiles
277 * @return the location, calculated from the begin of the station to stop at.
279 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
281 const Station *st = Station::Get(station_id);
282 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
283 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
285 /* Default to the middle of the station for stations stops that are not in
286 * the order list like intermediate stations when non-stop is disabled */
287 OrderStopLocation osl = OSL_PLATFORM_MIDDLE;
288 if (v->gcache.cached_total_length >= *station_length) {
289 /* The train is longer than the station, make it stop at the far end of the platform */
290 osl = OSL_PLATFORM_FAR_END;
291 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
292 osl = v->current_order.GetStopLocation();
295 /* The stop location of the FRONT! of the train */
296 int stop;
297 switch (osl) {
298 default: NOT_REACHED();
300 case OSL_PLATFORM_NEAR_END:
301 stop = v->gcache.cached_total_length;
302 break;
304 case OSL_PLATFORM_MIDDLE:
305 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
306 break;
308 case OSL_PLATFORM_FAR_END:
309 stop = *station_length;
310 break;
313 /* Subtract half the front vehicle length of the train so we get the real
314 * stop location of the train. */
315 return stop - (v->gcache.cached_veh_length + 1) / 2;
320 * Computes train speed limit caused by curves
321 * @return imposed speed limit
323 int Train::GetCurveSpeedLimit() const
325 assert(this->First() == this);
327 static const int absolute_max_speed = UINT16_MAX;
328 int max_speed = absolute_max_speed;
330 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
332 int curvecount[2] = {0, 0};
334 /* first find the curve speed limit */
335 int numcurve = 0;
336 int sum = 0;
337 int pos = 0;
338 int lastpos = -1;
339 for (const Vehicle *u = this; u->Next() != NULL; u = u->Next(), pos++) {
340 Direction this_dir = u->direction;
341 Direction next_dir = u->Next()->direction;
343 DirDiff dirdiff = DirDifference(this_dir, next_dir);
344 if (dirdiff == DIRDIFF_SAME) continue;
346 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
347 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
348 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
349 if (lastpos != -1) {
350 numcurve++;
351 sum += pos - lastpos;
352 if (pos - lastpos == 1 && max_speed > 88) {
353 max_speed = 88;
356 lastpos = pos;
359 /* if we have a 90 degree turn, fix the speed limit to 60 */
360 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
361 max_speed = 61;
365 if (numcurve > 0 && max_speed > 88) {
366 if (curvecount[0] == 1 && curvecount[1] == 1) {
367 max_speed = absolute_max_speed;
368 } else {
369 sum /= numcurve;
370 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
374 if (max_speed != absolute_max_speed) {
375 /* Apply the engine's rail type curve speed advantage, if it slowed by curves */
376 const RailtypeInfo *rti = GetRailTypeInfo(this->railtype);
377 max_speed += (max_speed / 2) * rti->curve_speed;
379 if (this->tcache.cached_tilt) {
380 /* Apply max_speed bonus of 20% for a tilting train */
381 max_speed += max_speed / 5;
385 return max_speed;
389 * Calculates the maximum speed of the vehicle under its current conditions.
390 * @return Maximum speed of the vehicle.
392 int Train::GetCurrentMaxSpeed() const
394 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
395 this->gcache.cached_max_track_speed :
396 this->tcache.cached_max_curve_speed;
398 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
399 StationID sid = GetStationIndex(this->tile);
400 if (this->current_order.ShouldStopAtStation(this, sid)) {
401 int station_ahead;
402 int station_length;
403 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
405 /* The distance to go is whatever is still ahead of the train minus the
406 * distance from the train's stop location to the end of the platform */
407 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
409 if (distance_to_go > 0) {
410 int st_max_speed = 120;
412 int delta_v = this->cur_speed / (distance_to_go + 1);
413 if (max_speed > (this->cur_speed - delta_v)) {
414 st_max_speed = this->cur_speed - (delta_v / 10);
417 st_max_speed = max(st_max_speed, 25 * distance_to_go);
418 max_speed = min(max_speed, st_max_speed);
423 for (const Train *u = this; u != NULL; u = u->Next()) {
424 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
425 max_speed = min(max_speed, 61);
426 break;
429 /* Vehicle is on the middle part of a bridge. */
430 if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
431 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
435 max_speed = min(max_speed, this->current_order.GetMaxSpeed());
436 return min(max_speed, this->gcache.cached_max_track_speed);
439 /** Update acceleration of the train from the cached power and weight. */
440 void Train::UpdateAcceleration()
442 assert(this->IsFrontEngine() || this->IsFreeWagon());
444 uint power = this->gcache.cached_power;
445 uint weight = this->gcache.cached_weight;
446 assert(weight != 0);
447 this->acceleration = Clamp(power / weight * 4, 1, 255);
451 * Get the width of a train vehicle image in the GUI.
452 * @param offset Additional offset for positioning the sprite; set to NULL if not needed
453 * @return Width in pixels
455 int Train::GetDisplayImageWidth(Point *offset) const
457 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
458 int vehicle_pitch = 0;
460 const Engine *e = this->GetEngine();
461 if (e->GetGRF() != NULL && is_custom_sprite(e->u.rail.image_index)) {
462 reference_width = e->GetGRF()->traininfo_vehicle_width;
463 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
466 if (offset != NULL) {
467 offset->x = ScaleGUITrad(reference_width) / 2;
468 offset->y = ScaleGUITrad(vehicle_pitch);
470 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
473 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
475 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
476 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
480 * Get the sprite to display the train.
481 * @param direction Direction of view/travel.
482 * @param image_type Visualisation context.
483 * @return Sprite to display.
485 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
487 uint8 spritenum = this->spritenum;
489 if (HasBit(this->flags, VRF_REVERSE_DIRECTION)) direction = ReverseDir(direction);
491 if (is_custom_sprite(spritenum)) {
492 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
493 if (result->IsValid()) return;
495 spritenum = this->GetEngine()->original_image_index;
498 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
499 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
501 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
503 result->Set(sprite);
506 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
508 const Engine *e = Engine::Get(engine);
509 Direction dir = rear_head ? DIR_E : DIR_W;
510 uint8 spritenum = e->u.rail.image_index;
512 if (is_custom_sprite(spritenum)) {
513 GetCustomVehicleIcon(engine, dir, image_type, result);
514 if (result->IsValid()) {
515 if (e->GetGRF() != NULL) {
516 y += ScaleGUITrad(e->GetGRF()->traininfo_vehicle_pitch);
518 return;
521 spritenum = Engine::Get(engine)->original_image_index;
524 if (rear_head) spritenum++;
526 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
529 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
531 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
532 int yf = y;
533 int yr = y;
535 VehicleSpriteSeq seqf, seqr;
536 GetRailIcon(engine, false, yf, image_type, &seqf);
537 GetRailIcon(engine, true, yr, image_type, &seqr);
539 Rect rectf, rectr;
540 seqf.GetBounds(&rectf);
541 seqr.GetBounds(&rectr);
543 preferred_x = Clamp(preferred_x,
544 left - UnScaleGUI(rectf.left) + ScaleGUITrad(14),
545 right - UnScaleGUI(rectr.right) - ScaleGUITrad(15));
547 seqf.Draw(preferred_x - ScaleGUITrad(14), yf, pal, pal == PALETTE_CRASH);
548 seqr.Draw(preferred_x + ScaleGUITrad(15), yr, pal, pal == PALETTE_CRASH);
549 } else {
550 VehicleSpriteSeq seq;
551 GetRailIcon(engine, false, y, image_type, &seq);
553 Rect rect;
554 seq.GetBounds(&rect);
555 preferred_x = Clamp(preferred_x,
556 left - UnScaleGUI(rect.left),
557 right - UnScaleGUI(rect.right));
559 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
564 * Get the size of the sprite of a train sprite heading west, or both heads (used for lists).
565 * @param engine The engine to get the sprite from.
566 * @param[out] width The width of the sprite.
567 * @param[out] height The height of the sprite.
568 * @param[out] xoffs Number of pixels to shift the sprite to the right.
569 * @param[out] yoffs Number of pixels to shift the sprite downwards.
570 * @param image_type Context the sprite is used in.
572 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
574 int y = 0;
576 VehicleSpriteSeq seq;
577 GetRailIcon(engine, false, y, image_type, &seq);
579 Rect rect;
580 seq.GetBounds(&rect);
582 width = UnScaleGUI(rect.right - rect.left + 1);
583 height = UnScaleGUI(rect.bottom - rect.top + 1);
584 xoffs = UnScaleGUI(rect.left);
585 yoffs = UnScaleGUI(rect.top);
587 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
588 GetRailIcon(engine, true, y, image_type, &seq);
589 seq.GetBounds(&rect);
591 /* Calculate values relative to an imaginary center between the two sprites. */
592 width = ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
593 height = max<uint>(height, UnScaleGUI(rect.bottom - rect.top + 1));
594 xoffs = xoffs - ScaleGUITrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
595 yoffs = min(yoffs, UnScaleGUI(rect.top));
600 * Build a railroad wagon.
601 * @param tile tile of the depot where rail-vehicle is built.
602 * @param flags type of operation.
603 * @param e the engine to build.
604 * @param ret[out] the vehicle that has been built.
605 * @return the cost of this operation or an error.
607 static CommandCost CmdBuildRailWagon(TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
609 const RailVehicleInfo *rvi = &e->u.rail;
611 /* Check that the wagon can drive on the track in question */
612 if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
614 if (flags & DC_EXEC) {
615 Train *v = new Train();
616 *ret = v;
617 v->spritenum = rvi->image_index;
619 v->engine_type = e->index;
620 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
622 DiagDirection dir = GetRailDepotDirection(tile);
624 v->direction = DiagDirToDir(dir);
625 v->tile = tile;
627 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
628 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
630 v->x_pos = x;
631 v->y_pos = y;
632 v->z_pos = GetSlopePixelZ(x, y);
633 v->owner = _current_company;
634 v->track = TRACK_BIT_DEPOT;
635 v->vehstatus = VS_HIDDEN | VS_DEFPAL;
637 v->SetWagon();
639 v->SetFreeWagon();
640 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
642 v->cargo_type = e->GetDefaultCargoType();
643 v->cargo_cap = rvi->capacity;
644 v->refit_cap = 0;
646 v->railtype = rvi->railtype;
648 v->date_of_last_service = _date;
649 v->build_year = _cur_year;
650 v->sprite_seq.Set(SPR_IMG_QUERY);
651 v->random_bits = VehicleRandomBits();
653 v->group_id = DEFAULT_GROUP;
655 AddArticulatedParts(v);
657 _new_vehicle_id = v->index;
659 v->UpdatePosition();
660 v->First()->ConsistChanged(CCF_ARRANGE);
661 UpdateTrainGroupID(v->First());
663 CheckConsistencyOfArticulatedVehicle(v);
665 /* Try to connect the vehicle to one of free chains of wagons. */
666 Train *w;
667 FOR_ALL_TRAINS(w) {
668 if (w->tile == tile && ///< Same depot
669 w->IsFreeWagon() && ///< A free wagon chain
670 w->engine_type == e->index && ///< Same type
671 w->First() != v && ///< Don't connect to ourself
672 !(w->vehstatus & VS_CRASHED)) { ///< Not crashed/flooded
673 DoCommand(0, v->index | 1 << 20, w->Last()->index, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
674 break;
679 return CommandCost();
682 /** Move all free vehicles in the depot to the train */
683 static void NormalizeTrainVehInDepot(const Train *u)
685 const Train *v;
686 FOR_ALL_TRAINS(v) {
687 if (v->IsFreeWagon() && v->tile == u->tile &&
688 v->track == TRACK_BIT_DEPOT) {
689 if (DoCommand(0, v->index | 1 << 20, u->index, DC_EXEC,
690 CMD_MOVE_RAIL_VEHICLE).Failed())
691 break;
696 static void AddRearEngineToMultiheadedTrain(Train *v)
698 Train *u = new Train();
699 v->value >>= 1;
700 u->value = v->value;
701 u->direction = v->direction;
702 u->owner = v->owner;
703 u->tile = v->tile;
704 u->x_pos = v->x_pos;
705 u->y_pos = v->y_pos;
706 u->z_pos = v->z_pos;
707 u->track = TRACK_BIT_DEPOT;
708 u->vehstatus = v->vehstatus & ~VS_STOPPED;
709 u->spritenum = v->spritenum + 1;
710 u->cargo_type = v->cargo_type;
711 u->cargo_subtype = v->cargo_subtype;
712 u->cargo_cap = v->cargo_cap;
713 u->refit_cap = v->refit_cap;
714 u->railtype = v->railtype;
715 u->engine_type = v->engine_type;
716 u->date_of_last_service = v->date_of_last_service;
717 u->build_year = v->build_year;
718 u->sprite_seq.Set(SPR_IMG_QUERY);
719 u->random_bits = VehicleRandomBits();
720 v->SetMultiheaded();
721 u->SetMultiheaded();
722 v->SetNext(u);
723 u->UpdatePosition();
725 /* Now we need to link the front and rear engines together */
726 v->other_multiheaded_part = u;
727 u->other_multiheaded_part = v;
731 * Build a railroad vehicle.
732 * @param tile tile of the depot where rail-vehicle is built.
733 * @param flags type of operation.
734 * @param e the engine to build.
735 * @param data bit 0 prevents any free cars from being added to the train.
736 * @param ret[out] the vehicle that has been built.
737 * @return the cost of this operation or an error.
739 CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
741 const RailVehicleInfo *rvi = &e->u.rail;
743 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(tile, flags, e, ret);
745 /* Check if depot and new engine uses the same kind of tracks *
746 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
747 if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
749 if (flags & DC_EXEC) {
750 DiagDirection dir = GetRailDepotDirection(tile);
751 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
752 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
754 Train *v = new Train();
755 *ret = v;
756 v->direction = DiagDirToDir(dir);
757 v->tile = tile;
758 v->owner = _current_company;
759 v->x_pos = x;
760 v->y_pos = y;
761 v->z_pos = GetSlopePixelZ(x, y);
762 v->track = TRACK_BIT_DEPOT;
763 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
764 v->spritenum = rvi->image_index;
765 v->cargo_type = e->GetDefaultCargoType();
766 v->cargo_cap = rvi->capacity;
767 v->refit_cap = 0;
768 v->last_station_visited = INVALID_STATION;
769 v->last_loading_station = INVALID_STATION;
771 v->engine_type = e->index;
772 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
774 v->reliability = e->reliability;
775 v->reliability_spd_dec = e->reliability_spd_dec;
776 v->max_age = e->GetLifeLengthInDays();
778 v->railtype = rvi->railtype;
779 _new_vehicle_id = v->index;
781 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
782 v->date_of_last_service = _date;
783 v->build_year = _cur_year;
784 v->sprite_seq.Set(SPR_IMG_QUERY);
785 v->random_bits = VehicleRandomBits();
787 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
788 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
790 v->group_id = DEFAULT_GROUP;
792 v->SetFrontEngine();
793 v->SetEngine();
795 v->UpdatePosition();
797 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
798 AddRearEngineToMultiheadedTrain(v);
799 } else {
800 AddArticulatedParts(v);
803 v->ConsistChanged(CCF_ARRANGE);
804 UpdateTrainGroupID(v);
806 if (!HasBit(data, 0) && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
807 NormalizeTrainVehInDepot(v);
810 CheckConsistencyOfArticulatedVehicle(v);
813 return CommandCost();
816 static Train *FindGoodVehiclePos(const Train *src)
818 EngineID eng = src->engine_type;
819 TileIndex tile = src->tile;
821 Train *dst;
822 FOR_ALL_TRAINS(dst) {
823 if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
824 /* check so all vehicles in the line have the same engine. */
825 Train *t = dst;
826 while (t->engine_type == eng) {
827 t = t->Next();
828 if (t == NULL) return dst;
833 return NULL;
836 /** Helper type for lists/vectors of trains */
837 typedef SmallVector<Train *, 16> TrainList;
840 * Make a backup of a train into a train list.
841 * @param list to make the backup in
842 * @param t the train to make the backup of
844 static void MakeTrainBackup(TrainList &list, Train *t)
846 for (; t != NULL; t = t->Next()) *list.Append() = t;
850 * Restore the train from the backup list.
851 * @param list the train to restore.
853 static void RestoreTrainBackup(TrainList &list)
855 /* No train, nothing to do. */
856 if (list.Length() == 0) return;
858 Train *prev = NULL;
859 /* Iterate over the list and rebuild it. */
860 for (Train **iter = list.Begin(); iter != list.End(); iter++) {
861 Train *t = *iter;
862 if (prev != NULL) {
863 prev->SetNext(t);
864 } else if (t->Previous() != NULL) {
865 /* Make sure the head of the train is always the first in the chain. */
866 t->Previous()->SetNext(NULL);
868 prev = t;
873 * Remove the given wagon from its consist.
874 * @param part the part of the train to remove.
875 * @param chain whether to remove the whole chain.
877 static void RemoveFromConsist(Train *part, bool chain = false)
879 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
881 /* Unlink at the front, but make it point to the next
882 * vehicle after the to be remove part. */
883 if (part->Previous() != NULL) part->Previous()->SetNext(tail->Next());
885 /* Unlink at the back */
886 tail->SetNext(NULL);
890 * Inserts a chain into the train at dst.
891 * @param dst the place where to append after.
892 * @param chain the chain to actually add.
894 static void InsertInConsist(Train *dst, Train *chain)
896 /* We do not want to add something in the middle of an articulated part. */
897 assert(dst->Next() == NULL || !dst->Next()->IsArticulatedPart());
899 chain->Last()->SetNext(dst->Next());
900 dst->SetNext(chain);
904 * Normalise the dual heads in the train, i.e. if one is
905 * missing move that one to this train.
906 * @param t the train to normalise.
908 static void NormaliseDualHeads(Train *t)
910 for (; t != NULL; t = t->GetNextVehicle()) {
911 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
913 /* Make sure that there are no free cars before next engine */
914 Train *u;
915 for (u = t; u->Next() != NULL && !u->Next()->IsEngine(); u = u->Next()) {}
917 if (u == t->other_multiheaded_part) continue;
919 /* Remove the part from the 'wrong' train */
920 RemoveFromConsist(t->other_multiheaded_part);
921 /* And add it to the 'right' train */
922 InsertInConsist(u, t->other_multiheaded_part);
927 * Normalise the sub types of the parts in this chain.
928 * @param chain the chain to normalise.
930 static void NormaliseSubtypes(Train *chain)
932 /* Nothing to do */
933 if (chain == NULL) return;
935 /* We must be the first in the chain. */
936 assert(chain->Previous() == NULL);
938 /* Set the appropriate bits for the first in the chain. */
939 if (chain->IsWagon()) {
940 chain->SetFreeWagon();
941 } else {
942 assert(chain->IsEngine());
943 chain->SetFrontEngine();
946 /* Now clear the bits for the rest of the chain */
947 for (Train *t = chain->Next(); t != NULL; t = t->Next()) {
948 t->ClearFreeWagon();
949 t->ClearFrontEngine();
954 * Check/validate whether we may actually build a new train.
955 * @note All vehicles are/were 'heads' of their chains.
956 * @param original_dst The original destination chain.
957 * @param dst The destination chain after constructing the train.
958 * @param original_dst The original source chain.
959 * @param dst The source chain after constructing the train.
960 * @return possible error of this command.
962 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
964 /* Just add 'new' engines and subtract the original ones.
965 * If that's less than or equal to 0 we can be sure we did
966 * not add any engines (read: trains) along the way. */
967 if ((src != NULL && src->IsEngine() ? 1 : 0) +
968 (dst != NULL && dst->IsEngine() ? 1 : 0) -
969 (original_src != NULL && original_src->IsEngine() ? 1 : 0) -
970 (original_dst != NULL && original_dst->IsEngine() ? 1 : 0) <= 0) {
971 return CommandCost();
974 /* Get a free unit number and check whether it's within the bounds.
975 * There will always be a maximum of one new train. */
976 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
978 return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
982 * Check whether the train parts can be attached.
983 * @param t the train to check
984 * @return possible error of this command.
986 static CommandCost CheckTrainAttachment(Train *t)
988 /* No multi-part train, no need to check. */
989 if (t == NULL || t->Next() == NULL || !t->IsEngine()) return CommandCost();
991 /* The maximum length for a train. For each part we decrease this by one
992 * and if the result is negative the train is simply too long. */
993 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
995 Train *head = t;
996 Train *prev = t;
998 /* Break the prev -> t link so it always holds within the loop. */
999 t = t->Next();
1000 prev->SetNext(NULL);
1002 /* Make sure the cache is cleared. */
1003 head->InvalidateNewGRFCache();
1005 while (t != NULL) {
1006 allowed_len -= t->gcache.cached_veh_length;
1008 Train *next = t->Next();
1010 /* Unlink the to-be-added piece; it is already unlinked from the previous
1011 * part due to the fact that the prev -> t link is broken. */
1012 t->SetNext(NULL);
1014 /* Don't check callback for articulated or rear dual headed parts */
1015 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1016 /* Back up and clear the first_engine data to avoid using wagon override group */
1017 EngineID first_engine = t->gcache.first_engine;
1018 t->gcache.first_engine = INVALID_ENGINE;
1020 /* We don't want the cache to interfere. head's cache is cleared before
1021 * the loop and after each callback does not need to be cleared here. */
1022 t->InvalidateNewGRFCache();
1024 uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1026 /* Restore original first_engine data */
1027 t->gcache.first_engine = first_engine;
1029 /* We do not want to remember any cached variables from the test run */
1030 t->InvalidateNewGRFCache();
1031 head->InvalidateNewGRFCache();
1033 if (callback != CALLBACK_FAILED) {
1034 /* A failing callback means everything is okay */
1035 StringID error = STR_NULL;
1037 if (head->GetGRF()->grf_version < 8) {
1038 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1039 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1040 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1041 } else {
1042 if (callback < 0x400) {
1043 error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1044 } else {
1045 switch (callback) {
1046 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1047 case 0x401: // allow
1048 break;
1050 default: // unknown reason -> disallow
1051 case 0x402: // disallow attaching
1052 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1053 break;
1058 if (error != STR_NULL) return_cmd_error(error);
1062 /* And link it to the new part. */
1063 prev->SetNext(t);
1064 prev = t;
1065 t = next;
1068 if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1069 return CommandCost();
1073 * Validate whether we are going to create valid trains.
1074 * @note All vehicles are/were 'heads' of their chains.
1075 * @param original_dst The original destination chain.
1076 * @param dst The destination chain after constructing the train.
1077 * @param original_dst The original source chain.
1078 * @param dst The source chain after constructing the train.
1079 * @param check_limit Whether to check the vehicle limit.
1080 * @return possible error of this command.
1082 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1084 /* Check whether we may actually construct the trains. */
1085 CommandCost ret = CheckTrainAttachment(src);
1086 if (ret.Failed()) return ret;
1087 ret = CheckTrainAttachment(dst);
1088 if (ret.Failed()) return ret;
1090 /* Check whether we need to build a new train. */
1091 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1095 * Arrange the trains in the wanted way.
1096 * @param dst_head The destination chain of the to be moved vehicle.
1097 * @param dst The destination for the to be moved vehicle.
1098 * @param src_head The source chain of the to be moved vehicle.
1099 * @param src The to be moved vehicle.
1100 * @param move_chain Whether to move all vehicles after src or not.
1102 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1104 /* First determine the front of the two resulting trains */
1105 if (*src_head == *dst_head) {
1106 /* If we aren't moving part(s) to a new train, we are just moving the
1107 * front back and there is not destination head. */
1108 *dst_head = NULL;
1109 } else if (*dst_head == NULL) {
1110 /* If we are moving to a new train the head of the move train would become
1111 * the head of the new vehicle. */
1112 *dst_head = src;
1115 if (src == *src_head) {
1116 /* If we are moving the front of a train then we are, in effect, creating
1117 * a new head for the train. Point to that. Unless we are moving the whole
1118 * train in which case there is not 'source' train anymore.
1119 * In case we are a multiheaded part we want the complete thing to come
1120 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1121 * that is followed by a rear multihead we do not want to include that. */
1122 *src_head = move_chain ? NULL :
1123 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1126 /* Now it's just simply removing the part that we are going to move from the
1127 * source train and *if* the destination is a not a new train add the chain
1128 * at the destination location. */
1129 RemoveFromConsist(src, move_chain);
1130 if (*dst_head != src) InsertInConsist(dst, src);
1132 /* Now normalise the dual heads, that is move the dual heads around in such
1133 * a way that the head and rear of a dual head are in the same train */
1134 NormaliseDualHeads(*src_head);
1135 NormaliseDualHeads(*dst_head);
1139 * Normalise the head of the train again, i.e. that is tell the world that
1140 * we have changed and update all kinds of variables.
1141 * @param head the train to update.
1143 static void NormaliseTrainHead(Train *head)
1145 /* Not much to do! */
1146 if (head == NULL) return;
1148 /* Tell the 'world' the train changed. */
1149 head->ConsistChanged(CCF_ARRANGE);
1150 UpdateTrainGroupID(head);
1152 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1153 if (!head->IsFrontEngine()) return;
1155 /* Update the refit button and window */
1156 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1157 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1159 /* If we don't have a unit number yet, set one. */
1160 if (head->unitnumber != 0) return;
1161 head->unitnumber = GetFreeUnitNumber(VEH_TRAIN);
1165 * Move a rail vehicle around inside the depot.
1166 * @param tile unused
1167 * @param flags type of operation
1168 * Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
1169 * @param p1 various bitstuffed elements
1170 * - p1 (bit 0 - 19) source vehicle index
1171 * - p1 (bit 20) move all vehicles following the source vehicle
1172 * @param p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
1173 * @param text unused
1174 * @return the cost of this operation or an error
1176 CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1178 VehicleID s = GB(p1, 0, 20);
1179 VehicleID d = GB(p2, 0, 20);
1180 bool move_chain = HasBit(p1, 20);
1182 Train *src = Train::GetIfValid(s);
1183 if (src == NULL) return CMD_ERROR;
1185 CommandCost ret = CheckOwnership(src->owner);
1186 if (ret.Failed()) return ret;
1188 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1189 if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1191 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1192 Train *dst;
1193 if (d == INVALID_VEHICLE) {
1194 dst = src->IsEngine() ? NULL : FindGoodVehiclePos(src);
1195 } else {
1196 dst = Train::GetIfValid(d);
1197 if (dst == NULL) return CMD_ERROR;
1199 CommandCost ret = CheckOwnership(dst->owner);
1200 if (ret.Failed()) return ret;
1202 /* Do not allow appending to crashed vehicles, too */
1203 if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1206 /* if an articulated part is being handled, deal with its parent vehicle */
1207 src = src->GetFirstEnginePart();
1208 if (dst != NULL) {
1209 dst = dst->GetFirstEnginePart();
1212 /* don't move the same vehicle.. */
1213 if (src == dst) return CommandCost();
1215 /* locate the head of the two chains */
1216 Train *src_head = src->First();
1217 Train *dst_head;
1218 if (dst != NULL) {
1219 dst_head = dst->First();
1220 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1221 /* Now deal with articulated part of destination wagon */
1222 dst = dst->GetLastEnginePart();
1223 } else {
1224 dst_head = NULL;
1227 if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1229 /* When moving all wagons, we can't have the same src_head and dst_head */
1230 if (move_chain && src_head == dst_head) return CommandCost();
1232 /* When moving a multiheaded part to be place after itself, bail out. */
1233 if (!move_chain && dst != NULL && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1235 /* Check if all vehicles in the source train are stopped inside a depot. */
1236 if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1238 /* Check if all vehicles in the destination train are stopped inside a depot. */
1239 if (dst_head != NULL && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1241 /* First make a backup of the order of the trains. That way we can do
1242 * whatever we want with the order and later on easily revert. */
1243 TrainList original_src;
1244 TrainList original_dst;
1246 MakeTrainBackup(original_src, src_head);
1247 MakeTrainBackup(original_dst, dst_head);
1249 /* Also make backup of the original heads as ArrangeTrains can change them.
1250 * For the destination head we do not care if it is the same as the source
1251 * head because in that case it's just a copy. */
1252 Train *original_src_head = src_head;
1253 Train *original_dst_head = (dst_head == src_head ? NULL : dst_head);
1255 /* We want this information from before the rearrangement, but execute this after the validation.
1256 * original_src_head can't be NULL; src is by definition != NULL, so src_head can't be NULL as
1257 * src->GetFirst() always yields non-NULL, so eventually original_src_head != NULL as well. */
1258 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1259 bool original_dst_head_front_engine = original_dst_head != NULL && original_dst_head->IsFrontEngine();
1261 /* (Re)arrange the trains in the wanted arrangement. */
1262 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1264 if ((flags & DC_AUTOREPLACE) == 0) {
1265 /* If the autoreplace flag is set we do not need to test for the validity
1266 * because we are going to revert the train to its original state. As we
1267 * assume the original state was correct autoreplace can skip this. */
1268 CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1269 if (ret.Failed()) {
1270 /* Restore the train we had. */
1271 RestoreTrainBackup(original_src);
1272 RestoreTrainBackup(original_dst);
1273 return ret;
1277 /* do it? */
1278 if (flags & DC_EXEC) {
1279 /* Remove old heads from the statistics */
1280 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1281 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1283 /* First normalise the sub types of the chains. */
1284 NormaliseSubtypes(src_head);
1285 NormaliseSubtypes(dst_head);
1287 /* There are 14 different cases:
1288 * 1) front engine gets moved to a new train, it stays a front engine.
1289 * a) the 'next' part is a wagon that becomes a free wagon chain.
1290 * b) the 'next' part is an engine that becomes a front engine.
1291 * c) there is no 'next' part, nothing else happens
1292 * 2) front engine gets moved to another train, it is not a front engine anymore
1293 * a) the 'next' part is a wagon that becomes a free wagon chain.
1294 * b) the 'next' part is an engine that becomes a front engine.
1295 * c) there is no 'next' part, nothing else happens
1296 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1297 * a) the 'next' part is a wagon that becomes a free wagon chain.
1298 * b) the 'next' part is an engine that becomes a front engine.
1299 * 4) free wagon gets moved
1300 * a) the 'next' part is a wagon that becomes a free wagon chain.
1301 * b) the 'next' part is an engine that becomes a front engine.
1302 * c) there is no 'next' part, nothing else happens
1303 * 5) non front engine gets moved and becomes a new train, nothing else happens
1304 * 6) non front engine gets moved within a train / to another train, nothing hapens
1305 * 7) wagon gets moved, nothing happens
1307 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1308 /* Cases #2 and #3: the front engine gets trashed. */
1309 DeleteWindowById(WC_VEHICLE_VIEW, src->index);
1310 DeleteWindowById(WC_VEHICLE_ORDERS, src->index);
1311 DeleteWindowById(WC_VEHICLE_REFIT, src->index);
1312 DeleteWindowById(WC_VEHICLE_DETAILS, src->index);
1313 DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index);
1314 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1315 SetWindowDirty(WC_COMPANY, _current_company);
1317 /* Delete orders, group stuff and the unit number as we're not the
1318 * front of any vehicle anymore. */
1319 DeleteVehicleOrders(src);
1320 RemoveVehicleFromGroup(src);
1321 src->unitnumber = 0;
1324 /* We weren't a front engine but are becoming one. So
1325 * we should be put in the default group. */
1326 if (original_src_head != src && dst_head == src) {
1327 SetTrainGroupID(src, DEFAULT_GROUP);
1328 SetWindowDirty(WC_COMPANY, _current_company);
1331 /* Add new heads to statistics */
1332 if (src_head != NULL && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1333 if (dst_head != NULL && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1335 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1336 NormaliseTrainHead(src_head);
1337 NormaliseTrainHead(dst_head);
1339 if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1340 CheckCargoCapacity(src_head);
1341 CheckCargoCapacity(dst_head);
1344 if (src_head != NULL) src_head->First()->MarkDirty();
1345 if (dst_head != NULL) dst_head->First()->MarkDirty();
1347 /* We are undoubtedly changing something in the depot and train list. */
1348 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1349 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1350 } else {
1351 /* We don't want to execute what we're just tried. */
1352 RestoreTrainBackup(original_src);
1353 RestoreTrainBackup(original_dst);
1356 return CommandCost();
1360 * Sell a (single) train wagon/engine.
1361 * @param flags type of operation
1362 * @param t the train wagon to sell
1363 * @param data the selling mode
1364 * - data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
1365 * - data = 1: sell the vehicle and all vehicles following it in the chain
1366 * if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
1367 * @param user the user for the order backup.
1368 * @return the cost of this operation or an error
1370 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
1372 /* Sell a chain of vehicles or not? */
1373 bool sell_chain = HasBit(data, 0);
1375 Train *v = Train::From(t)->GetFirstEnginePart();
1376 Train *first = v->First();
1378 if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1380 /* First make a backup of the order of the train. That way we can do
1381 * whatever we want with the order and later on easily revert. */
1382 TrainList original;
1383 MakeTrainBackup(original, first);
1385 /* We need to keep track of the new head and the head of what we're going to sell. */
1386 Train *new_head = first;
1387 Train *sell_head = NULL;
1389 /* Split the train in the wanted way. */
1390 ArrangeTrains(&sell_head, NULL, &new_head, v, sell_chain);
1392 /* We don't need to validate the second train; it's going to be sold. */
1393 CommandCost ret = ValidateTrains(NULL, NULL, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1394 if (ret.Failed()) {
1395 /* Restore the train we had. */
1396 RestoreTrainBackup(original);
1397 return ret;
1400 if (first->orders.list == NULL && !OrderList::CanAllocateItem()) {
1401 /* Restore the train we had. */
1402 RestoreTrainBackup(original);
1403 return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1406 CommandCost cost(EXPENSES_NEW_VEHICLES);
1407 for (Train *t = sell_head; t != NULL; t = t->Next()) cost.AddCost(-t->value);
1409 /* do it? */
1410 if (flags & DC_EXEC) {
1411 /* First normalise the sub types of the chain. */
1412 NormaliseSubtypes(new_head);
1414 if (v == first && v->IsEngine() && !sell_chain && new_head != NULL && new_head->IsFrontEngine()) {
1415 /* We are selling the front engine. In this case we want to
1416 * 'give' the order, unit number and such to the new head. */
1417 new_head->orders.list = first->orders.list;
1418 new_head->AddToShared(first);
1419 DeleteVehicleOrders(first);
1421 /* Copy other important data from the front engine */
1422 new_head->CopyVehicleConfigAndStatistics(first);
1423 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1424 } else if (v->IsPrimaryVehicle() && data & (MAKE_ORDER_BACKUP_FLAG >> 20)) {
1425 OrderBackup::Backup(v, user);
1428 /* We need to update the information about the train. */
1429 NormaliseTrainHead(new_head);
1431 /* We are undoubtedly changing something in the depot and train list. */
1432 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1433 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1435 /* Actually delete the sold 'goods' */
1436 delete sell_head;
1437 } else {
1438 /* We don't want to execute what we're just tried. */
1439 RestoreTrainBackup(original);
1442 return cost;
1445 void Train::UpdateDeltaXY(Direction direction)
1447 /* Set common defaults. */
1448 this->x_offs = -1;
1449 this->y_offs = -1;
1450 this->x_extent = 3;
1451 this->y_extent = 3;
1452 this->z_extent = 6;
1453 this->x_bb_offs = 0;
1454 this->y_bb_offs = 0;
1456 if (!IsDiagonalDirection(direction)) {
1457 static const int _sign_table[] =
1459 /* x, y */
1460 -1, -1, // DIR_N
1461 -1, 1, // DIR_E
1462 1, 1, // DIR_S
1463 1, -1, // DIR_W
1466 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length) / 2;
1468 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1469 this->x_offs -= half_shorten * _sign_table[direction];
1470 this->y_offs -= half_shorten * _sign_table[direction + 1];
1471 this->x_extent += this->x_bb_offs = half_shorten * _sign_table[direction];
1472 this->y_extent += this->y_bb_offs = half_shorten * _sign_table[direction + 1];
1473 } else {
1474 switch (direction) {
1475 /* Shorten southern corner of the bounding box according the vehicle length
1476 * and center the bounding box on the vehicle. */
1477 case DIR_NE:
1478 this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1479 this->x_extent = this->gcache.cached_veh_length - 1;
1480 this->x_bb_offs = -1;
1481 break;
1483 case DIR_NW:
1484 this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2;
1485 this->y_extent = this->gcache.cached_veh_length - 1;
1486 this->y_bb_offs = -1;
1487 break;
1489 /* Move northern corner of the bounding box down according to vehicle length
1490 * and center the bounding box on the vehicle. */
1491 case DIR_SW:
1492 this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1493 this->x_extent = VEHICLE_LENGTH - 1;
1494 this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1495 break;
1497 case DIR_SE:
1498 this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH;
1499 this->y_extent = VEHICLE_LENGTH - 1;
1500 this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1501 break;
1503 default:
1504 NOT_REACHED();
1510 * Mark a train as stuck and stop it if it isn't stopped right now.
1511 * @param v %Train to mark as being stuck.
1513 static void MarkTrainAsStuck(Train *v)
1515 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1516 /* It is the first time the problem occurred, set the "train stuck" flag. */
1517 SetBit(v->flags, VRF_TRAIN_STUCK);
1519 v->wait_counter = 0;
1521 /* Stop train */
1522 v->cur_speed = 0;
1523 v->subspeed = 0;
1524 v->SetLastSpeed();
1526 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1531 * Swap the two up/down flags in two ways:
1532 * - Swap values of \a swap_flag1 and \a swap_flag2, and
1533 * - If going up previously (#GVF_GOINGUP_BIT set), the #GVF_GOINGDOWN_BIT is set, and vice versa.
1534 * @param swap_flag1 [inout] First train flag.
1535 * @param swap_flag2 [inout] Second train flag.
1537 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1539 uint16 flag1 = *swap_flag1;
1540 uint16 flag2 = *swap_flag2;
1542 /* Clear the flags */
1543 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1544 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1545 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1546 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1548 /* Reverse the rail-flags (if needed) */
1549 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1550 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1551 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1552 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1554 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1555 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1556 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1557 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1562 * Updates some variables after swapping the vehicle.
1563 * @param v swapped vehicle
1565 static void UpdateStatusAfterSwap(Train *v)
1567 /* Reverse the direction. */
1568 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1570 /* Call the proper EnterTile function unless we are in a wormhole. */
1571 if (v->track != TRACK_BIT_WORMHOLE) {
1572 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1573 } else {
1574 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1575 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1576 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1577 * when we shouldn't have. Check if this is the case. */
1578 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1579 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1580 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1581 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1582 /* We have just left the wormhole, possibly set the
1583 * "goingdown" bit. UpdateInclination() can be used
1584 * because we are at the border of the tile. */
1585 v->UpdatePosition();
1586 v->UpdateInclination(true, true);
1587 return;
1592 v->UpdatePosition();
1593 v->UpdateViewport(true, true);
1597 * Swap vehicles \a l and \a r in consist \a v, and reverse their direction.
1598 * @param v Consist to change.
1599 * @param l %Vehicle index in the consist of the first vehicle.
1600 * @param r %Vehicle index in the consist of the second vehicle.
1602 void ReverseTrainSwapVeh(Train *v, int l, int r)
1604 Train *a, *b;
1606 /* locate vehicles to swap */
1607 for (a = v; l != 0; l--) a = a->Next();
1608 for (b = v; r != 0; r--) b = b->Next();
1610 if (a != b) {
1611 /* swap the hidden bits */
1613 uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1614 b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1615 a->vehstatus = tmp;
1618 Swap(a->track, b->track);
1619 Swap(a->direction, b->direction);
1620 Swap(a->x_pos, b->x_pos);
1621 Swap(a->y_pos, b->y_pos);
1622 Swap(a->tile, b->tile);
1623 Swap(a->z_pos, b->z_pos);
1625 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1627 UpdateStatusAfterSwap(a);
1628 UpdateStatusAfterSwap(b);
1629 } else {
1630 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1631 * This is a little bit redundant way, a->gv_flags will
1632 * be (re)set twice, but it reduces code duplication */
1633 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1634 UpdateStatusAfterSwap(a);
1640 * Check if the vehicle is a train
1641 * @param v vehicle on tile
1642 * @return v if it is a train, NULL otherwise
1644 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1646 return (v->type == VEH_TRAIN) ? v : NULL;
1651 * Checks if a train is approaching a rail-road crossing
1652 * @param v vehicle on tile
1653 * @param data tile with crossing we are testing
1654 * @return v if it is approaching a crossing, NULL otherwise
1656 static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
1658 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
1660 Train *t = Train::From(v);
1661 if (!t->IsFrontEngine()) return NULL;
1663 TileIndex tile = *(TileIndex *)data;
1665 if (TrainApproachingCrossingTile(t) != tile) return NULL;
1667 return t;
1672 * Finds a vehicle approaching rail-road crossing
1673 * @param tile tile to test
1674 * @return true if a vehicle is approaching the crossing
1675 * @pre tile is a rail-road crossing
1677 static bool TrainApproachingCrossing(TileIndex tile)
1679 assert(IsLevelCrossingTile(tile));
1681 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1682 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1684 if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1686 dir = ReverseDiagDir(dir);
1687 tile_from = tile + TileOffsByDiagDir(dir);
1689 return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1694 * Sets correct crossing state
1695 * @param tile tile to update
1696 * @param sound should we play sound?
1697 * @pre tile is a rail-road crossing
1699 void UpdateLevelCrossing(TileIndex tile, bool sound)
1701 assert(IsLevelCrossingTile(tile));
1703 /* train on crossing || train approaching crossing || reserved */
1704 bool new_state = HasVehicleOnPos(tile, NULL, &TrainOnTileEnum) || TrainApproachingCrossing(tile) || HasCrossingReservation(tile);
1706 if (new_state != IsCrossingBarred(tile)) {
1707 if (new_state && sound) {
1708 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1710 SetCrossingBarred(tile, new_state);
1711 MarkTileDirtyByTile(tile);
1717 * Bars crossing and plays ding-ding sound if not barred already
1718 * @param tile tile with crossing
1719 * @pre tile is a rail-road crossing
1721 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1723 if (!IsCrossingBarred(tile)) {
1724 BarCrossing(tile);
1725 if (_settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1726 MarkTileDirtyByTile(tile);
1732 * Advances wagons for train reversing, needed for variable length wagons.
1733 * This one is called before the train is reversed.
1734 * @param v First vehicle in chain
1736 static void AdvanceWagonsBeforeSwap(Train *v)
1738 Train *base = v;
1739 Train *first = base; // first vehicle to move
1740 Train *last = v->Last(); // last vehicle to move
1741 uint length = CountVehiclesInChain(v);
1743 while (length > 2) {
1744 last = last->Previous();
1745 first = first->Next();
1747 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1749 /* do not update images now
1750 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1751 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1753 base = first; // == base->Next()
1754 length -= 2;
1760 * Advances wagons for train reversing, needed for variable length wagons.
1761 * This one is called after the train is reversed.
1762 * @param v First vehicle in chain
1764 static void AdvanceWagonsAfterSwap(Train *v)
1766 /* first of all, fix the situation when the train was entering a depot */
1767 Train *dep = v; // last vehicle in front of just left depot
1768 while (dep->Next() != NULL && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1769 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1772 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1774 if (leave != NULL) {
1775 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1776 int d = TicksToLeaveDepot(dep);
1778 if (d <= 0) {
1779 leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1780 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1781 for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
1783 } else {
1784 dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
1787 Train *base = v;
1788 Train *first = base; // first vehicle to move
1789 Train *last = v->Last(); // last vehicle to move
1790 uint length = CountVehiclesInChain(v);
1792 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1793 * they have already correct spacing, so we have to make sure they are moved how they should */
1794 bool nomove = (dep == NULL); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1796 while (length > 2) {
1797 /* we reached vehicle (originally) in front of a depot, stop now
1798 * (we would move wagons that are already moved with new wagon length). */
1799 if (base == dep) break;
1801 /* the last wagon was that one leaving a depot, so do not move it anymore */
1802 if (last == dep) nomove = true;
1804 last = last->Previous();
1805 first = first->Next();
1807 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1809 /* do not update images now */
1810 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : NULL));
1812 base = first; // == base->Next()
1813 length -= 2;
1818 * Turn a train around.
1819 * @param v %Train to turn around.
1821 void ReverseTrainDirection(Train *v)
1823 if (IsRailDepotTile(v->tile)) {
1824 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1827 /* Clear path reservation in front if train is not stuck. */
1828 if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1830 /* Check if we were approaching a rail/road-crossing */
1831 TileIndex crossing = TrainApproachingCrossingTile(v);
1833 /* count number of vehicles */
1834 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1836 AdvanceWagonsBeforeSwap(v);
1838 /* swap start<>end, start+1<>end-1, ... */
1839 int l = 0;
1840 do {
1841 ReverseTrainSwapVeh(v, l++, r--);
1842 } while (l <= r);
1844 AdvanceWagonsAfterSwap(v);
1846 if (IsRailDepotTile(v->tile)) {
1847 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1850 ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1852 ClrBit(v->flags, VRF_REVERSING);
1854 /* recalculate cached data */
1855 v->ConsistChanged(CCF_TRACK);
1857 /* update all images */
1858 for (Train *u = v; u != NULL; u = u->Next()) u->UpdateViewport(false, false);
1860 /* update crossing we were approaching */
1861 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1863 /* maybe we are approaching crossing now, after reversal */
1864 crossing = TrainApproachingCrossingTile(v);
1865 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1867 /* If we are inside a depot after reversing, don't bother with path reserving. */
1868 if (v->track == TRACK_BIT_DEPOT) {
1869 /* Can't be stuck here as inside a depot is always a safe tile. */
1870 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1871 ClrBit(v->flags, VRF_TRAIN_STUCK);
1872 return;
1875 /* TrainExitDir does not always produce the desired dir for depots and
1876 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1877 DiagDirection dir = TrainExitDir(v->direction, v->track);
1878 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
1880 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
1881 /* If we are currently on a tile with conventional signals, we can't treat the
1882 * current tile as a safe tile or we would enter a PBS block without a reservation. */
1883 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1884 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
1885 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1887 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1888 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1890 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1891 if (TryPathReserve(v, false, first_tile_okay)) {
1892 /* Do a look-ahead now in case our current tile was already a safe tile. */
1893 CheckNextTrainTile(v);
1894 } else if (v->current_order.GetType() != OT_LOADING) {
1895 /* Do not wait for a way out when we're still loading */
1896 MarkTrainAsStuck(v);
1898 } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1899 /* A train not inside a PBS block can't be stuck. */
1900 ClrBit(v->flags, VRF_TRAIN_STUCK);
1901 v->wait_counter = 0;
1906 * Reverse train.
1907 * @param tile unused
1908 * @param flags type of operation
1909 * @param p1 train to reverse
1910 * @param p2 if true, reverse a unit in a train (needs to be in a depot)
1911 * @param text unused
1912 * @return the cost of this operation or an error
1914 CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1916 Train *v = Train::GetIfValid(p1);
1917 if (v == NULL) return CMD_ERROR;
1919 CommandCost ret = CheckOwnership(v->owner);
1920 if (ret.Failed()) return ret;
1922 if (p2 != 0) {
1923 /* turn a single unit around */
1925 if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
1926 return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
1928 if (!HasBit(EngInfo(v->engine_type)->misc_flags, EF_RAIL_FLIPS)) return CMD_ERROR;
1930 Train *front = v->First();
1931 /* make sure the vehicle is stopped in the depot */
1932 if (!front->IsStoppedInDepot()) {
1933 return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1936 if (flags & DC_EXEC) {
1937 ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
1939 front->ConsistChanged(CCF_ARRANGE);
1940 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
1941 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1942 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
1943 SetWindowClassesDirty(WC_TRAINS_LIST);
1945 } else {
1946 /* turn the whole train around */
1947 if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
1949 if (flags & DC_EXEC) {
1950 /* Properly leave the station if we are loading and won't be loading anymore */
1951 if (v->current_order.IsType(OT_LOADING)) {
1952 const Vehicle *last = v;
1953 while (last->Next() != NULL) last = last->Next();
1955 /* not a station || different station --> leave the station */
1956 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
1957 v->LeaveStation();
1961 /* We cancel any 'skip signal at dangers' here */
1962 v->force_proceed = TFP_NONE;
1963 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
1965 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
1966 ToggleBit(v->flags, VRF_REVERSING);
1967 } else {
1968 v->cur_speed = 0;
1969 v->SetLastSpeed();
1970 HideFillingPercent(&v->fill_percent_te_id);
1971 ReverseTrainDirection(v);
1975 return CommandCost();
1979 * Force a train through a red signal
1980 * @param tile unused
1981 * @param flags type of operation
1982 * @param p1 train to ignore the red signal
1983 * @param p2 unused
1984 * @param text unused
1985 * @return the cost of this operation or an error
1987 CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1989 Train *t = Train::GetIfValid(p1);
1990 if (t == NULL) return CMD_ERROR;
1992 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
1994 CommandCost ret = CheckOwnership(t->owner);
1995 if (ret.Failed()) return ret;
1998 if (flags & DC_EXEC) {
1999 /* If we are forced to proceed, cancel that order.
2000 * If we are marked stuck we would want to force the train
2001 * to proceed to the next signal. In the other cases we
2002 * would like to pass the signal at danger and run till the
2003 * next signal we encounter. */
2004 t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2005 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2008 return CommandCost();
2012 * Try to find a depot nearby.
2013 * @param v %Train that wants a depot.
2014 * @param max_distance Maximal search distance.
2015 * @return Information where the closest train depot is located.
2016 * @pre The given vehicle must not be crashed!
2018 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2020 assert(!(v->vehstatus & VS_CRASHED));
2022 if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2024 PBSTileInfo origin = FollowTrainReservation(v);
2025 if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2027 switch (_settings_game.pf.pathfinder_for_trains) {
2028 case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2029 case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2031 default: NOT_REACHED();
2036 * Locate the closest depot for this consist, and return the information to the caller.
2037 * @param location [out] If not \c NULL and a depot is found, store its location in the given address.
2038 * @param destination [out] If not \c NULL and a depot is found, store its index in the given address.
2039 * @param reverse [out] If not \c NULL and a depot is found, store reversal information in the given address.
2040 * @return A depot has been found.
2042 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2044 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2045 if (tfdd.best_length == UINT_MAX) return false;
2047 if (location != NULL) *location = tfdd.tile;
2048 if (destination != NULL) *destination = GetDepotIndex(tfdd.tile);
2049 if (reverse != NULL) *reverse = tfdd.reverse;
2051 return true;
2054 /** Play a sound for a train leaving the station. */
2055 void Train::PlayLeaveStationSound() const
2057 static const SoundFx sfx[] = {
2058 SND_04_TRAIN,
2059 SND_0A_TRAIN_HORN,
2060 SND_0A_TRAIN_HORN,
2061 SND_47_MAGLEV_2,
2062 SND_41_MAGLEV
2065 if (PlayVehicleSound(this, VSE_START)) return;
2067 EngineID engtype = this->engine_type;
2068 SndPlayVehicleFx(sfx[RailVehInfo(engtype)->engclass], this);
2072 * Check if the train is on the last reserved tile and try to extend the path then.
2073 * @param v %Train that needs its path extended.
2075 static void CheckNextTrainTile(Train *v)
2077 /* Don't do any look-ahead if path_backoff_interval is 255. */
2078 if (_settings_game.pf.path_backoff_interval == 255) return;
2080 /* Exit if we are inside a depot. */
2081 if (v->track == TRACK_BIT_DEPOT) return;
2083 switch (v->current_order.GetType()) {
2084 /* Exit if we reached our destination depot. */
2085 case OT_GOTO_DEPOT:
2086 if (v->tile == v->dest_tile) return;
2087 break;
2089 case OT_GOTO_WAYPOINT:
2090 /* If we reached our waypoint, make sure we see that. */
2091 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2092 break;
2094 case OT_NOTHING:
2095 case OT_LEAVESTATION:
2096 case OT_LOADING:
2097 /* Exit if the current order doesn't have a destination, but the train has orders. */
2098 if (v->GetNumOrders() > 0) return;
2099 break;
2101 default:
2102 break;
2104 /* Exit if we are on a station tile and are going to stop. */
2105 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2107 Trackdir td = v->GetVehicleTrackdir();
2109 /* On a tile with a red non-pbs signal, don't look ahead. */
2110 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2111 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2112 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2114 CFollowTrackRail ft(v);
2115 if (!ft.Follow(v->tile, td)) return;
2117 if (!HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(ft.m_new_td_bits))) {
2118 /* Next tile is not reserved. */
2119 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2120 if (HasPbsSignalOnTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) {
2121 /* If the next tile is a PBS signal, try to make a reservation. */
2122 TrackBits tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2123 if (_settings_game.pf.forbid_90_deg) {
2124 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.m_old_td));
2126 ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, NULL, false);
2133 * Will the train stay in the depot the next tick?
2134 * @param v %Train to check.
2135 * @return True if it stays in the depot, false otherwise.
2137 static bool CheckTrainStayInDepot(Train *v)
2139 /* bail out if not all wagons are in the same depot or not in a depot at all */
2140 for (const Train *u = v; u != NULL; u = u->Next()) {
2141 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2144 /* if the train got no power, then keep it in the depot */
2145 if (v->gcache.cached_power == 0) {
2146 v->vehstatus |= VS_STOPPED;
2147 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2148 return true;
2151 SigSegState seg_state;
2153 if (v->force_proceed == TFP_NONE) {
2154 /* force proceed was not pressed */
2155 if (++v->wait_counter < 37) {
2156 SetWindowClassesDirty(WC_TRAINS_LIST);
2157 return true;
2160 v->wait_counter = 0;
2162 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2163 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2164 /* Full and no PBS signal in block or depot reserved, can't exit. */
2165 SetWindowClassesDirty(WC_TRAINS_LIST);
2166 return true;
2168 } else {
2169 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2172 /* We are leaving a depot, but have to go to the exact same one; re-enter */
2173 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2174 /* We need to have a reservation for this to work. */
2175 if (HasDepotReservation(v->tile)) return true;
2176 SetDepotReservation(v->tile, true);
2177 VehicleEnterDepot(v);
2178 return true;
2181 /* Only leave when we can reserve a path to our destination. */
2182 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2183 /* No path and no force proceed. */
2184 SetWindowClassesDirty(WC_TRAINS_LIST);
2185 MarkTrainAsStuck(v);
2186 return true;
2189 SetDepotReservation(v->tile, true);
2190 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2192 VehicleServiceInDepot(v);
2193 SetWindowClassesDirty(WC_TRAINS_LIST);
2194 v->PlayLeaveStationSound();
2196 v->track = TRACK_BIT_X;
2197 if (v->direction & 2) v->track = TRACK_BIT_Y;
2199 v->vehstatus &= ~VS_HIDDEN;
2200 v->cur_speed = 0;
2202 v->UpdateViewport(true, true);
2203 v->UpdatePosition();
2204 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2205 v->UpdateAcceleration();
2206 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2208 return false;
2212 * Clear the reservation of \a tile that was just left by a wagon on \a track_dir.
2213 * @param v %Train owning the reservation.
2214 * @param tile Tile with reservation to clear.
2215 * @param track_dir Track direction to clear.
2217 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2219 DiagDirection dir = TrackdirToExitdir(track_dir);
2221 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2222 /* Are we just leaving a tunnel/bridge? */
2223 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2224 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2226 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2227 /* Free the reservation only if no other train is on the tiles. */
2228 SetTunnelBridgeReservation(tile, false);
2229 SetTunnelBridgeReservation(end, false);
2231 if (_settings_client.gui.show_track_reservation) {
2232 if (IsBridge(tile)) {
2233 MarkBridgeDirty(tile);
2234 } else {
2235 MarkTileDirtyByTile(tile);
2236 MarkTileDirtyByTile(end);
2241 } else if (IsRailStationTile(tile)) {
2242 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2243 /* If the new tile is not a further tile of the same station, we
2244 * clear the reservation for the whole platform. */
2245 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2246 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2248 } else {
2249 /* Any other tile */
2250 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2255 * Free the reserved path in front of a vehicle.
2256 * @param v %Train owning the reserved path.
2257 * @param origin %Tile to start clearing (if #INVALID_TILE, use the current tile of \a v).
2258 * @param orig_td Track direction (if #INVALID_TRACKDIR, use the track direction of \a v).
2260 void FreeTrainTrackReservation(const Train *v, TileIndex origin, Trackdir orig_td)
2262 assert(v->IsFrontEngine());
2264 TileIndex tile = origin != INVALID_TILE ? origin : v->tile;
2265 Trackdir td = orig_td != INVALID_TRACKDIR ? orig_td : v->GetVehicleTrackdir();
2266 bool free_tile = tile != v->tile || !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2267 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2269 /* Can't be holding a reservation if we enter a depot. */
2270 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2271 if (v->track == TRACK_BIT_DEPOT) {
2272 /* Front engine is in a depot. We enter if some part is not in the depot. */
2273 for (const Train *u = v; u != NULL; u = u->Next()) {
2274 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2277 /* Don't free reservation if it's not ours. */
2278 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2280 CFollowTrackRail ft(v, GetRailTypeInfo(v->railtype)->compatible_railtypes);
2281 while (ft.Follow(tile, td)) {
2282 tile = ft.m_new_tile;
2283 TrackdirBits bits = ft.m_new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2284 td = RemoveFirstTrackdir(&bits);
2285 assert(bits == TRACKDIR_BIT_NONE);
2287 if (!IsValidTrackdir(td)) break;
2289 if (IsTileType(tile, MP_RAILWAY)) {
2290 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2291 /* Conventional signal along trackdir: remove reservation and stop. */
2292 UnreserveRailTrack(tile, TrackdirToTrack(td));
2293 break;
2295 if (HasPbsSignalOnTrackdir(tile, td)) {
2296 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2297 /* Red PBS signal? Can't be our reservation, would be green then. */
2298 break;
2299 } else {
2300 /* Turn the signal back to red. */
2301 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2302 MarkTileDirtyByTile(tile);
2304 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2305 break;
2309 /* Don't free first station/bridge/tunnel if we are on it. */
2310 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);
2312 free_tile = true;
2316 static const byte _initial_tile_subcoord[6][4][3] = {
2317 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2318 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2319 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2320 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2321 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2322 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2326 * Perform pathfinding for a train.
2328 * @param v The train
2329 * @param tile The tile the train is about to enter
2330 * @param enterdir Diagonal direction the train is coming from
2331 * @param tracks Usable tracks on the new tile
2332 * @param path_found [out] Whether a path has been found or not.
2333 * @param do_track_reservation Path reservation is requested
2334 * @param dest [out] State and destination of the requested path
2335 * @return The best track the train should follow
2337 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
2339 switch (_settings_game.pf.pathfinder_for_trains) {
2340 case VPF_NPF: return NPFTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2341 case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest);
2343 default: NOT_REACHED();
2348 * Extend a train path as far as possible. Stops on encountering a safe tile,
2349 * another reservation or a track choice.
2350 * @return INVALID_TILE indicates that the reservation failed.
2352 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2354 PBSTileInfo origin = FollowTrainReservation(v);
2356 CFollowTrackRail ft(v);
2358 TileIndex tile = origin.tile;
2359 Trackdir cur_td = origin.trackdir;
2360 while (ft.Follow(tile, cur_td)) {
2361 if (KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE) {
2362 /* Possible signal tile. */
2363 if (HasOnewaySignalBlockingTrackdir(ft.m_new_tile, FindFirstTrackdir(ft.m_new_td_bits))) break;
2366 if (_settings_game.pf.forbid_90_deg) {
2367 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2368 if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2371 /* Station, depot or waypoint are a possible target. */
2372 bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2373 if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2374 /* Choice found or possible target encountered.
2375 * On finding a possible target, we need to stop and let the pathfinder handle the
2376 * remaining path. This is because we don't know if this target is in one of our
2377 * orders, so we might cause pathfinding to fail later on if we find a choice.
2378 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2379 * a wrong path not leading to our next destination. */
2380 if (HasReservedTracks(ft.m_new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.m_old_td)))) break;
2382 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2383 * actually starts its search at the first unreserved tile. */
2384 if (ft.m_tiles_skipped != 0) ft.m_new_tile -= TileOffsByDiagDir(ft.m_exitdir) * ft.m_tiles_skipped;
2386 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2387 if (new_tracks != NULL) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2388 if (enterdir != NULL) *enterdir = ft.m_exitdir;
2389 return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2392 tile = ft.m_new_tile;
2393 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2395 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2396 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2397 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2398 /* Safe position is all good, path valid and okay. */
2399 return PBSTileInfo(tile, cur_td, true);
2402 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2405 if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2406 /* End of line, path valid and okay. */
2407 return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2410 /* Sorry, can't reserve path, back out. */
2411 tile = origin.tile;
2412 cur_td = origin.trackdir;
2413 TileIndex stopped = ft.m_old_tile;
2414 Trackdir stopped_td = ft.m_old_td;
2415 while (tile != stopped || cur_td != stopped_td) {
2416 if (!ft.Follow(tile, cur_td)) break;
2418 if (_settings_game.pf.forbid_90_deg) {
2419 ft.m_new_td_bits &= ~TrackdirCrossesTrackdirs(ft.m_old_td);
2420 assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2422 assert(KillFirstBit(ft.m_new_td_bits) == TRACKDIR_BIT_NONE);
2424 tile = ft.m_new_tile;
2425 cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2427 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2430 /* Path invalid. */
2431 return PBSTileInfo();
2435 * Try to reserve any path to a safe tile, ignoring the vehicle's destination.
2436 * Safe tiles are tiles in front of a signal, depots and station tiles at end of line.
2438 * @param v The vehicle.
2439 * @param tile The tile the search should start from.
2440 * @param td The trackdir the search should start from.
2441 * @param override_railtype Whether all physically compatible railtypes should be followed.
2442 * @return True if a path to a safe stopping tile could be reserved.
2444 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
2446 switch (_settings_game.pf.pathfinder_for_trains) {
2447 case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2448 case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_tailtype);
2450 default: NOT_REACHED();
2454 /** This class will save the current order of a vehicle and restore it on destruction. */
2455 class VehicleOrderSaver {
2456 private:
2457 Train *v;
2458 Order old_order;
2459 TileIndex old_dest_tile;
2460 StationID old_last_station_visited;
2461 VehicleOrderID index;
2462 bool suppress_implicit_orders;
2464 public:
2465 VehicleOrderSaver(Train *_v) :
2466 v(_v),
2467 old_order(_v->current_order),
2468 old_dest_tile(_v->dest_tile),
2469 old_last_station_visited(_v->last_station_visited),
2470 index(_v->cur_real_order_index),
2471 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS))
2475 ~VehicleOrderSaver()
2477 this->v->current_order = this->old_order;
2478 this->v->dest_tile = this->old_dest_tile;
2479 this->v->last_station_visited = this->old_last_station_visited;
2480 SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2484 * Set the current vehicle order to the next order in the order list.
2485 * @param skip_first Shall the first (i.e. active) order be skipped?
2486 * @return True if a suitable next order could be found.
2488 bool SwitchToNextOrder(bool skip_first)
2490 if (this->v->GetNumOrders() == 0) return false;
2492 if (skip_first) ++this->index;
2494 int depth = 0;
2496 do {
2497 /* Wrap around. */
2498 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2500 Order *order = this->v->GetOrder(this->index);
2501 assert(order != NULL);
2503 switch (order->GetType()) {
2504 case OT_GOTO_DEPOT:
2505 /* Skip service in depot orders when the train doesn't need service. */
2506 if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2507 case OT_GOTO_STATION:
2508 case OT_GOTO_WAYPOINT:
2509 this->v->current_order = *order;
2510 return UpdateOrderDest(this->v, order, 0, true);
2511 case OT_CONDITIONAL: {
2512 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2513 if (next != INVALID_VEH_ORDER_ID) {
2514 depth++;
2515 this->index = next;
2516 /* Don't increment next, so no break here. */
2517 continue;
2519 break;
2521 default:
2522 break;
2524 /* Don't increment inside the while because otherwise conditional
2525 * orders can lead to an infinite loop. */
2526 ++this->index;
2527 depth++;
2528 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2530 return false;
2534 /* choose a track */
2535 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2537 Track best_track = INVALID_TRACK;
2538 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2539 bool changed_signal = false;
2541 assert((tracks & ~TRACK_BIT_MASK) == 0);
2543 if (got_reservation != NULL) *got_reservation = false;
2545 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2546 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2547 /* Do we have a suitable reserved track? */
2548 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2550 /* Quick return in case only one possible track is available */
2551 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2552 Track track = FindFirstTrack(tracks);
2553 /* We need to check for signals only here, as a junction tile can't have signals. */
2554 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2555 do_track_reservation = true;
2556 changed_signal = true;
2557 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2558 } else if (!do_track_reservation) {
2559 return track;
2561 best_track = track;
2564 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2565 DiagDirection dest_enterdir = enterdir;
2566 if (do_track_reservation) {
2567 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2568 if (res_dest.tile == INVALID_TILE) {
2569 /* Reservation failed? */
2570 if (mark_stuck) MarkTrainAsStuck(v);
2571 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2572 return FindFirstTrack(tracks);
2574 if (res_dest.okay) {
2575 /* Got a valid reservation that ends at a safe target, quick exit. */
2576 if (got_reservation != NULL) *got_reservation = true;
2577 if (changed_signal) MarkTileDirtyByTile(tile);
2578 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2579 return best_track;
2582 /* Check if the train needs service here, so it has a chance to always find a depot.
2583 * Also check if the current order is a service order so we don't reserve a path to
2584 * the destination but instead to the next one if service isn't needed. */
2585 CheckIfTrainNeedsService(v);
2586 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2589 /* Save the current train order. The destructor will restore the old order on function exit. */
2590 VehicleOrderSaver orders(v);
2592 /* If the current tile is the destination of the current order and
2593 * a reservation was requested, advance to the next order.
2594 * Don't advance on a depot order as depots are always safe end points
2595 * for a path and no look-ahead is necessary. This also avoids a
2596 * problem with depot orders not part of the order list when the
2597 * order list itself is empty. */
2598 if (v->current_order.IsType(OT_LEAVESTATION)) {
2599 orders.SwitchToNextOrder(false);
2600 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2601 v->current_order.IsType(OT_GOTO_STATION) ?
2602 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2603 v->tile == v->dest_tile))) {
2604 orders.SwitchToNextOrder(true);
2607 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2608 /* Pathfinders are able to tell that route was only 'guessed'. */
2609 bool path_found = true;
2610 TileIndex new_tile = res_dest.tile;
2612 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest);
2613 if (new_tile == tile) best_track = next_track;
2614 v->HandlePathfindingResult(path_found);
2617 /* No track reservation requested -> finished. */
2618 if (!do_track_reservation) return best_track;
2620 /* A path was found, but could not be reserved. */
2621 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2622 if (mark_stuck) MarkTrainAsStuck(v);
2623 FreeTrainTrackReservation(v);
2624 return best_track;
2627 /* No possible reservation target found, we are probably lost. */
2628 if (res_dest.tile == INVALID_TILE) {
2629 /* Try to find any safe destination. */
2630 PBSTileInfo origin = FollowTrainReservation(v);
2631 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2632 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2633 best_track = FindFirstTrack(res);
2634 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2635 if (got_reservation != NULL) *got_reservation = true;
2636 if (changed_signal) MarkTileDirtyByTile(tile);
2637 } else {
2638 FreeTrainTrackReservation(v);
2639 if (mark_stuck) MarkTrainAsStuck(v);
2641 return best_track;
2644 if (got_reservation != NULL) *got_reservation = true;
2646 /* Reservation target found and free, check if it is safe. */
2647 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2648 /* Extend reservation until we have found a safe position. */
2649 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2650 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2651 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
2652 if (_settings_game.pf.forbid_90_deg) {
2653 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2656 /* Get next order with destination. */
2657 if (orders.SwitchToNextOrder(true)) {
2658 PBSTileInfo cur_dest;
2659 bool path_found;
2660 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest);
2661 if (cur_dest.tile != INVALID_TILE) {
2662 res_dest = cur_dest;
2663 if (res_dest.okay) continue;
2664 /* Path found, but could not be reserved. */
2665 FreeTrainTrackReservation(v);
2666 if (mark_stuck) MarkTrainAsStuck(v);
2667 if (got_reservation != NULL) *got_reservation = false;
2668 changed_signal = false;
2669 break;
2672 /* No order or no safe position found, try any position. */
2673 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2674 FreeTrainTrackReservation(v);
2675 if (mark_stuck) MarkTrainAsStuck(v);
2676 if (got_reservation != NULL) *got_reservation = false;
2677 changed_signal = false;
2679 break;
2682 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2684 if (changed_signal) MarkTileDirtyByTile(tile);
2686 return best_track;
2690 * Try to reserve a path to a safe position.
2692 * @param v The vehicle
2693 * @param mark_as_stuck Should the train be marked as stuck on a failed reservation?
2694 * @param first_tile_okay True if no path should be reserved if the current tile is a safe position.
2695 * @return True if a path could be reserved.
2697 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2699 assert(v->IsFrontEngine());
2701 /* We have to handle depots specially as the track follower won't look
2702 * at the depot tile itself but starts from the next tile. If we are still
2703 * inside the depot, a depot reservation can never be ours. */
2704 if (v->track == TRACK_BIT_DEPOT) {
2705 if (HasDepotReservation(v->tile)) {
2706 if (mark_as_stuck) MarkTrainAsStuck(v);
2707 return false;
2708 } else {
2709 /* Depot not reserved, but the next tile might be. */
2710 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
2711 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2715 Vehicle *other_train = NULL;
2716 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2717 /* The path we are driving on is already blocked by some other train.
2718 * This can only happen in certain situations when mixing path and
2719 * block signals or when changing tracks and/or signals.
2720 * Exit here as doing any further reservations will probably just
2721 * make matters worse. */
2722 if (other_train != NULL && other_train->index != v->index) {
2723 if (mark_as_stuck) MarkTrainAsStuck(v);
2724 return false;
2726 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2727 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2728 /* Can't be stuck then. */
2729 if (HasBit(v->flags, VRF_TRAIN_STUCK)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2730 ClrBit(v->flags, VRF_TRAIN_STUCK);
2731 return true;
2734 /* If we are in a depot, tentatively reserve the depot. */
2735 if (v->track == TRACK_BIT_DEPOT) {
2736 SetDepotReservation(v->tile, true);
2737 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2740 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2741 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2742 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
2744 if (_settings_game.pf.forbid_90_deg) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
2746 bool res_made = false;
2747 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2749 if (!res_made) {
2750 /* Free the depot reservation as well. */
2751 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2752 return false;
2755 if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2756 v->wait_counter = 0;
2757 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2759 ClrBit(v->flags, VRF_TRAIN_STUCK);
2760 return true;
2764 static bool CheckReverseTrain(const Train *v)
2766 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2767 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2768 !(v->direction & 1)) {
2769 return false;
2772 assert(v->track != TRACK_BIT_NONE);
2774 switch (_settings_game.pf.pathfinder_for_trains) {
2775 case VPF_NPF: return NPFTrainCheckReverse(v);
2776 case VPF_YAPF: return YapfTrainCheckReverse(v);
2778 default: NOT_REACHED();
2783 * Get the location of the next station to visit.
2784 * @param station Next station to visit.
2785 * @return Location of the new station.
2787 TileIndex Train::GetOrderStationLocation(StationID station)
2789 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2791 const Station *st = Station::Get(station);
2792 if (!(st->facilities & FACIL_TRAIN)) {
2793 /* The destination station has no trainstation tiles. */
2794 this->IncrementRealOrderIndex();
2795 return 0;
2798 return st->xy;
2801 /** Goods at the consist have changed, update the graphics, cargo, and acceleration. */
2802 void Train::MarkDirty()
2804 Train *v = this;
2805 do {
2806 v->colourmap = PAL_NONE;
2807 v->UpdateViewport(true, false);
2808 } while ((v = v->Next()) != NULL);
2810 /* need to update acceleration and cached values since the goods on the train changed. */
2811 this->CargoChanged();
2812 this->UpdateAcceleration();
2816 * This function looks at the vehicle and updates its speed (cur_speed
2817 * and subspeed) variables. Furthermore, it returns the distance that
2818 * the train can drive this tick. #Vehicle::GetAdvanceDistance() determines
2819 * the distance to drive before moving a step on the map.
2820 * @return distance to drive.
2822 int Train::UpdateSpeed()
2824 switch (_settings_game.vehicle.train_acceleration_model) {
2825 default: NOT_REACHED();
2826 case AM_ORIGINAL:
2827 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2829 case AM_REALISTIC:
2830 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2835 * Trains enters a station, send out a news item if it is the first train, and start loading.
2836 * @param v Train that entered the station.
2837 * @param station Station visited.
2839 static void TrainEnterStation(Train *v, StationID station)
2841 v->last_station_visited = station;
2843 /* check if a train ever visited this station before */
2844 Station *st = Station::Get(station);
2845 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2846 st->had_vehicle_of_type |= HVOT_TRAIN;
2847 SetDParam(0, st->index);
2848 AddVehicleNewsItem(
2849 STR_NEWS_FIRST_TRAIN_ARRIVAL,
2850 v->owner == _local_company ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
2851 v->index,
2852 st->index
2854 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2855 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2858 v->force_proceed = TFP_NONE;
2859 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2861 v->BeginLoading();
2863 TriggerStationRandomisation(st, v->tile, SRT_TRAIN_ARRIVES);
2864 TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2867 /* Check if the vehicle is compatible with the specified tile */
2868 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2870 return IsTileOwner(tile, v->owner) &&
2871 (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2874 /** Data structure for storing engine speed changes of an acceleration type. */
2875 struct AccelerationSlowdownParams {
2876 byte small_turn; ///< Speed change due to a small turn.
2877 byte large_turn; ///< Speed change due to a large turn.
2878 byte z_up; ///< Fraction to remove when moving up.
2879 byte z_down; ///< Fraction to add when moving down.
2882 /** Speed update fractions for each acceleration type. */
2883 static const AccelerationSlowdownParams _accel_slowdown[] = {
2884 /* normal accel */
2885 {256 / 4, 256 / 2, 256 / 4, 2}, ///< normal
2886 {256 / 4, 256 / 2, 256 / 4, 2}, ///< monorail
2887 {0, 256 / 2, 256 / 4, 2}, ///< maglev
2891 * Modify the speed of the vehicle due to a change in altitude.
2892 * @param v %Train to update.
2893 * @param old_z Previous height.
2895 static inline void AffectSpeedByZChange(Train *v, int old_z)
2897 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
2899 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
2901 if (old_z < v->z_pos) {
2902 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
2903 } else {
2904 uint16 spd = v->cur_speed + asp->z_down;
2905 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
2909 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
2911 if (IsTileType(tile, MP_RAILWAY) &&
2912 GetRailTileType(tile) == RAIL_TILE_SIGNALS) {
2913 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
2914 Trackdir trackdir = FindFirstTrackdir(tracks);
2915 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
2916 /* A PBS block with a non-PBS signal facing us? */
2917 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
2920 return false;
2923 /** Tries to reserve track under whole train consist. */
2924 void Train::ReserveTrackUnderConsist() const
2926 for (const Train *u = this; u != NULL; u = u->Next()) {
2927 switch (u->track) {
2928 case TRACK_BIT_WORMHOLE:
2929 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
2930 break;
2931 case TRACK_BIT_DEPOT:
2932 break;
2933 default:
2934 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
2935 break;
2941 * The train vehicle crashed!
2942 * Update its status and other parts around it.
2943 * @param flooded Crash was caused by flooding.
2944 * @return Number of people killed.
2946 uint Train::Crash(bool flooded)
2948 uint pass = 0;
2949 if (this->IsFrontEngine()) {
2950 pass += 2; // driver
2952 /* Remove the reserved path in front of the train if it is not stuck.
2953 * Also clear all reserved tracks the train is currently on. */
2954 if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
2955 for (const Train *v = this; v != NULL; v = v->Next()) {
2956 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
2957 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
2958 /* ClearPathReservation will not free the wormhole exit
2959 * if the train has just entered the wormhole. */
2960 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
2964 /* we may need to update crossing we were approaching,
2965 * but must be updated after the train has been marked crashed */
2966 TileIndex crossing = TrainApproachingCrossingTile(this);
2967 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2969 /* Remove the loading indicators (if any) */
2970 HideFillingPercent(&this->fill_percent_te_id);
2973 pass += this->GroundVehicleBase::Crash(flooded);
2975 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
2976 return pass;
2980 * Marks train as crashed and creates an AI event.
2981 * Doesn't do anything if the train is crashed already.
2982 * @param v first vehicle of chain
2983 * @return number of victims (including 2 drivers; zero if train was already crashed)
2985 static uint TrainCrashed(Train *v)
2987 uint num = 0;
2989 /* do not crash train twice */
2990 if (!(v->vehstatus & VS_CRASHED)) {
2991 num = v->Crash();
2992 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2993 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
2996 /* Try to re-reserve track under already crashed train too.
2997 * Crash() clears the reservation! */
2998 v->ReserveTrackUnderConsist();
3000 return num;
3003 /** Temporary data storage for testing collisions. */
3004 struct TrainCollideChecker {
3005 Train *v; ///< %Vehicle we are testing for collision.
3006 uint num; ///< Total number of victims if train collided.
3010 * Collision test function.
3011 * @param v %Train vehicle to test collision with.
3012 * @param data %Train being examined.
3013 * @return \c NULL (always continue search)
3015 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3017 TrainCollideChecker *tcc = (TrainCollideChecker*)data;
3019 /* not a train or in depot */
3020 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
3022 /* do not crash into trains of another company. */
3023 if (v->owner != tcc->v->owner) return NULL;
3025 /* get first vehicle now to make most usual checks faster */
3026 Train *coll = Train::From(v)->First();
3028 /* can't collide with own wagons */
3029 if (coll == tcc->v) return NULL;
3031 int x_diff = v->x_pos - tcc->v->x_pos;
3032 int y_diff = v->y_pos - tcc->v->y_pos;
3034 /* Do fast calculation to check whether trains are not in close vicinity
3035 * and quickly reject trains distant enough for any collision.
3036 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3037 * Differences are then ORed and then we check for any higher bits */
3038 uint hash = (y_diff + 7) | (x_diff + 7);
3039 if (hash & ~15) return NULL;
3041 /* Slower check using multiplication */
3042 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3043 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return NULL;
3045 /* Happens when there is a train under bridge next to bridge head */
3046 if (abs(v->z_pos - tcc->v->z_pos) > 5) return NULL;
3048 /* crash both trains */
3049 tcc->num += TrainCrashed(tcc->v);
3050 tcc->num += TrainCrashed(coll);
3052 return NULL; // continue searching
3056 * Checks whether the specified train has a collision with another vehicle. If
3057 * so, destroys this vehicle, and the other vehicle if its subtype has TS_Front.
3058 * Reports the incident in a flashy news item, modifies station ratings and
3059 * plays a sound.
3060 * @param v %Train to test.
3062 static bool CheckTrainCollision(Train *v)
3064 /* can't collide in depot */
3065 if (v->track == TRACK_BIT_DEPOT) return false;
3067 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3069 TrainCollideChecker tcc;
3070 tcc.v = v;
3071 tcc.num = 0;
3073 /* find colliding vehicles */
3074 if (v->track == TRACK_BIT_WORMHOLE) {
3075 FindVehicleOnPos(v->tile, &tcc, FindTrainCollideEnum);
3076 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &tcc, FindTrainCollideEnum);
3077 } else {
3078 FindVehicleOnPosXY(v->x_pos, v->y_pos, &tcc, FindTrainCollideEnum);
3081 /* any dead -> no crash */
3082 if (tcc.num == 0) return false;
3084 SetDParam(0, tcc.num);
3085 AddVehicleNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->index);
3087 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3088 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_BIG_CRASH, v);
3089 return true;
3092 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3094 if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
3096 Train *t = Train::From(v);
3097 DiagDirection exitdir = *(DiagDirection *)data;
3099 /* not front engine of a train, inside wormhole or depot, crashed */
3100 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return NULL;
3102 if (t->cur_speed > 5 || TrainExitDir(t->direction, t->track) != exitdir) return NULL;
3104 return t;
3108 * Move a vehicle chain one movement stop forwards.
3109 * @param v First vehicle to move.
3110 * @param nomove Stop moving this and all following vehicles.
3111 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3112 * @return True if the vehicle could be moved forward, false otherwise.
3114 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3116 Train *first = v->First();
3117 Train *prev;
3118 bool direction_changed = false; // has direction of any part changed?
3120 /* For every vehicle after and including the given vehicle */
3121 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3122 DiagDirection enterdir = DIAGDIR_BEGIN;
3123 bool update_signals_crossing = false; // will we update signals or crossing state?
3125 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3126 if (v->track != TRACK_BIT_WORMHOLE) {
3127 /* Not inside tunnel */
3128 if (gp.old_tile == gp.new_tile) {
3129 /* Staying in the old tile */
3130 if (v->track == TRACK_BIT_DEPOT) {
3131 /* Inside depot */
3132 gp.x = v->x_pos;
3133 gp.y = v->y_pos;
3134 } else {
3135 /* Not inside depot */
3137 /* Reverse when we are at the end of the track already, do not move to the new position */
3138 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3140 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3141 if (HasBit(r, VETS_CANNOT_ENTER)) {
3142 goto invalid_rail;
3144 if (HasBit(r, VETS_ENTERED_STATION)) {
3145 /* The new position is the end of the platform */
3146 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3149 } else {
3150 /* A new tile is about to be entered. */
3152 /* Determine what direction we're entering the new tile from */
3153 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3154 assert(IsValidDiagDirection(enterdir));
3156 /* Get the status of the tracks in the new tile and mask
3157 * away the bits that aren't reachable. */
3158 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3159 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3161 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3162 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3164 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3165 if (_settings_game.pf.forbid_90_deg && prev == NULL) {
3166 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3167 * can be switched on halfway a turn */
3168 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3171 if (bits == TRACK_BIT_NONE) goto invalid_rail;
3173 /* Check if the new tile constrains tracks that are compatible
3174 * with the current train, if not, bail out. */
3175 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3177 TrackBits chosen_track;
3178 if (prev == NULL) {
3179 /* Currently the locomotive is active. Determine which one of the
3180 * available tracks to choose */
3181 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, NULL, true));
3182 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3184 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3185 /* For each signal we find decrease the counter by one.
3186 * We start at two, so the first signal we pass decreases
3187 * this to one, then if we reach the next signal it is
3188 * decreased to zero and we won't pass that new signal. */
3189 Trackdir dir = FindFirstTrackdir(trackdirbits);
3190 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3191 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3192 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3193 /* However, we do not want to be stopped by PBS signals
3194 * entered via the back. */
3195 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3196 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3200 /* Check if it's a red signal and that force proceed is not clicked. */
3201 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3202 /* In front of a red signal */
3203 Trackdir i = FindFirstTrackdir(trackdirbits);
3205 /* Don't handle stuck trains here. */
3206 if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3208 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3209 v->cur_speed = 0;
3210 v->subspeed = 0;
3211 v->progress = 255 - 100;
3212 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * 20) return false;
3213 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3214 v->cur_speed = 0;
3215 v->subspeed = 0;
3216 v->progress = 255 - 10;
3217 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * 73) {
3218 DiagDirection exitdir = TrackdirToExitdir(i);
3219 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3221 exitdir = ReverseDiagDir(exitdir);
3223 /* check if a train is waiting on the other side */
3224 if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3228 /* If we would reverse but are currently in a PBS block and
3229 * reversing of stuck trains is disabled, don't reverse.
3230 * This does not apply if the reason for reversing is a one-way
3231 * signal blocking us, because a train would then be stuck forever. */
3232 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3233 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3234 v->wait_counter = 0;
3235 return false;
3237 goto reverse_train_direction;
3238 } else {
3239 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3241 } else {
3242 /* The wagon is active, simply follow the prev vehicle. */
3243 if (prev->tile == gp.new_tile) {
3244 /* Choose the same track as prev */
3245 if (prev->track == TRACK_BIT_WORMHOLE) {
3246 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3247 * However, just choose the track into the wormhole. */
3248 assert(IsTunnel(prev->tile));
3249 chosen_track = bits;
3250 } else {
3251 chosen_track = prev->track;
3253 } else {
3254 /* Choose the track that leads to the tile where prev is.
3255 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3256 * I.e. when the tile between them has only space for a single vehicle like
3257 * 1) horizontal/vertical track tiles and
3258 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3259 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3261 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3262 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3263 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3264 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3265 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3267 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3268 assert(IsValidDiagDirection(exitdir));
3269 chosen_track = _connecting_track[enterdir][exitdir];
3271 chosen_track &= bits;
3274 /* Make sure chosen track is a valid track */
3275 assert(
3276 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3277 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3278 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3280 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3281 const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3282 gp.x = (gp.x & ~0xF) | b[0];
3283 gp.y = (gp.y & ~0xF) | b[1];
3284 Direction chosen_dir = (Direction)b[2];
3286 /* Call the landscape function and tell it that the vehicle entered the tile */
3287 uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3288 if (HasBit(r, VETS_CANNOT_ENTER)) {
3289 goto invalid_rail;
3292 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3293 Track track = FindFirstTrack(chosen_track);
3294 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3295 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3296 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3297 MarkTileDirtyByTile(gp.new_tile);
3300 /* Clear any track reservation when the last vehicle leaves the tile */
3301 if (v->Next() == NULL) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3303 v->tile = gp.new_tile;
3305 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3306 v->First()->ConsistChanged(CCF_TRACK);
3309 v->track = chosen_track;
3310 assert(v->track);
3313 /* We need to update signal status, but after the vehicle position hash
3314 * has been updated by UpdateInclination() */
3315 update_signals_crossing = true;
3317 if (chosen_dir != v->direction) {
3318 if (prev == NULL && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3319 const AccelerationSlowdownParams *asp = &_accel_slowdown[GetRailTypeInfo(v->railtype)->acceleration_type];
3320 DirDiff diff = DirDifference(v->direction, chosen_dir);
3321 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3323 direction_changed = true;
3324 v->direction = chosen_dir;
3327 if (v->IsFrontEngine()) {
3328 v->wait_counter = 0;
3330 /* If we are approaching a crossing that is reserved, play the sound now. */
3331 TileIndex crossing = TrainApproachingCrossingTile(v);
3332 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3334 /* Always try to extend the reservation when entering a tile. */
3335 CheckNextTrainTile(v);
3338 if (HasBit(r, VETS_ENTERED_STATION)) {
3339 /* The new position is the location where we want to stop */
3340 TrainEnterStation(v, r >> VETS_STATION_ID_OFFSET);
3343 } else {
3344 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
3345 /* Perform look-ahead on tunnel exit. */
3346 if (v->IsFrontEngine()) {
3347 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
3348 CheckNextTrainTile(v);
3350 /* Prevent v->UpdateInclination() being called with wrong parameters.
3351 * This could happen if the train was reversed inside the tunnel/bridge. */
3352 if (gp.old_tile == gp.new_tile) {
3353 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
3355 } else {
3356 v->x_pos = gp.x;
3357 v->y_pos = gp.y;
3358 v->UpdatePosition();
3359 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3360 continue;
3364 /* update image of train, as well as delta XY */
3365 v->UpdateDeltaXY(v->direction);
3367 v->x_pos = gp.x;
3368 v->y_pos = gp.y;
3369 v->UpdatePosition();
3371 /* update the Z position of the vehicle */
3372 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3374 if (prev == NULL) {
3375 /* This is the first vehicle in the train */
3376 AffectSpeedByZChange(v, old_z);
3379 if (update_signals_crossing) {
3380 if (v->IsFrontEngine()) {
3381 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3382 /* We are entering a block with PBS signals right now, but
3383 * not through a PBS signal. This means we don't have a
3384 * reservation right now. As a conventional signal will only
3385 * ever be green if no other train is in the block, getting
3386 * a path should always be possible. If the player built
3387 * such a strange network that it is not possible, the train
3388 * will be marked as stuck and the player has to deal with
3389 * the problem. */
3390 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3391 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3392 !TryPathReserve(v)) {
3393 MarkTrainAsStuck(v);
3398 /* Signals can only change when the first
3399 * (above) or the last vehicle moves. */
3400 if (v->Next() == NULL) {
3401 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3402 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
3406 /* Do not check on every tick to save some computing time. */
3407 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3410 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3412 return true;
3414 invalid_rail:
3415 /* We've reached end of line?? */
3416 if (prev != NULL) error("Disconnecting train");
3418 reverse_train_direction:
3419 if (reverse) {
3420 v->wait_counter = 0;
3421 v->cur_speed = 0;
3422 v->subspeed = 0;
3423 ReverseTrainDirection(v);
3426 return false;
3430 * Collect trackbits of all crashed train vehicles on a tile
3431 * @param v Vehicle passed from Find/HasVehicleOnPos()
3432 * @param data trackdirbits for the result
3433 * @return NULL to iterate over all vehicles on the tile.
3435 static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
3437 TrackBits *trackbits = (TrackBits *)data;
3439 if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3440 TrackBits train_tbits = Train::From(v)->track;
3441 if (train_tbits == TRACK_BIT_WORMHOLE) {
3442 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3443 *trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
3444 } else if (train_tbits != TRACK_BIT_DEPOT) {
3445 *trackbits |= train_tbits;
3449 return NULL;
3453 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
3454 * train, then goes to the last wagon and deletes that. Each call to this function
3455 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
3456 * or inside a tunnel/bridge, recalculate the signals as they might need updating
3457 * @param v the Vehicle of which last wagon is to be removed
3459 static void DeleteLastWagon(Train *v)
3461 Train *first = v->First();
3463 /* Go to the last wagon and delete the link pointing there
3464 * *u is then the one-before-last wagon, and *v the last
3465 * one which will physically be removed */
3466 Train *u = v;
3467 for (; v->Next() != NULL; v = v->Next()) u = v;
3468 u->SetNext(NULL);
3470 if (first != v) {
3471 /* Recalculate cached train properties */
3472 first->ConsistChanged(CCF_ARRANGE);
3473 /* Update the depot window if the first vehicle is in depot -
3474 * if v == first, then it is updated in PreDestructor() */
3475 if (first->track == TRACK_BIT_DEPOT) {
3476 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3478 v->last_station_visited = first->last_station_visited; // for PreDestructor
3481 /* 'v' shouldn't be accessed after it has been deleted */
3482 TrackBits trackbits = v->track;
3483 TileIndex tile = v->tile;
3484 Owner owner = v->owner;
3486 delete v;
3487 v = NULL; // make sure nobody will try to read 'v' anymore
3489 if (trackbits == TRACK_BIT_WORMHOLE) {
3490 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3491 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
3494 Track track = TrackBitsToTrack(trackbits);
3495 if (HasReservedTracks(tile, trackbits)) {
3496 UnreserveRailTrack(tile, track);
3498 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3499 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3500 FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3502 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3503 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3504 Track t;
3505 FOR_EACH_SET_TRACK(t, remaining_trackbits) TryReserveRailTrack(tile, t);
3508 /* check if the wagon was on a road/rail-crossing */
3509 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3511 /* Update signals */
3512 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3513 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
3514 } else {
3515 SetSignalsOnBothDir(tile, track, owner);
3520 * Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
3521 * @param v First crashed vehicle.
3523 static void ChangeTrainDirRandomly(Train *v)
3525 static const DirDiff delta[] = {
3526 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3529 do {
3530 /* We don't need to twist around vehicles if they're not visible */
3531 if (!(v->vehstatus & VS_HIDDEN)) {
3532 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3533 /* Refrain from updating the z position of the vehicle when on
3534 * a bridge, because UpdateInclination() will put the vehicle under
3535 * the bridge in that case */
3536 if (v->track != TRACK_BIT_WORMHOLE) {
3537 v->UpdatePosition();
3538 v->UpdateInclination(false, true);
3539 } else {
3540 v->UpdateViewport(false, true);
3543 } while ((v = v->Next()) != NULL);
3547 * Handle a crashed train.
3548 * @param v First train vehicle.
3549 * @return %Vehicle chain still exists.
3551 static bool HandleCrashedTrain(Train *v)
3553 int state = ++v->crash_anim_pos;
3555 if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3556 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3559 uint32 r;
3560 if (state <= 200 && Chance16R(1, 7, r)) {
3561 int index = (r * 10 >> 16);
3563 Vehicle *u = v;
3564 do {
3565 if (--index < 0) {
3566 r = Random();
3568 CreateEffectVehicleRel(u,
3569 GB(r, 8, 3) + 2,
3570 GB(r, 16, 3) + 2,
3571 GB(r, 0, 3) + 5,
3572 EV_EXPLOSION_SMALL);
3573 break;
3575 } while ((u = u->Next()) != NULL);
3578 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3580 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3581 bool ret = v->Next() != NULL;
3582 DeleteLastWagon(v);
3583 return ret;
3586 return true;
3589 /** Maximum speeds for train that is broken down or approaching line end */
3590 static const uint16 _breakdown_speeds[16] = {
3591 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3596 * Train is approaching line end, slow down and possibly reverse
3598 * @param v front train engine
3599 * @param signal not line end, just a red signal
3600 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3601 * @return true iff we did NOT have to reverse
3603 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3605 /* Calc position within the current tile */
3606 uint x = v->x_pos & 0xF;
3607 uint y = v->y_pos & 0xF;
3609 /* for diagonal directions, 'x' will be 0..15 -
3610 * for other directions, it will be 1, 3, 5, ..., 15 */
3611 switch (v->direction) {
3612 case DIR_N : x = ~x + ~y + 25; break;
3613 case DIR_NW: x = y; // FALL THROUGH
3614 case DIR_NE: x = ~x + 16; break;
3615 case DIR_E : x = ~x + y + 9; break;
3616 case DIR_SE: x = y; break;
3617 case DIR_S : x = x + y - 7; break;
3618 case DIR_W : x = ~y + x + 9; break;
3619 default: break;
3622 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3623 * does not cross the tile boundary when we do reverse, but as the vehicle's
3624 * location is based on their center, use half a vehicle's length as offset.
3625 * Multiply the half-length by two for straight directions to compensate that
3626 * we only get odd x offsets there. */
3627 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3628 /* we are too near the tile end, reverse now */
3629 v->cur_speed = 0;
3630 if (reverse) ReverseTrainDirection(v);
3631 return false;
3634 /* slow down */
3635 v->vehstatus |= VS_TRAIN_SLOWING;
3636 uint16 break_speed = _breakdown_speeds[x & 0xF];
3637 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3639 return true;
3644 * Determines whether train would like to leave the tile
3645 * @param v train to test
3646 * @return true iff vehicle is NOT entering or inside a depot or tunnel/bridge
3648 static bool TrainCanLeaveTile(const Train *v)
3650 /* Exit if inside a tunnel/bridge or a depot */
3651 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3653 TileIndex tile = v->tile;
3655 /* entering a tunnel/bridge? */
3656 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3657 DiagDirection dir = GetTunnelBridgeDirection(tile);
3658 if (DiagDirToDir(dir) == v->direction) return false;
3661 /* entering a depot? */
3662 if (IsRailDepotTile(tile)) {
3663 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
3664 if (DiagDirToDir(dir) == v->direction) return false;
3667 return true;
3672 * Determines whether train is approaching a rail-road crossing
3673 * (thus making it barred)
3674 * @param v front engine of train
3675 * @return TileIndex of crossing the train is approaching, else INVALID_TILE
3676 * @pre v in non-crashed front engine
3678 static TileIndex TrainApproachingCrossingTile(const Train *v)
3680 assert(v->IsFrontEngine());
3681 assert(!(v->vehstatus & VS_CRASHED));
3683 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3685 DiagDirection dir = TrainExitDir(v->direction, v->track);
3686 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3688 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3689 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3690 !CheckCompatibleRail(v, tile)) {
3691 return INVALID_TILE;
3694 return tile;
3699 * Checks for line end. Also, bars crossing at next tile if needed
3701 * @param v vehicle we are checking
3702 * @param reverse Set to false to not execute the vehicle reversing. This does not change any other logic.
3703 * @return true iff we did NOT have to reverse
3705 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3707 /* First, handle broken down train */
3709 int t = v->breakdown_ctr;
3710 if (t > 1) {
3711 v->vehstatus |= VS_TRAIN_SLOWING;
3713 uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3714 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3715 } else {
3716 v->vehstatus &= ~VS_TRAIN_SLOWING;
3719 if (!TrainCanLeaveTile(v)) return true;
3721 /* Determine the non-diagonal direction in which we will exit this tile */
3722 DiagDirection dir = TrainExitDir(v->direction, v->track);
3723 /* Calculate next tile */
3724 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3726 /* Determine the track status on the next tile */
3727 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3728 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3730 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3731 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3733 /* We are sure the train is not entering a depot, it is detected above */
3735 /* mask unreachable track bits if we are forbidden to do 90deg turns */
3736 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3737 if (_settings_game.pf.forbid_90_deg) {
3738 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3741 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3742 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3743 return TrainApproachingLineEnd(v, false, reverse);
3746 /* approaching red signal */
3747 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3749 /* approaching a rail/road crossing? then make it red */
3750 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
3752 return true;
3756 static bool TrainLocoHandler(Train *v, bool mode)
3758 /* train has crashed? */
3759 if (v->vehstatus & VS_CRASHED) {
3760 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3763 if (v->force_proceed != TFP_NONE) {
3764 ClrBit(v->flags, VRF_TRAIN_STUCK);
3765 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3768 /* train is broken down? */
3769 if (v->HandleBreakdown()) return true;
3771 if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3772 ReverseTrainDirection(v);
3775 /* exit if train is stopped */
3776 if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3778 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3779 if (ProcessOrders(v) && CheckReverseTrain(v)) {
3780 v->wait_counter = 0;
3781 v->cur_speed = 0;
3782 v->subspeed = 0;
3783 ClrBit(v->flags, VRF_LEAVING_STATION);
3784 ReverseTrainDirection(v);
3785 return true;
3786 } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3787 /* Try to reserve a path when leaving the station as we
3788 * might not be marked as wanting a reservation, e.g.
3789 * when an overlength train gets turned around in a station. */
3790 DiagDirection dir = TrainExitDir(v->direction, v->track);
3791 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
3793 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
3794 TryPathReserve(v, true, true);
3796 ClrBit(v->flags, VRF_LEAVING_STATION);
3799 v->HandleLoading(mode);
3801 if (v->current_order.IsType(OT_LOADING)) return true;
3803 if (CheckTrainStayInDepot(v)) return true;
3805 if (!mode) v->ShowVisualEffect();
3807 /* We had no order but have an order now, do look ahead. */
3808 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3809 CheckNextTrainTile(v);
3812 /* Handle stuck trains. */
3813 if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3814 ++v->wait_counter;
3816 /* Should we try reversing this tick if still stuck? */
3817 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
3819 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3820 if (!TryPathReserve(v)) {
3821 /* Still stuck. */
3822 if (turn_around) ReverseTrainDirection(v);
3824 if (HasBit(v->flags, VRF_TRAIN_STUCK) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * DAY_TICKS) {
3825 /* Show message to player. */
3826 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
3827 SetDParam(0, v->index);
3828 AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3830 v->wait_counter = 0;
3832 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3833 if (v->force_proceed == TFP_NONE) return true;
3834 ClrBit(v->flags, VRF_TRAIN_STUCK);
3835 v->wait_counter = 0;
3836 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3840 if (v->current_order.IsType(OT_LEAVESTATION)) {
3841 v->current_order.Free();
3842 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3843 return true;
3846 int j = v->UpdateSpeed();
3848 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3849 if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3850 /* If we manually stopped, we're not force-proceeding anymore. */
3851 v->force_proceed = TFP_NONE;
3852 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3855 int adv_spd = v->GetAdvanceDistance();
3856 if (j < adv_spd) {
3857 /* if the vehicle has speed 0, update the last_speed field. */
3858 if (v->cur_speed == 0) v->SetLastSpeed();
3859 } else {
3860 TrainCheckIfLineEnds(v);
3861 /* Loop until the train has finished moving. */
3862 for (;;) {
3863 j -= adv_spd;
3864 TrainController(v, NULL);
3865 /* Don't continue to move if the train crashed. */
3866 if (CheckTrainCollision(v)) break;
3867 /* Determine distance to next map position */
3868 adv_spd = v->GetAdvanceDistance();
3870 /* No more moving this tick */
3871 if (j < adv_spd || v->cur_speed == 0) break;
3873 OrderType order_type = v->current_order.GetType();
3874 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3875 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3876 (v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) &&
3877 IsTileType(v->tile, MP_STATION) &&
3878 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
3879 ProcessOrders(v);
3882 v->SetLastSpeed();
3885 for (Train *u = v; u != NULL; u = u->Next()) {
3886 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3888 u->UpdateViewport(false, false);
3891 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
3893 return true;
3897 * Get running cost for the train consist.
3898 * @return Yearly running costs.
3900 Money Train::GetRunningCost() const
3902 Money cost = 0;
3903 const Train *v = this;
3905 do {
3906 const Engine *e = v->GetEngine();
3907 if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
3909 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
3910 if (cost_factor == 0) continue;
3912 /* Halve running cost for multiheaded parts */
3913 if (v->IsMultiheaded()) cost_factor /= 2;
3915 cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
3916 } while ((v = v->GetNextVehicle()) != NULL);
3918 return cost;
3922 * Update train vehicle data for a tick.
3923 * @return True if the vehicle still exists, false if it has ceased to exist (front of consists only).
3925 bool Train::Tick()
3927 this->tick_counter++;
3929 if (this->IsFrontEngine()) {
3930 if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
3932 this->current_order_time++;
3934 if (!TrainLocoHandler(this, false)) return false;
3936 return TrainLocoHandler(this, true);
3937 } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
3938 /* Delete flooded standalone wagon chain */
3939 if (++this->crash_anim_pos >= 4400) {
3940 delete this;
3941 return false;
3945 return true;
3949 * Check whether a train needs service, and if so, find a depot or service it.
3950 * @return v %Train to check.
3952 static void CheckIfTrainNeedsService(Train *v)
3954 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
3955 if (v->IsChainInDepot()) {
3956 VehicleServiceInDepot(v);
3957 return;
3960 uint max_penalty;
3961 switch (_settings_game.pf.pathfinder_for_trains) {
3962 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
3963 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
3964 default: NOT_REACHED();
3967 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
3968 /* Only go to the depot if it is not too far out of our way. */
3969 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
3970 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
3971 /* If we were already heading for a depot but it has
3972 * suddenly moved farther away, we continue our normal
3973 * schedule? */
3974 v->current_order.MakeDummy();
3975 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3977 return;
3980 DepotID depot = GetDepotIndex(tfdd.tile);
3982 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
3983 v->current_order.GetDestination() != depot &&
3984 !Chance16(3, 16)) {
3985 return;
3988 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
3989 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
3990 v->dest_tile = tfdd.tile;
3991 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3994 /** Update day counters of the train vehicle. */
3995 void Train::OnNewDay()
3997 AgeVehicle(this);
3999 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4001 if (this->IsFrontEngine()) {
4002 CheckVehicleBreakdown(this);
4004 CheckIfTrainNeedsService(this);
4006 CheckOrders(this);
4008 /* update destination */
4009 if (this->current_order.IsType(OT_GOTO_STATION)) {
4010 TileIndex tile = Station::Get(this->current_order.GetDestination())->train_station.tile;
4011 if (tile != INVALID_TILE) this->dest_tile = tile;
4014 if (this->running_ticks != 0) {
4015 /* running costs */
4016 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
4018 this->profit_this_year -= cost.GetCost();
4019 this->running_ticks = 0;
4021 SubtractMoneyFromCompanyFract(this->owner, cost);
4023 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4024 SetWindowClassesDirty(WC_TRAINS_LIST);
4030 * Get the tracks of the train vehicle.
4031 * @return Current tracks of the vehicle.
4033 Trackdir Train::GetVehicleTrackdir() const
4035 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4037 if (this->track == TRACK_BIT_DEPOT) {
4038 /* We'll assume the train is facing outwards */
4039 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4042 if (this->track == TRACK_BIT_WORMHOLE) {
4043 /* train in tunnel or on bridge, so just use his direction and assume a diagonal track */
4044 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4047 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);