OpenTTD
Data Structures | Typedefs | Functions | Variables
train_cmd.cpp File Reference

Handling of trains. More...

#include "stdafx.h"
#include "error.h"
#include "articulated_vehicles.h"
#include "command_func.h"
#include "pathfinder/npf/npf_func.h"
#include "pathfinder/yapf/yapf.hpp"
#include "news_func.h"
#include "company_func.h"
#include "newgrf_sound.h"
#include "newgrf_text.h"
#include "strings_func.h"
#include "viewport_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "ai/ai.hpp"
#include "game/game.hpp"
#include "newgrf_station.h"
#include "effectvehicle_func.h"
#include "network/network.h"
#include "spritecache.h"
#include "core/random_func.hpp"
#include "company_base.h"
#include "newgrf.h"
#include "order_backup.h"
#include "zoom_func.h"
#include "newgrf_debug.h"
#include "table/strings.h"
#include "table/train_cmd.h"
#include "safeguards.h"

Go to the source code of this file.

Data Structures

class  VehicleOrderSaver
 This class will save the current order of a vehicle and restore it on destruction. More...
 
struct  AccelerationSlowdownParams
 Data structure for storing engine speed changes of an acceleration type. More...
 
struct  TrainCollideChecker
 Temporary data storage for testing collisions. More...
 

Typedefs

typedef SmallVector< Train *, 16 > TrainList
 Helper type for lists/vectors of trains.
 

Functions

static Track ChooseTrainTrack (Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
 
static bool TrainCheckIfLineEnds (Train *v, bool reverse)
 Checks for line end. More...
 
bool TrainController (Train *v, Vehicle *nomove, bool reverse)
 Move a vehicle chain one movement stop forwards. More...
 
static TileIndex TrainApproachingCrossingTile (const Train *v)
 Determines whether train is approaching a rail-road crossing (thus making it barred) More...
 
static void CheckIfTrainNeedsService (Train *v)
 Check whether a train needs service, and if so, find a depot or service it. More...
 
static void CheckNextTrainTile (Train *v)
 Check if the train is on the last reserved tile and try to extend the path then. More...
 
template<>
bool IsValidImageIndex< VEH_TRAIN > (uint8 image_index)
 
static DiagDirection TrainExitDir (Direction direction, TrackBits track)
 Determine the side in which the train will leave the tile. More...
 
byte FreightWagonMult (CargoID cargo)
 Return the cargo weight multiplier to use for a rail vehicle. More...
 
void CheckTrainsLengths ()
 Checks if lengths of all rail vehicles are valid. More...
 
int GetTrainStopLocation (StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
 Get the stop location of (the center) of the front vehicle of a train at a platform of a station. More...
 
static SpriteID GetDefaultTrainSprite (uint8 spritenum, Direction direction)
 
static void GetRailIcon (EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
 
void DrawTrainEngine (int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
 
void GetTrainSpriteSize (EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
 Get the size of the sprite of a train sprite heading west, or both heads (used for lists). More...
 
static CommandCost CmdBuildRailWagon (TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
 Build a railroad wagon. More...
 
static void NormalizeTrainVehInDepot (const Train *u)
 Move all free vehicles in the depot to the train.
 
static void AddRearEngineToMultiheadedTrain (Train *v)
 
CommandCost CmdBuildRailVehicle (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
 Build a railroad vehicle. More...
 
static TrainFindGoodVehiclePos (const Train *src)
 
static void MakeTrainBackup (TrainList &list, Train *t)
 Make a backup of a train into a train list. More...
 
static void RestoreTrainBackup (TrainList &list)
 Restore the train from the backup list. More...
 
static void RemoveFromConsist (Train *part, bool chain=false)
 Remove the given wagon from its consist. More...
 
static void InsertInConsist (Train *dst, Train *chain)
 Inserts a chain into the train at dst. More...
 
static void NormaliseDualHeads (Train *t)
 Normalise the dual heads in the train, i.e. More...
 
static void NormaliseSubtypes (Train *chain)
 Normalise the sub types of the parts in this chain. More...
 
static CommandCost CheckNewTrain (Train *original_dst, Train *dst, Train *original_src, Train *src)
 Check/validate whether we may actually build a new train. More...
 
static CommandCost CheckTrainAttachment (Train *t)
 Check whether the train parts can be attached. More...
 
static CommandCost ValidateTrains (Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
 Validate whether we are going to create valid trains. More...
 
static void ArrangeTrains (Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
 Arrange the trains in the wanted way. More...
 
static void NormaliseTrainHead (Train *head)
 Normalise the head of the train again, i.e. More...
 
CommandCost CmdMoveRailVehicle (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Move a rail vehicle around inside the depot. More...
 
CommandCost CmdSellRailWagon (DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
 Sell a (single) train wagon/engine. More...
 
static void MarkTrainAsStuck (Train *v)
 Mark a train as stuck and stop it if it isn't stopped right now. More...
 
static void SwapTrainFlags (uint16 *swap_flag1, uint16 *swap_flag2)
 Swap the two up/down flags in two ways: More...
 
static void UpdateStatusAfterSwap (Train *v)
 Updates some variables after swapping the vehicle. More...
 
void ReverseTrainSwapVeh (Train *v, int l, int r)
 Swap vehicles l and r in consist v, and reverse their direction. More...
 
static VehicleTrainOnTileEnum (Vehicle *v, void *)
 Check if the vehicle is a train. More...
 
static VehicleTrainApproachingCrossingEnum (Vehicle *v, void *data)
 Checks if a train is approaching a rail-road crossing. More...
 
static bool TrainApproachingCrossing (TileIndex tile)
 Finds a vehicle approaching rail-road crossing. More...
 
void UpdateLevelCrossing (TileIndex tile, bool sound)
 Sets correct crossing state. More...
 
static void MaybeBarCrossingWithSound (TileIndex tile)
 Bars crossing and plays ding-ding sound if not barred already. More...
 
static void AdvanceWagonsBeforeSwap (Train *v)
 Advances wagons for train reversing, needed for variable length wagons. More...
 
static void AdvanceWagonsAfterSwap (Train *v)
 Advances wagons for train reversing, needed for variable length wagons. More...
 
void ReverseTrainDirection (Train *v)
 Turn a train around. More...
 
CommandCost CmdReverseTrainDirection (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Reverse train. More...
 
CommandCost CmdForceTrainProceed (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Force a train through a red signal. More...
 
static FindDepotData FindClosestTrainDepot (Train *v, int max_distance)
 Try to find a depot nearby. More...
 
static bool CheckTrainStayInDepot (Train *v)
 Will the train stay in the depot the next tick? More...
 
static void ClearPathReservation (const Train *v, TileIndex tile, Trackdir track_dir)
 Clear the reservation of tile that was just left by a wagon on track_dir. More...
 
void FreeTrainTrackReservation (const Train *v)
 Free the reserved path in front of a vehicle. More...
 
static Track DoTrainPathfind (const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest)
 Perform pathfinding for a train. More...
 
static PBSTileInfo ExtendTrainReservation (const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
 Extend a train path as far as possible. More...
 
static bool TryReserveSafeTrack (const Train *v, TileIndex tile, Trackdir td, bool override_tailtype)
 Try to reserve any path to a safe tile, ignoring the vehicle's destination. More...
 
bool TryPathReserve (Train *v, bool mark_as_stuck, bool first_tile_okay)
 Try to reserve a path to a safe position. More...
 
static bool CheckReverseTrain (const Train *v)
 
static void TrainEnterStation (Train *v, StationID station)
 Trains enters a station, send out a news item if it is the first train, and start loading. More...
 
static bool CheckCompatibleRail (const Train *v, TileIndex tile)
 
static void AffectSpeedByZChange (Train *v, int old_z)
 Modify the speed of the vehicle due to a change in altitude. More...
 
static bool TrainMovedChangeSignals (TileIndex tile, DiagDirection dir)
 
static uint TrainCrashed (Train *v)
 Marks train as crashed and creates an AI event. More...
 
static VehicleFindTrainCollideEnum (Vehicle *v, void *data)
 Collision test function. More...
 
static bool CheckTrainCollision (Train *v)
 Checks whether the specified train has a collision with another vehicle. More...
 
static VehicleCheckTrainAtSignal (Vehicle *v, void *data)
 
static VehicleCollectTrackbitsFromCrashedVehiclesEnum (Vehicle *v, void *data)
 Collect trackbits of all crashed train vehicles on a tile. More...
 
static void DeleteLastWagon (Train *v)
 Deletes/Clears the last wagon of a crashed train. More...
 
static void ChangeTrainDirRandomly (Train *v)
 Rotate all vehicles of a (crashed) train chain randomly to animate the crash. More...
 
static bool HandleCrashedTrain (Train *v)
 Handle a crashed train. More...
 
static bool TrainApproachingLineEnd (Train *v, bool signal, bool reverse)
 Train is approaching line end, slow down and possibly reverse. More...
 
static bool TrainCanLeaveTile (const Train *v)
 Determines whether train would like to leave the tile. More...
 
static bool TrainLocoHandler (Train *v, bool mode)
 

Variables

static const byte _vehicle_initial_x_fract [4] = {10, 8, 4, 8}
 
static const byte _vehicle_initial_y_fract [4] = { 8, 4, 8, 10}
 
static const byte _initial_tile_subcoord [6][4][3]
 
static const AccelerationSlowdownParams _accel_slowdown []
 Speed update fractions for each acceleration type. More...
 
static const uint16 _breakdown_speeds [16]
 Maximum speeds for train that is broken down or approaching line end. More...
 

Detailed Description

Handling of trains.

Definition in file train_cmd.cpp.

Function Documentation

◆ AdvanceWagonsAfterSwap()

static void AdvanceWagonsAfterSwap ( Train v)
static

Advances wagons for train reversing, needed for variable length wagons.

This one is called after the train is reversed.

Parameters
vFirst vehicle in chain

Definition at line 1764 of file train_cmd.cpp.

References Vehicle::first, GetRailDepotTrack(), SpecializedVehicle< T, Type >::Last(), SpecializedVehicle< T, Type >::Next(), TicksToLeaveDepot(), Vehicle::tile, TRACK_BIT_DEPOT, TrackToTrackBits(), TrainController(), Vehicle::vehstatus, and VS_HIDDEN.

◆ AdvanceWagonsBeforeSwap()

static void AdvanceWagonsBeforeSwap ( Train v)
static

Advances wagons for train reversing, needed for variable length wagons.

This one is called before the train is reversed.

Parameters
vFirst vehicle in chain

Definition at line 1736 of file train_cmd.cpp.

References Vehicle::first, and SpecializedVehicle< T, Type >::Last().

◆ AffectSpeedByZChange()

static void AffectSpeedByZChange ( Train v,
int  old_z 
)
inlinestatic

Modify the speed of the vehicle due to a change in altitude.

Parameters
vTrain to update.
old_zPrevious height.

Definition at line 2894 of file train_cmd.cpp.

References _settings_game, VehicleSettings::train_acceleration_model, GameSettings::vehicle, and Vehicle::z_pos.

◆ ArrangeTrains()

static void ArrangeTrains ( Train **  dst_head,
Train dst,
Train **  src_head,
Train src,
bool  move_chain 
)
static

Arrange the trains in the wanted way.

Parameters
dst_headThe destination chain of the to be moved vehicle.
dstThe destination for the to be moved vehicle.
src_headThe source chain of the to be moved vehicle.
srcThe to be moved vehicle.
move_chainWhether to move all vehicles after src or not.

Definition at line 1102 of file train_cmd.cpp.

References Train::GetNextUnit(), SpecializedVehicle< T, Type >::GetNextVehicle(), InsertInConsist(), GroundVehicle< T, Type >::IsMultiheaded(), NormaliseDualHeads(), and RemoveFromConsist().

Referenced by CmdSellRailWagon().

◆ ChangeTrainDirRandomly()

static void ChangeTrainDirRandomly ( Train v)
static

Rotate all vehicles of a (crashed) train chain randomly to animate the crash.

Parameters
vFirst crashed vehicle.

Definition at line 3522 of file train_cmd.cpp.

References ChangeDir(), DIRDIFF_45LEFT, DIRDIFF_45RIGHT, DIRDIFF_SAME, Vehicle::direction, GB(), Vehicle::vehstatus, and VS_HIDDEN.

◆ CheckIfTrainNeedsService()

static void CheckIfTrainNeedsService ( Train v)
static

◆ CheckNewTrain()

static CommandCost CheckNewTrain ( Train original_dst,
Train dst,
Train original_src,
Train src 
)
static

Check/validate whether we may actually build a new train.

Note
All vehicles are/were 'heads' of their chains.
Parameters
original_dstThe original destination chain.
dstThe destination chain after constructing the train.
original_dstThe original source chain.
dstThe source chain after constructing the train.
Returns
possible error of this command.

Definition at line 962 of file train_cmd.cpp.

References _settings_game, GetFreeUnitNumber(), GroundVehicle< T, Type >::IsEngine(), VehicleSettings::max_trains, return_cmd_error, VEH_TRAIN, and GameSettings::vehicle.

Referenced by ValidateTrains().

◆ CheckNextTrainTile()

static void CheckNextTrainTile ( Train v)
static

Check if the train is on the last reserved tile and try to extend the path then.

Parameters
vTrain that needs its path extended.

Definition at line 2075 of file train_cmd.cpp.

References _settings_game, Vehicle::current_order, Order::GetType(), PathfinderSettings::path_backoff_interval, GameSettings::pf, and TRACK_BIT_DEPOT.

◆ CheckTrainAttachment()

static CommandCost CheckTrainAttachment ( Train t)
static

◆ CheckTrainCollision()

static bool CheckTrainCollision ( Train v)
static

Checks whether the specified train has a collision with another vehicle.

If so, destroys this vehicle, and the other vehicle if its subtype has TS_Front. Reports the incident in a flashy news item, modifies station ratings and plays a sound.

Parameters
vTrain to test.

Definition at line 3061 of file train_cmd.cpp.

References TRACK_BIT_DEPOT.

◆ CheckTrainsLengths()

void CheckTrainsLengths ( )

Checks if lengths of all rail vehicles are valid.

If not, shows an error message.

Definition at line 94 of file train_cmd.cpp.

References Vehicle::first.

◆ CheckTrainStayInDepot()

static bool CheckTrainStayInDepot ( Train v)
static

◆ ClearPathReservation()

static void ClearPathReservation ( const Train v,
TileIndex  tile,
Trackdir  track_dir 
)
static

◆ CmdBuildRailVehicle()

CommandCost CmdBuildRailVehicle ( TileIndex  tile,
DoCommandFlag  flags,
const Engine e,
uint16  data,
Vehicle **  ret 
)

Build a railroad vehicle.

Parameters
tiletile of the depot where rail-vehicle is built.
flagstype of operation.
ethe engine to build.
databit 0 prevents any free cars from being added to the train.
ret[out]the vehicle that has been built.
Returns
the cost of this operation or an error.

Definition at line 739 of file train_cmd.cpp.

References CMD_ERROR, CmdBuildRailWagon(), DC_EXEC, GetRailDepotDirection(), GetRailType(), HasPowerOnRail(), and RAILVEH_WAGON.

◆ CmdBuildRailWagon()

static CommandCost CmdBuildRailWagon ( TileIndex  tile,
DoCommandFlag  flags,
const Engine e,
Vehicle **  ret 
)
static

Build a railroad wagon.

Parameters
tiletile of the depot where rail-vehicle is built.
flagstype of operation.
ethe engine to build.
ret[out]the vehicle that has been built.
Returns
the cost of this operation or an error.

< Same depot

< A free wagon chain

< Same type

< Don't connect to ourself

< Not crashed/flooded

Definition at line 607 of file train_cmd.cpp.

References CMD_ERROR, DC_EXEC, DiagDirToDir(), Vehicle::direction, Vehicle::engine_type, GroundVehicleCache::first_engine, GroundVehicle< T, Type >::gcache, GetRailDepotDirection(), GetRailType(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, INVALID_ENGINE, IsCompatibleRail(), Vehicle::spritenum, Vehicle::tile, and Train::Train().

Referenced by CmdBuildRailVehicle().

◆ CmdForceTrainProceed()

CommandCost CmdForceTrainProceed ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)

Force a train through a red signal.

Parameters
tileunused
flagstype of operation
p1train to ignore the red signal
p2unused
textunused
Returns
the cost of this operation or an error

Definition at line 1987 of file train_cmd.cpp.

References CheckOwnership(), CMD_ERROR, DC_EXEC, CommandCost::Failed(), SpecializedVehicle< Train, Type >::GetIfValid(), HasBit(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, GroundVehicle< T, Type >::IsChainInDepot(), Train::IsPrimaryVehicle(), Vehicle::owner, SetWindowDirty(), TFP_NONE, TFP_SIGNAL, TFP_STUCK, VRF_TRAIN_STUCK, and WC_VEHICLE_VIEW.

◆ CmdMoveRailVehicle()

CommandCost CmdMoveRailVehicle ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)

Move a rail vehicle around inside the depot.

Parameters
tileunused
flagstype of operation Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
p1various bitstuffed elements
  • p1 (bit 0 - 19) source vehicle index
  • p1 (bit 20) move all vehicles following the source vehicle
p2what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
textunused
Returns
the cost of this operation or an error

Definition at line 1176 of file train_cmd.cpp.

References CheckOwnership(), CMD_ERROR, CommandCost::Failed(), GB(), SpecializedVehicle< Train, Type >::GetIfValid(), HasBit(), INVALID_VEHICLE, GroundVehicle< T, Type >::IsEngine(), Vehicle::owner, Vehicle::vehstatus, and VS_CRASHED.

◆ CmdReverseTrainDirection()

CommandCost CmdReverseTrainDirection ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)

Reverse train.

Parameters
tileunused
flagstype of operation
p1train to reverse
p2if true, reverse a unit in a train (needs to be in a depot)
textunused
Returns
the cost of this operation or an error

Definition at line 1914 of file train_cmd.cpp.

References CheckOwnership(), CMD_ERROR, CommandCost::Failed(), SpecializedVehicle< Train, Type >::GetIfValid(), HasBit(), GroundVehicle< T, Type >::IsMultiheaded(), and Vehicle::owner.

◆ CmdSellRailWagon()

CommandCost CmdSellRailWagon ( DoCommandFlag  flags,
Vehicle t,
uint16  data,
uint32  user 
)

Sell a (single) train wagon/engine.

Parameters
flagstype of operation
tthe train wagon to sell
datathe selling mode
  • data = 0: only sell the single dragged wagon/engine (and any belonging rear-engines)
  • data = 1: sell the vehicle and all vehicles following it in the chain if the wagon is dragged, don't delete the possibly belonging rear-engine to some front
userthe user for the order backup.
Returns
the cost of this operation or an error

Definition at line 1370 of file train_cmd.cpp.

References CommandCost::AddCost(), Vehicle::AddToShared(), ArrangeTrains(), OrderBackup::Backup(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_orderlist_pool >::CanAllocateItem(), Vehicle::CopyVehicleConfigAndStatistics(), GroupStatistics::CountVehicle(), DC_AUTOREPLACE, DC_EXEC, DeleteVehicleOrders(), EXPENSES_NEW_VEHICLES, CommandCost::Failed(), Vehicle::first, SpecializedVehicle< T, Type >::First(), SpecializedVehicle< Train, Type >::From(), SpecializedVehicle< T, Type >::GetFirstEnginePart(), HasBit(), InvalidateWindowClassesData(), InvalidateWindowData(), GroundVehicle< T, Type >::IsEngine(), Vehicle::IsFrontEngine(), Train::IsPrimaryVehicle(), GroundVehicle< T, Type >::IsRearDualheaded(), Vehicle::list, MAKE_ORDER_BACKUP_FLAG, MakeTrainBackup(), Vehicle::Next(), NormaliseSubtypes(), NormaliseTrainHead(), Vehicle::orders, RestoreTrainBackup(), return_cmd_error, Vehicle::tile, ValidateTrains(), Vehicle::value, WC_TRAINS_LIST, and WC_VEHICLE_DEPOT.

Referenced by CmdSellVehicle().

◆ CollectTrackbitsFromCrashedVehiclesEnum()

static Vehicle* CollectTrackbitsFromCrashedVehiclesEnum ( Vehicle v,
void *  data 
)
static

Collect trackbits of all crashed train vehicles on a tile.

Parameters
vVehicle passed from Find/HasVehicleOnPos()
datatrackdirbits for the result
Returns
NULL to iterate over all vehicles on the tile.

Definition at line 3434 of file train_cmd.cpp.

References DiagDirToDiagTrackBits(), SpecializedVehicle< Train, Type >::From(), GetTunnelBridgeDirection(), Vehicle::tile, TRACK_BIT_DEPOT, TRACK_BIT_WORMHOLE, BaseVehicle::type, VEH_TRAIN, Vehicle::vehstatus, and VS_CRASHED.

Referenced by DeleteLastWagon().

◆ DeleteLastWagon()

static void DeleteLastWagon ( Train v)
static

Deletes/Clears the last wagon of a crashed train.

It takes the engine of the train, then goes to the last wagon and deletes that. Each call to this function will remove the last wagon of a crashed train. If this wagon was on a crossing, or inside a tunnel/bridge, recalculate the signals as they might need updating

Parameters
vthe Vehicle of which last wagon is to be removed

Definition at line 3458 of file train_cmd.cpp.

References CCF_ARRANGE, CollectTrackbitsFromCrashedVehiclesEnum(), Train::ConsistChanged(), DiagDirToDiagTrackBits(), FindVehicleOnPos(), Vehicle::first, SpecializedVehicle< T, Type >::First(), GetTunnelBridgeDirection(), HasReservedTracks(), Vehicle::last_station_visited, SpecializedVehicle< T, Type >::Next(), Vehicle::owner, Vehicle::SetNext(), SetWindowDirty(), Vehicle::tile, TRACK_BIT_DEPOT, TRACK_BIT_NONE, TRACK_BIT_WORMHOLE, TrackBitsToTrack(), UnreserveRailTrack(), and WC_VEHICLE_DEPOT.

◆ DoTrainPathfind()

static Track DoTrainPathfind ( const Train v,
TileIndex  tile,
DiagDirection  enterdir,
TrackBits  tracks,
bool &  path_found,
bool  do_track_reservation,
PBSTileInfo dest 
)
static

Perform pathfinding for a train.

Parameters
vThe train
tileThe tile the train is about to enter
enterdirDiagonal direction the train is coming from
tracksUsable tracks on the new tile
path_found[out] Whether a path has been found or not.
do_track_reservationPath reservation is requested
dest[out] State and destination of the requested path
Returns
The best track the train should follow

Definition at line 2335 of file train_cmd.cpp.

References _settings_game, NPFTrainChooseTrack(), PathfinderSettings::pathfinder_for_trains, GameSettings::pf, VPF_NPF, VPF_YAPF, and YapfTrainChooseTrack().

◆ ExtendTrainReservation()

static PBSTileInfo ExtendTrainReservation ( const Train v,
TrackBits new_tracks,
DiagDirection enterdir 
)
static

Extend a train path as far as possible.

Stops on encountering a safe tile, another reservation or a track choice.

Returns
INVALID_TILE indicates that the reservation failed.

Definition at line 2350 of file train_cmd.cpp.

References _settings_game, FindFirstTrackdir(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::Follow(), FollowTrainReservation(), PathfinderSettings::forbid_90_deg, HasOnewaySignalBlockingTrackdir(), HasReservedTracks(), IsPlainRail(), IsSafeWaitingPosition(), IsTileType(), IsWaitingPositionFree(), KillFirstBit(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_exitdir, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_station, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_td_bits, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_new_tile, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_old_td, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_old_tile, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_tiles_skipped, MP_RAILWAY, GameSettings::pf, PBSTileInfo::tile, Vehicle::tile, TileOffsByDiagDir(), PBSTileInfo::trackdir, TRACKDIR_BIT_NONE, TrackdirBitsToTrackBits(), TrackdirCrossesTrackdirs(), TrackdirReachesTrackdirs(), TrackdirToTrack(), and TryReserveRailTrack().

◆ FindClosestTrainDepot()

static FindDepotData FindClosestTrainDepot ( Train v,
int  max_distance 
)
static

Try to find a depot nearby.

Parameters
vTrain that wants a depot.
max_distanceMaximal search distance.
Returns
Information where the closest train depot is located.
Precondition
The given vehicle must not be crashed!

Definition at line 2018 of file train_cmd.cpp.

Referenced by Train::FindClosestDepot().

◆ FindTrainCollideEnum()

static Vehicle* FindTrainCollideEnum ( Vehicle v,
void *  data 
)
static

◆ FreeTrainTrackReservation()

void FreeTrainTrackReservation ( const Train v)

Free the reserved path in front of a vehicle.

Parameters
vTrain owning the reserved path.

Definition at line 2258 of file train_cmd.cpp.

Referenced by CmdConvertRail(), Train::Crash(), FreeTrainReservation(), and ReverseTrainDirection().

◆ FreightWagonMult()

byte FreightWagonMult ( CargoID  cargo)

Return the cargo weight multiplier to use for a rail vehicle.

Parameters
cargoCargo type to get multiplier for
Returns
Cargo weight multiplier

Definition at line 87 of file train_cmd.cpp.

References _settings_game, VehicleSettings::freight_trains, CargoSpec::Get(), and GameSettings::vehicle.

Referenced by Train::GetWeight().

◆ GetTrainSpriteSize()

void GetTrainSpriteSize ( EngineID  engine,
uint &  width,
uint &  height,
int &  xoffs,
int &  yoffs,
EngineImageType  image_type 
)

Get the size of the sprite of a train sprite heading west, or both heads (used for lists).

Parameters
engineThe engine to get the sprite from.
[out]widthThe width of the sprite.
[out]heightThe height of the sprite.
[out]xoffsNumber of pixels to shift the sprite to the right.
[out]yoffsNumber of pixels to shift the sprite downwards.
image_typeContext the sprite is used in.

Definition at line 572 of file train_cmd.cpp.

◆ GetTrainStopLocation()

int GetTrainStopLocation ( StationID  station_id,
TileIndex  tile,
const Train v,
int *  station_ahead,
int *  station_length 
)

Get the stop location of (the center) of the front vehicle of a train at a platform of a station.

Parameters
station_idthe ID of the station where we're stopping
tilethe tile where the vehicle currently is
vthe vehicle to get the stop location of
station_ahead'return' the amount of 1/16th tiles in front of the train
station_length'return' the station length in 1/16th tiles
Returns
the location, calculated from the begin of the station to stop at.

Definition at line 279 of file train_cmd.cpp.

References GroundVehicleCache::cached_total_length, Vehicle::current_order, Vehicle::direction, DirToDiagDir(), GroundVehicle< T, Type >::gcache, SpecializedStation< Station, false >::Get(), Station::GetPlatformLength(), Order::IsType(), OSL_PLATFORM_FAR_END, OSL_PLATFORM_MIDDLE, and TILE_SIZE.

◆ HandleCrashedTrain()

static bool HandleCrashedTrain ( Train v)
static

Handle a crashed train.

Parameters
vFirst train vehicle.
Returns
Vehicle chain still exists.

Definition at line 3550 of file train_cmd.cpp.

References Chance16R(), Train::crash_anim_pos, CreateEffectVehicleRel(), EV_EXPLOSION_LARGE, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_vehicle_pool >::index, Vehicle::vehstatus, and VS_HIDDEN.

◆ InsertInConsist()

static void InsertInConsist ( Train dst,
Train chain 
)
static

Inserts a chain into the train at dst.

Parameters
dstthe place where to append after.
chainthe chain to actually add.

Definition at line 894 of file train_cmd.cpp.

Referenced by ArrangeTrains(), and NormaliseDualHeads().

◆ MakeTrainBackup()

static void MakeTrainBackup ( TrainList list,
Train t 
)
static

Make a backup of a train into a train list.

Parameters
listto make the backup in
tthe train to make the backup of

Definition at line 844 of file train_cmd.cpp.

References SmallVector< T, S >::Append(), and SpecializedVehicle< T, Type >::Next().

Referenced by CmdSellRailWagon().

◆ MarkTrainAsStuck()

static void MarkTrainAsStuck ( Train v)
static

◆ MaybeBarCrossingWithSound()

static void MaybeBarCrossingWithSound ( TileIndex  tile)
inlinestatic

Bars crossing and plays ding-ding sound if not barred already.

Parameters
tiletile with crossing
Precondition
tile is a rail-road crossing

Definition at line 1721 of file train_cmd.cpp.

References _settings_client, SoundSettings::ambient, BarCrossing(), IsCrossingBarred(), and ClientSettings::sound.

◆ NormaliseDualHeads()

static void NormaliseDualHeads ( Train t)
static

Normalise the dual heads in the train, i.e.

if one is missing move that one to this train.

Parameters
tthe train to normalise.

Definition at line 908 of file train_cmd.cpp.

References SpecializedVehicle< T, Type >::GetNextVehicle(), InsertInConsist(), GroundVehicle< T, Type >::IsEngine(), GroundVehicle< T, Type >::IsMultiheaded(), SpecializedVehicle< T, Type >::Next(), and RemoveFromConsist().

Referenced by ArrangeTrains().

◆ NormaliseSubtypes()

static void NormaliseSubtypes ( Train chain)
static

Normalise the sub types of the parts in this chain.

Parameters
chainthe chain to normalise.

Definition at line 930 of file train_cmd.cpp.

Referenced by CmdSellRailWagon().

◆ NormaliseTrainHead()

static void NormaliseTrainHead ( Train head)
static

Normalise the head of the train again, i.e.

that is tell the world that we have changed and update all kinds of variables.

Parameters
headthe train to update.

Definition at line 1143 of file train_cmd.cpp.

References CCF_ARRANGE, Train::ConsistChanged(), GetFreeUnitNumber(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, InvalidateWindowData(), Vehicle::IsFrontEngine(), SetWindowWidgetDirty(), Vehicle::unitnumber, UpdateTrainGroupID(), VEH_TRAIN, VIWD_CONSIST_CHANGED, WC_VEHICLE_REFIT, WC_VEHICLE_VIEW, and WID_VV_REFIT.

Referenced by CmdSellRailWagon().

◆ RemoveFromConsist()

static void RemoveFromConsist ( Train part,
bool  chain = false 
)
static

Remove the given wagon from its consist.

Parameters
partthe part of the train to remove.
chainwhether to remove the whole chain.

Definition at line 877 of file train_cmd.cpp.

References SpecializedVehicle< T, Type >::GetLastEnginePart(), SpecializedVehicle< T, Type >::Last(), SpecializedVehicle< T, Type >::Next(), SpecializedVehicle< T, Type >::Previous(), and Vehicle::SetNext().

Referenced by ArrangeTrains(), and NormaliseDualHeads().

◆ RestoreTrainBackup()

static void RestoreTrainBackup ( TrainList list)
static

Restore the train from the backup list.

Parameters
listthe train to restore.

Definition at line 853 of file train_cmd.cpp.

References SmallVector< T, S >::Begin(), SmallVector< T, S >::End(), SmallVector< T, S >::Length(), SpecializedVehicle< T, Type >::Previous(), and Vehicle::SetNext().

Referenced by CmdSellRailWagon().

◆ ReverseTrainDirection()

void ReverseTrainDirection ( Train v)

Turn a train around.

Parameters
vTrain to turn around.

Definition at line 1821 of file train_cmd.cpp.

References FreeTrainTrackReservation(), HasBit(), InvalidateWindowData(), IsRailDepotTile(), Vehicle::tile, TrainApproachingCrossingTile(), VRF_TRAIN_STUCK, and WC_VEHICLE_DEPOT.

◆ ReverseTrainSwapVeh()

void ReverseTrainSwapVeh ( Train v,
int  l,
int  r 
)

Swap vehicles l and r in consist v, and reverse their direction.

Parameters
vConsist to change.
lVehicle index in the consist of the first vehicle.
rVehicle index in the consist of the second vehicle.

Definition at line 1602 of file train_cmd.cpp.

References Vehicle::direction, GroundVehicle< T, Type >::gv_flags, SpecializedVehicle< T, Type >::Next(), Swap(), SwapTrainFlags(), Vehicle::tile, UpdateStatusAfterSwap(), Vehicle::vehstatus, VS_HIDDEN, Vehicle::x_pos, Vehicle::y_pos, and Vehicle::z_pos.

◆ SwapTrainFlags()

static void SwapTrainFlags ( uint16 *  swap_flag1,
uint16 *  swap_flag2 
)
static

Swap the two up/down flags in two ways:

  • Swap values of swap_flag1 and swap_flag2, and
  • If going up previously (GVF_GOINGUP_BIT set), the GVF_GOINGDOWN_BIT is set, and vice versa.
    Parameters
    swap_flag1[inout] First train flag.
    swap_flag2[inout] Second train flag.

Definition at line 1537 of file train_cmd.cpp.

References ClrBit(), GVF_GOINGDOWN_BIT, GVF_GOINGUP_BIT, HasBit(), and SetBit().

Referenced by ReverseTrainSwapVeh().

◆ TrainApproachingCrossing()

static bool TrainApproachingCrossing ( TileIndex  tile)
static

Finds a vehicle approaching rail-road crossing.

Parameters
tiletile to test
Returns
true if a vehicle is approaching the crossing
Precondition
tile is a rail-road crossing

Definition at line 1677 of file train_cmd.cpp.

◆ TrainApproachingCrossingEnum()

static Vehicle* TrainApproachingCrossingEnum ( Vehicle v,
void *  data 
)
static

Checks if a train is approaching a rail-road crossing.

Parameters
vvehicle on tile
datatile with crossing we are testing
Returns
v if it is approaching a crossing, NULL otherwise

Definition at line 1656 of file train_cmd.cpp.

References SpecializedVehicle< Train, Type >::From(), Vehicle::IsFrontEngine(), Vehicle::tile, TrainApproachingCrossingTile(), BaseVehicle::type, VEH_TRAIN, Vehicle::vehstatus, and VS_CRASHED.

◆ TrainApproachingCrossingTile()

static TileIndex TrainApproachingCrossingTile ( const Train v)
static

Determines whether train is approaching a rail-road crossing (thus making it barred)

Parameters
vfront engine of train
Returns
TileIndex of crossing the train is approaching, else INVALID_TILE
Precondition
v in non-crashed front engine

Definition at line 3677 of file train_cmd.cpp.

Referenced by Train::Crash(), ReverseTrainDirection(), and TrainApproachingCrossingEnum().

◆ TrainApproachingLineEnd()

static bool TrainApproachingLineEnd ( Train v,
bool  signal,
bool  reverse 
)
static

Train is approaching line end, slow down and possibly reverse.

Parameters
vfront train engine
signalnot line end, just a red signal
reverseSet to false to not execute the vehicle reversing. This does not change any other logic.
Returns
true iff we did NOT have to reverse

Definition at line 3602 of file train_cmd.cpp.

◆ TrainCanLeaveTile()

static bool TrainCanLeaveTile ( const Train v)
static

Determines whether train would like to leave the tile.

Parameters
vtrain to test
Returns
true iff vehicle is NOT entering or inside a depot or tunnel/bridge

Definition at line 3647 of file train_cmd.cpp.

References DiagDirToDir(), Vehicle::direction, GetRailDepotDirection(), GetTunnelBridgeDirection(), IsRailDepotTile(), IsTileType(), MP_TUNNELBRIDGE, ReverseDiagDir(), Vehicle::tile, TRACK_BIT_DEPOT, and TRACK_BIT_WORMHOLE.

Referenced by TrainCheckIfLineEnds().

◆ TrainCheckIfLineEnds()

static bool TrainCheckIfLineEnds ( Train v,
bool  reverse 
)
static

Checks for line end.

Also, bars crossing at next tile if needed

Parameters
vvehicle we are checking
reverseSet to false to not execute the vehicle reversing. This does not change any other logic.
Returns
true iff we did NOT have to reverse

Definition at line 3704 of file train_cmd.cpp.

References _breakdown_speeds, _settings_game, Vehicle::breakdown_ctr, Vehicle::cur_speed, DiagdirReachesTrackdirs(), Vehicle::direction, FindFirstTrack(), PathfinderSettings::forbid_90_deg, GB(), GetTileTrackStatus(), GameSettings::pf, ReverseDiagDir(), Vehicle::tile, TileOffsByDiagDir(), TRACK_BIT_NONE, TrackCrossesTracks(), TrackdirBitsToTrackBits(), TrackStatusToRedSignals(), TrackStatusToTrackdirBits(), TrainCanLeaveTile(), TrainExitDir(), TRANSPORT_RAIL, Vehicle::vehstatus, and VS_TRAIN_SLOWING.

Referenced by TrainController().

◆ TrainController()

bool TrainController ( Train v,
Vehicle nomove,
bool  reverse 
)

Move a vehicle chain one movement stop forwards.

Parameters
vFirst vehicle to move.
nomoveStop moving this and all following vehicles.
reverseSet to false to not execute the vehicle reversing. This does not change any other logic.
Returns
True if the vehicle could be moved forward, false otherwise.

Definition at line 3113 of file train_cmd.cpp.

References DIAGDIR_BEGIN, DiagdirBetweenTiles(), Vehicle::first, SpecializedVehicle< T, Type >::First(), GetNewVehiclePos(), HasBit(), GetNewVehiclePosResult::new_tile, SpecializedVehicle< T, Type >::Next(), GetNewVehiclePosResult::old_tile, SpecializedVehicle< T, Type >::Previous(), TRACK_BIT_DEPOT, TRACK_BIT_WORMHOLE, TrainCheckIfLineEnds(), TrainEnterStation(), VehicleEnterTile(), VETS_CANNOT_ENTER, VETS_ENTERED_STATION, VETS_STATION_ID_OFFSET, and GetNewVehiclePosResult::y.

Referenced by AdvanceWagonsAfterSwap(), and FixupTrainLengths().

◆ TrainCrashed()

static uint TrainCrashed ( Train v)
static

Marks train as crashed and creates an AI event.

Doesn't do anything if the train is crashed already.

Parameters
vfirst vehicle of chain
Returns
number of victims (including 2 drivers; zero if train was already crashed)

Definition at line 2984 of file train_cmd.cpp.

References Train::Crash(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, Game::NewEvent(), AI::NewEvent(), Vehicle::owner, Train::ReserveTrackUnderConsist(), Vehicle::tile, Vehicle::vehstatus, and VS_CRASHED.

Referenced by FindTrainCollideEnum().

◆ TrainEnterStation()

static void TrainEnterStation ( Train v,
StationID  station 
)
static

◆ TrainExitDir()

static DiagDirection TrainExitDir ( Direction  direction,
TrackBits  track 
)
inlinestatic

Determine the side in which the train will leave the tile.

Parameters
directionvehicle direction
trackvehicle track bits
Returns
side of tile the train will leave

Definition at line 67 of file train_cmd.cpp.

References ChangeDiagDir(), DIAGDIR_END, DIAGDIRDIFF_90LEFT, DirToDiagDir(), HasBit(), TRACK_BIT_LEFT, TRACK_BIT_LOWER, TRACK_BIT_RIGHT, and TRACK_BIT_UPPER.

Referenced by TrainCheckIfLineEnds().

◆ TrainOnTileEnum()

static Vehicle* TrainOnTileEnum ( Vehicle v,
void *   
)
static

Check if the vehicle is a train.

Parameters
vvehicle on tile
Returns
v if it is a train, NULL otherwise

Definition at line 1644 of file train_cmd.cpp.

References BaseVehicle::type, and VEH_TRAIN.

◆ TryPathReserve()

bool TryPathReserve ( Train v,
bool  mark_as_stuck,
bool  first_tile_okay 
)

Try to reserve a path to a safe position.

Parameters
vThe vehicle
mark_as_stuckShould the train be marked as stuck on a failed reservation?
first_tile_okayTrue if no path should be reserved if the current tile is a safe position.
Returns
True if a path could be reserved.

Definition at line 2696 of file train_cmd.cpp.

Referenced by CmdConvertRail(), and RestoreTrainReservation().

◆ TryReserveSafeTrack()

static bool TryReserveSafeTrack ( const Train v,
TileIndex  tile,
Trackdir  td,
bool  override_tailtype 
)
static

Try to reserve any path to a safe tile, ignoring the vehicle's destination.

Safe tiles are tiles in front of a signal, depots and station tiles at end of line.

Parameters
vThe vehicle.
tileThe tile the search should start from.
tdThe trackdir the search should start from.
override_railtypeWhether all physically compatible railtypes should be followed.
Returns
True if a path to a safe stopping tile could be reserved.

Definition at line 2442 of file train_cmd.cpp.

References _settings_game, NPFTrainFindNearestSafeTile(), PathfinderSettings::pathfinder_for_trains, GameSettings::pf, VPF_NPF, VPF_YAPF, and YapfTrainFindNearestSafeTile().

◆ UpdateLevelCrossing()

void UpdateLevelCrossing ( TileIndex  tile,
bool  sound 
)

Sets correct crossing state.

Parameters
tiletile to update
soundshould we play sound?
Precondition
tile is a rail-road crossing

Definition at line 1699 of file train_cmd.cpp.

Referenced by Train::Crash().

◆ UpdateStatusAfterSwap()

static void UpdateStatusAfterSwap ( Train v)
static

◆ ValidateTrains()

static CommandCost ValidateTrains ( Train original_dst,
Train dst,
Train original_src,
Train src,
bool  check_limit 
)
static

Validate whether we are going to create valid trains.

Note
All vehicles are/were 'heads' of their chains.
Parameters
original_dstThe original destination chain.
dstThe destination chain after constructing the train.
original_dstThe original source chain.
dstThe source chain after constructing the train.
check_limitWhether to check the vehicle limit.
Returns
possible error of this command.

Definition at line 1082 of file train_cmd.cpp.

References CheckNewTrain(), CheckTrainAttachment(), and CommandCost::Failed().

Referenced by CmdSellRailWagon().

Variable Documentation

◆ _accel_slowdown

const AccelerationSlowdownParams _accel_slowdown[]
static
Initial value:
= {
{256 / 4, 256 / 2, 256 / 4, 2},
{256 / 4, 256 / 2, 256 / 4, 2},
{0, 256 / 2, 256 / 4, 2},
}

Speed update fractions for each acceleration type.

Definition at line 2882 of file train_cmd.cpp.

◆ _breakdown_speeds

const uint16 _breakdown_speeds[16]
static
Initial value:
= {
225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
}

Maximum speeds for train that is broken down or approaching line end.

Definition at line 3589 of file train_cmd.cpp.

Referenced by TrainCheckIfLineEnds().

◆ _initial_tile_subcoord

const byte _initial_tile_subcoord[6][4][3]
static
Initial value:
= {
{{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
{{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
{{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
{{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
{{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
{{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
}

Definition at line 2314 of file train_cmd.cpp.