OpenTTD Source 20241224-master-gf74b0cf984
train_cmd.cpp File Reference

Handling of trains. More...

#include "stdafx.h"
#include "error.h"
#include "articulated_vehicles.h"
#include "command_func.h"
#include "error_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 "framerate_type.h"
#include "train_cmd.h"
#include "misc_cmd.h"
#include "timer/timer_game_calendar.h"
#include "timer/timer_game_economy.h"
#include "table/strings.h"
#include "table/train_sprites.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 std::vector< Train * > 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.
 
bool TrainController (Train *v, Vehicle *nomove, bool reverse)
 Move a vehicle chain one movement stop forwards.
 
static TileIndex TrainApproachingCrossingTile (const Train *v)
 Determines whether train is approaching a rail-road crossing (thus making it barred)
 
static void CheckIfTrainNeedsService (Train *v)
 Check whether a train needs service, and if so, find a depot or service it.
 
static void CheckNextTrainTile (Train *v)
 Check if the train is on the last reserved tile and try to extend the path then.
 
template<>
bool IsValidImageIndex< VEH_TRAIN > (uint8_t image_index)
 
uint8_t FreightWagonMult (CargoID cargo)
 Return the cargo weight multiplier to use for a rail vehicle.
 
void CheckTrainsLengths ()
 Checks if lengths of all rail vehicles are valid.
 
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.
 
static SpriteID GetDefaultTrainSprite (uint8_t 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).
 
static CommandCost CmdBuildRailWagon (DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
 Build a railroad wagon.
 
void NormalizeTrainVehInDepot (const Train *u)
 Move all free vehicles in the depot to the train.
 
static void AddRearEngineToMultiheadedTrain (Train *v)
 
CommandCost CmdBuildRailVehicle (DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
 Build a railroad vehicle.
 
static TrainFindGoodVehiclePos (const Train *src)
 
static void MakeTrainBackup (TrainList &list, Train *t)
 Make a backup of a train into a train list.
 
static void RestoreTrainBackup (TrainList &list)
 Restore the train from the backup list.
 
static void RemoveFromConsist (Train *part, bool chain=false)
 Remove the given wagon from its consist.
 
static void InsertInConsist (Train *dst, Train *chain)
 Inserts a chain into the train at dst.
 
static void NormaliseDualHeads (Train *t)
 Normalise the dual heads in the train, i.e.
 
static void NormaliseSubtypes (Train *chain)
 Normalise the sub types of the parts in this chain.
 
static CommandCost CheckNewTrain (Train *original_dst, Train *dst, Train *original_src, Train *src)
 Check/validate whether we may actually build a new train.
 
static CommandCost CheckTrainAttachment (Train *t)
 Check whether the train parts can be attached.
 
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.
 
static void ArrangeTrains (Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
 Arrange the trains in the wanted way.
 
static void NormaliseTrainHead (Train *head)
 Normalise the head of the train again, i.e.
 
CommandCost CmdMoveRailVehicle (DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
 Move a rail vehicle around inside the depot.
 
CommandCost CmdSellRailWagon (DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
 Sell a (single) train wagon/engine.
 
static void MarkTrainAsStuck (Train *v)
 Mark a train as stuck and stop it if it isn't stopped right now.
 
static void SwapTrainFlags (uint16_t *swap_flag1, uint16_t *swap_flag2)
 Swap the two up/down flags in two ways:
 
static void UpdateStatusAfterSwap (Train *v)
 Updates some variables after swapping the vehicle.
 
void ReverseTrainSwapVeh (Train *v, int l, int r)
 Swap vehicles l and r in consist v, and reverse their direction.
 
static VehicleTrainOnTileEnum (Vehicle *v, void *)
 Check if the vehicle is a train.
 
bool TrainOnCrossing (TileIndex tile)
 Check if a level crossing tile has a train on it.
 
static VehicleTrainApproachingCrossingEnum (Vehicle *v, void *data)
 Checks if a train is approaching a rail-road crossing.
 
static bool TrainApproachingCrossing (TileIndex tile)
 Finds a vehicle approaching rail-road crossing.
 
static bool CheckLevelCrossing (TileIndex tile)
 Check if a level crossing should be barred.
 
static void UpdateLevelCrossingTile (TileIndex tile, bool sound, bool force_barred)
 Sets a level crossing tile to the correct state.
 
void UpdateLevelCrossing (TileIndex tile, bool sound, bool force_bar)
 Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
 
void MarkDirtyAdjacentLevelCrossingTiles (TileIndex tile, Axis road_axis)
 Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.
 
void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval (TileIndex tile, Axis road_axis)
 Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing tile.
 
static void MaybeBarCrossingWithSound (TileIndex tile)
 Bars crossing and plays ding-ding sound if not barred already.
 
static void AdvanceWagonsBeforeSwap (Train *v)
 Advances wagons for train reversing, needed for variable length wagons.
 
static void AdvanceWagonsAfterSwap (Train *v)
 Advances wagons for train reversing, needed for variable length wagons.
 
static bool IsWholeTrainInsideDepot (const Train *v)
 
void ReverseTrainDirection (Train *v)
 Turn a train around.
 
CommandCost CmdReverseTrainDirection (DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
 Reverse train.
 
CommandCost CmdForceTrainProceed (DoCommandFlag flags, VehicleID veh_id)
 Force a train through a red signal.
 
static FindDepotData FindClosestTrainDepot (Train *v, int max_distance)
 Try to find a depot nearby.
 
static bool CheckTrainStayInDepot (Train *v)
 Will the train stay in the depot the next tick?
 
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.
 
void FreeTrainTrackReservation (const Train *v)
 Free the reserved path in front of a vehicle.
 
static Track DoTrainPathfind (const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
 Perform pathfinding for a train.
 
static PBSTileInfo ExtendTrainReservation (const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
 Extend a train path as far as possible.
 
static bool TryReserveSafeTrack (const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
 Try to reserve any path to a safe tile, ignoring the vehicle's destination.
 
bool TryPathReserve (Train *v, bool mark_as_stuck, bool first_tile_okay)
 Try to reserve a path to a safe position.
 
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.
 
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.
 
static bool TrainMovedChangeSignals (TileIndex tile, DiagDirection dir)
 
static uint TrainCrashed (Train *v)
 Marks train as crashed and creates an AI event.
 
static VehicleFindTrainCollideEnum (Vehicle *v, void *data)
 Collision test function.
 
static bool CheckTrainCollision (Train *v)
 Checks whether the specified train has a collision with another vehicle.
 
static VehicleCheckTrainAtSignal (Vehicle *v, void *data)
 
static VehicleCollectTrackbitsFromCrashedVehiclesEnum (Vehicle *v, void *data)
 Collect trackbits of all crashed train vehicles on a tile.
 
static bool IsRailStationPlatformOccupied (TileIndex tile)
 
static void DeleteLastWagon (Train *v)
 Deletes/Clears the last wagon of a crashed train.
 
static void ChangeTrainDirRandomly (Train *v)
 Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
 
static bool HandleCrashedTrain (Train *v)
 Handle a crashed train.
 
static bool TrainApproachingLineEnd (Train *v, bool signal, bool reverse)
 Train is approaching line end, slow down and possibly reverse.
 
static bool TrainCanLeaveTile (const Train *v)
 Determines whether train would like to leave the tile.
 
static bool TrainLocoHandler (Train *v, bool mode)
 

Variables

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

Detailed Description

Handling of trains.

Definition in file train_cmd.cpp.

Typedef Documentation

◆ TrainList

typedef std::vector<Train *> TrainList

Helper type for lists/vectors of trains.

Definition at line 845 of file train_cmd.cpp.

Function Documentation

◆ AddRearEngineToMultiheadedTrain()

static void AddRearEngineToMultiheadedTrain ( Train v)
static

Definition at line 706 of file train_cmd.cpp.

◆ 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 1902 of file train_cmd.cpp.

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

Referenced by ReverseTrainDirection().

◆ 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 1874 of file train_cmd.cpp.

References Train::CalcNextVehicleOffset(), SpecializedVehicle< T, Type >::Last(), SpecializedVehicle< T, Type >::Next(), SpecializedVehicle< T, Type >::Previous(), and TrainController().

Referenced by ReverseTrainDirection().

◆ 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 3059 of file train_cmd.cpp.

References _accel_slowdown, _settings_game, RailTypeInfo::acceleration_type, Vehicle::cur_speed, GetRailTypeInfo(), VehicleSettings::train_acceleration_model, GameSettings::vehicle, AccelerationSlowdownParams::z_down, Vehicle::z_pos, and AccelerationSlowdownParams::z_up.

Referenced by TrainController().

◆ 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 1122 of file train_cmd.cpp.

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

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().

◆ ChangeTrainDirRandomly()

static void ChangeTrainDirRandomly ( Train v)
static

◆ CheckCompatibleRail()

static bool CheckCompatibleRail ( const Train v,
TileIndex  tile 
)
inlinestatic

Definition at line 3032 of file train_cmd.cpp.

◆ CheckIfTrainNeedsService()

◆ CheckLevelCrossing()

static bool CheckLevelCrossing ( TileIndex  tile)
inlinestatic

Check if a level crossing should be barred.

Parameters
tileThe tile to check.
Returns
True if the crossing should be barred, else false.

Definition at line 1738 of file train_cmd.cpp.

References HasCrossingReservation(), TrainApproachingCrossing(), and TrainOnCrossing().

Referenced by UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(), UpdateLevelCrossing(), and UpdateLevelCrossingTile().

◆ 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_srcThe original source chain.
srcThe source chain after constructing the train.
Returns
possible error of this command.

Definition at line 969 of file train_cmd.cpp.

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

Referenced by ValidateTrains().

◆ CheckNextTrainTile()

static void CheckNextTrainTile ( Train v)
static

◆ CheckReverseTrain()

static bool CheckReverseTrain ( const Train v)
static

Definition at line 2933 of file train_cmd.cpp.

◆ CheckTrainAtSignal()

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

Definition at line 3256 of file train_cmd.cpp.

◆ CheckTrainAttachment()

◆ 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 3226 of file train_cmd.cpp.

References _settings_client, SoundSettings::disaster, FindTrainCollideEnum(), FindVehicleOnPos(), FindVehicleOnPosXY(), GetOtherTunnelBridgeEnd(), NT_ACCIDENT, TrainCollideChecker::num, Vehicle::owner, SetDParam(), SND_13_TRAIN_COLLISION, ClientSettings::sound, Vehicle::tile, TileVirtXY(), TRACK_BIT_DEPOT, TRACK_BIT_WORMHOLE, TrainCollideChecker::v, Vehicle::x_pos, and Vehicle::y_pos.

◆ CheckTrainsLengths()

void CheckTrainsLengths ( )

◆ CheckTrainStayInDepot()

◆ ChooseTrainTrack()

static Track ChooseTrainTrack ( Train v,
TileIndex  tile,
DiagDirection  enterdir,
TrackBits  tracks,
bool  force_res,
bool *  got_reservation,
bool  mark_stuck 
)
static

Definition at line 2694 of file train_cmd.cpp.

◆ ClearPathReservation()

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

◆ CmdBuildRailVehicle()

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

Build a railroad vehicle.

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

Definition at line 750 of file train_cmd.cpp.

References _current_company, AddArticulatedParts(), Vehicle::build_year, RailVehicleInfo::capacity, Vehicle::cargo_cap, Vehicle::cargo_type, CCF_ARRANGE, CheckConsistencyOfArticulatedVehicle(), CMD_ERROR, CmdBuildRailWagon(), Train::ConsistChanged(), TimerGameCalendar::date, TimerGameEconomy::date, Vehicle::date_of_last_service, Vehicle::date_of_last_service_newgrf, DC_EXEC, DEFAULT_GROUP, DiagDirToDir(), Vehicle::direction, ENGINE_EXCLUSIVE_PREVIEW, Vehicle::engine_type, GroundVehicleCache::first_engine, Engine::flags, GroundVehicle< T, Type >::gcache, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_company_pool >::Get(), Engine::GetDefaultCargoType(), Engine::GetLifeLengthInDays(), GetRailDepotDirection(), GetRailType(), GetSlopePixelZ(), Vehicle::group_id, HasPowerOnRail(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, INVALID_ENGINE, IsValidCargoID(), Vehicle::last_loading_station, Vehicle::last_station_visited, Vehicle::max_age, Vehicle::owner, RailVehicleInfo::railtype, RAILVEH_MULTIHEAD, RAILVEH_WAGON, Vehicle::random_bits, Vehicle::refit_cap, Engine::reliability, Vehicle::reliability, Engine::reliability_spd_dec, Vehicle::reliability_spd_dec, VehicleSpriteSeq::Set(), SetBit(), GroundVehicle< T, Type >::SetEngine(), GroundVehicle< T, Type >::SetFrontEngine(), settings, Vehicle::sprite_cache, MutableSpriteCache::sprite_seq, Vehicle::spritenum, TestVehicleBuildProbability(), Vehicle::tile, TILE_SIZE, TileX(), TileY(), TRACK_BIT_DEPOT, Vehicle::UpdatePosition(), UpdateTrainGroupID(), BaseConsist::vehicle_flags, Vehicle::vehstatus, VF_BUILT_AS_PROTOTYPE, VRF_REVERSE_DIRECTION, VS_DEFPAL, VS_HIDDEN, VS_STOPPED, Vehicle::x_pos, Vehicle::y_pos, TimerGameCalendar::year, and Vehicle::z_pos.

Referenced by CmdBuildVehicle().

◆ CmdBuildRailWagon()

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

Build a railroad wagon.

Parameters
flagstype of operation.
tiletile of the depot where rail-vehicle is built.
ethe engine to build.
[out]retthe 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 616 of file train_cmd.cpp.

References _current_company, AddArticulatedParts(), Vehicle::build_year, RailVehicleInfo::capacity, Vehicle::cargo_cap, Vehicle::cargo_type, CCF_ARRANGE, CheckConsistencyOfArticulatedVehicle(), CMD_ERROR, TimerGameCalendar::date, TimerGameEconomy::date, Vehicle::date_of_last_service, Vehicle::date_of_last_service_newgrf, DC_EXEC, DEFAULT_GROUP, DiagDirToDir(), Vehicle::direction, Vehicle::engine_type, SpecializedVehicle< T, Type >::First(), GroundVehicleCache::first_engine, GroundVehicle< T, Type >::gcache, Engine::GetDefaultCargoType(), GetRailDepotDirection(), GetRailType(), GetSlopePixelZ(), Vehicle::group_id, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, INVALID_ENGINE, InvalidateWindowData(), IsCompatibleRail(), IsValidCargoID(), SpecializedVehicle< T, Type >::Iterate(), Vehicle::owner, RailVehicleInfo::railtype, Vehicle::random_bits, Vehicle::refit_cap, VehicleSpriteSeq::Set(), SetBit(), GroundVehicle< T, Type >::SetFreeWagon(), GroundVehicle< T, Type >::SetWagon(), Vehicle::sprite_cache, MutableSpriteCache::sprite_seq, Vehicle::spritenum, TestVehicleBuildProbability(), Vehicle::tile, TILE_SIZE, TileX(), TileY(), TRACK_BIT_DEPOT, Vehicle::UpdatePosition(), UpdateTrainGroupID(), Vehicle::vehstatus, VRF_REVERSE_DIRECTION, VS_CRASHED, VS_DEFPAL, VS_HIDDEN, WC_VEHICLE_DEPOT, Vehicle::x_pos, Vehicle::y_pos, TimerGameCalendar::year, and Vehicle::z_pos.

Referenced by CmdBuildRailVehicle().

◆ CmdForceTrainProceed()

◆ CmdMoveRailVehicle()

CommandCost CmdMoveRailVehicle ( DoCommandFlag  flags,
VehicleID  src_veh,
VehicleID  dest_veh,
bool  move_chain 
)

Move a rail vehicle around inside the depot.

Parameters
flagstype of operation Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
src_vehsource vehicle index
dest_vehwhat wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
move_chainmove all vehicles following the source vehicle
Returns
the cost of this operation or an error

Definition at line 1193 of file train_cmd.cpp.

References _current_company, Vehicle::AddToShared(), ArrangeTrains(), CheckCargoCapacity(), CheckOwnership(), CloseWindowById(), CMD_ERROR, Vehicle::CopyVehicleConfigAndStatistics(), GroupStatistics::CountVehicle(), DC_AUTOREPLACE, DC_EXEC, DC_NO_CARGO_CAP_CHECK, DEFAULT_GROUP, DeleteNewGRFInspectWindow(), DeleteVehicleOrders(), CommandCost::Failed(), SpecializedVehicle< T, Type >::First(), SpecializedVehicle< T, Type >::GetFirstEnginePart(), SpecializedVehicle< T, Type >::GetIfValid(), SpecializedVehicle< T, Type >::GetLastEnginePart(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, INVALID_VEHICLE, InvalidateWindowClassesData(), InvalidateWindowData(), GroundVehicle< T, Type >::IsEngine(), Vehicle::IsFrontEngine(), GroundVehicle< T, Type >::IsRearDualheaded(), Vehicle::IsStoppedInDepot(), MakeTrainBackup(), BaseConsist::name, NormaliseSubtypes(), NormaliseTrainHead(), Vehicle::orders, Vehicle::owner, Vehicle::ReleaseUnitNumber(), RestoreTrainBackup(), SetTrainGroupID(), SetWindowDirty(), Vehicle::tile, ValidateTrains(), Vehicle::vehstatus, VS_CRASHED, WC_COMPANY, WC_TRAINS_LIST, WC_VEHICLE_DEPOT, WC_VEHICLE_DETAILS, WC_VEHICLE_ORDERS, WC_VEHICLE_REFIT, WC_VEHICLE_TIMETABLE, and WC_VEHICLE_VIEW.

◆ CmdReverseTrainDirection()

◆ CmdSellRailWagon()

CommandCost CmdSellRailWagon ( DoCommandFlag  flags,
Vehicle t,
bool  sell_chain,
bool  backup_order,
ClientID  user 
)

Sell a (single) train wagon/engine.

Parameters
flagstype of operation
tthe train wagon to sell
sell_chainthe selling mode
  • sell_chain = false: only sell the single dragged wagon/engine (and any belonging rear-engines)
  • sell_chain = true: 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
backup_ordermake order backup?
userthe user for the order backup.
Returns
the cost of this operation or an error

Definition at line 1391 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(), SpecializedVehicle< T, Type >::First(), SpecializedVehicle< T, Type >::From(), SpecializedVehicle< T, Type >::GetFirstEnginePart(), InvalidateWindowClassesData(), InvalidateWindowData(), GroundVehicle< T, Type >::IsEngine(), Vehicle::IsFrontEngine(), Train::IsPrimaryVehicle(), GroundVehicle< T, Type >::IsRearDualheaded(), MakeTrainBackup(), SpecializedVehicle< T, Type >::Next(), NormaliseSubtypes(), NormaliseTrainHead(), Vehicle::orders, RestoreTrainBackup(), Vehicle::tile, ValidateTrains(), 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
nullptr to iterate over all vehicles on the tile.

Definition at line 3599 of file train_cmd.cpp.

References DiagDirToDiagTrackBits(), SpecializedVehicle< T, 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

◆ DoTrainPathfind()

static Track DoTrainPathfind ( const Train v,
TileIndex  tile,
DiagDirection  enterdir,
TrackBits  tracks,
bool &  path_found,
bool  do_track_reservation,
PBSTileInfo dest,
TileIndex final_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
[out]path_foundWhether a path has been found or not.
do_track_reservationPath reservation is requested
[out]destState and destination of the requested path
[out]final_destFinal tile of the best path found
Returns
The best track the train should follow

Definition at line 2469 of file train_cmd.cpp.

References INVALID_TILE, and YapfTrainChooseTrack().

◆ DrawTrainEngine()

void DrawTrainEngine ( int  left,
int  right,
int  preferred_x,
int  y,
EngineID  engine,
PaletteID  pal,
EngineImageType  image_type 
)

Definition at line 538 of file train_cmd.cpp.

◆ 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 2480 of file train_cmd.cpp.

References _settings_game, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::exitdir, FindFirstTrackdir(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::Follow(), FollowTrainReservation(), PathfinderSettings::forbid_90_deg, GetSignalStateByTrackdir(), GetTileRailType(), HasOnewaySignalBlockingTrackdir(), HasPbsSignalOnTrackdir(), HasReservedTracks(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::is_station, IsPlainRail(), IsSafeWaitingPosition(), IsTileType(), IsWaitingPositionFree(), KillFirstBit(), MarkTileDirtyByTile(), MP_RAILWAY, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::new_td_bits, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::new_tile, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::old_td, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::old_tile, GameSettings::pf, Rail90DegTurnDisallowed(), ReverseTrackdir(), SetSignalStateByTrackdir(), SIGNAL_STATE_GREEN, SIGNAL_STATE_RED, PBSTileInfo::tile, TileOffsByDiagDir(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::tiles_skipped, PBSTileInfo::trackdir, TRACKDIR_BIT_NONE, TrackdirBitsToTrackBits(), TrackdirReachesTrackdirs(), TrackdirToTrack(), TryReserveRailTrack(), and UnreserveRailTrack().

◆ 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 2166 of file train_cmd.cpp.

References Vehicle::vehstatus, VS_CRASHED, and YapfTrainFindNearestDepot().

Referenced by CheckIfTrainNeedsService(), and Train::FindClosestDepot().

◆ FindGoodVehiclePos()

static Train * FindGoodVehiclePos ( const Train src)
static

Definition at line 825 of file train_cmd.cpp.

◆ FindTrainCollideEnum()

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

Collision test function.

Parameters
vTrain vehicle to test collision with.
dataTrain being examined.
Returns
nullptr (always continue search)

Definition at line 3179 of file train_cmd.cpp.

References abs(), GroundVehicleCache::cached_veh_length, SpecializedVehicle< T, Type >::First(), SpecializedVehicle< T, Type >::From(), GroundVehicle< T, Type >::gcache, TrainCollideChecker::num, Vehicle::owner, TRACK_BIT_DEPOT, TrainCrashed(), BaseVehicle::type, TrainCollideChecker::v, VEH_TRAIN, Vehicle::x_pos, Vehicle::y_pos, and Vehicle::z_pos.

Referenced by CheckTrainCollision().

◆ FreeTrainTrackReservation()

void FreeTrainTrackReservation ( const Train v)

Free the reserved path in front of a vehicle.

Parameters
vTrain owning the reserved path.

Definition at line 2386 of file train_cmd.cpp.

References AddSideToSignalBuffer(), ClearPathReservation(), RailTypeInfo::compatible_railtypes, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::Follow(), GetRailDepotDirection(), GetRailTypeInfo(), GetReservedTrackbits(), GetSignalStateByTrackdir(), GetStationIndex(), Train::GetVehicleTrackdir(), HasPbsSignalOnTrackdir(), HasSignalOnTrackdir(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::is_bridge, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::is_station, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::is_tunnel, Vehicle::IsFrontEngine(), IsOnewaySignal(), IsRailDepotTile(), IsRailStationTile(), IsTileType(), IsValidTrackdir(), MarkTileDirtyByTile(), MP_RAILWAY, MP_TUNNELBRIDGE, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::new_td_bits, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::new_tile, SpecializedVehicle< T, Type >::Next(), Vehicle::owner, RemoveFirstTrackdir(), ReverseTrackdir(), SetSignalStateByTrackdir(), SIGNAL_STATE_RED, Vehicle::tile, TRACK_BIT_DEPOT, TrackBitsToTrackdirBits(), TRACKDIR_BIT_NONE, TrackdirToExitdir(), TrackdirToTrack(), TracksOverlap(), TrackToTrackBits(), UnreserveRailTrack(), and UpdateSignalsInBuffer().

Referenced by CmdBuildSingleSignal(), CmdConvertRail(), CmdRemoveSingleRail(), Train::Crash(), DoClearBridge(), DoClearTunnel(), FreeTrainReservation(), and ReverseTrainDirection().

◆ FreightWagonMult()

uint8_t 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 69 of file train_cmd.cpp.

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

Referenced by DrawTrainDetails(), TrainDetailsCapacityTab(), and TrainDetailsCargoTab().

◆ GetDefaultTrainSprite()

static SpriteID GetDefaultTrainSprite ( uint8_t  spritenum,
Direction  direction 
)
static

Definition at line 482 of file train_cmd.cpp.

◆ GetRailIcon()

static void GetRailIcon ( EngineID  engine,
bool  rear_head,
int &  y,
EngineImageType  image_type,
VehicleSpriteSeq result 
)
static

Definition at line 515 of file train_cmd.cpp.

◆ 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 581 of file train_cmd.cpp.

References VehicleSpriteSeq::GetBounds(), Rect::Height(), RAILVEH_MULTIHEAD, ScaleSpriteTrad(), UnScaleGUI(), and Rect::Width().

Referenced by EnginePreviewWindow::UpdateWidgetSize().

◆ 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 263 of file train_cmd.cpp.

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

Referenced by Train::GetCurrentMaxSpeed().

◆ HandleCrashedTrain()

static bool HandleCrashedTrain ( Train v)
static

◆ 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 901 of file train_cmd.cpp.

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

Referenced by ArrangeTrains(), and NormaliseDualHeads().

◆ IsRailStationPlatformOccupied()

static bool IsRailStationPlatformOccupied ( TileIndex  tile)
static

Definition at line 3616 of file train_cmd.cpp.

◆ IsValidImageIndex< VEH_TRAIN >()

template<>
bool IsValidImageIndex< VEH_TRAIN > ( uint8_t  image_index)

Definition at line 58 of file train_cmd.cpp.

◆ IsWholeTrainInsideDepot()

static bool IsWholeTrainInsideDepot ( const Train v)
static

Definition at line 1955 of file train_cmd.cpp.

◆ 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 852 of file train_cmd.cpp.

References SpecializedVehicle< T, Type >::Next().

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().

◆ MarkDirtyAdjacentLevelCrossingTiles()

void MarkDirtyAdjacentLevelCrossingTiles ( TileIndex  tile,
Axis  road_axis 
)

Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.

Parameters
tileThe tile which causes the update.
road_axisThe road axis.

Definition at line 1805 of file train_cmd.cpp.

References AxisToDiagDir(), GetCrossingRoadAxis(), IsLevelCrossingTile(), MarkTileDirtyByTile(), ReverseDiagDir(), Map::Size(), and TileAddByDiagDir().

Referenced by CmdBuildRoad(), and CmdBuildSingleRail().

◆ MarkTrainAsStuck()

◆ 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 1860 of file train_cmd.cpp.

References IsCrossingBarred(), SetCrossingReservation(), and UpdateLevelCrossing().

Referenced by ReverseTrainDirection(), and TrainCheckIfLineEnds().

◆ 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 915 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()

◆ NormaliseTrainHead()

◆ NormalizeTrainVehInDepot()

void NormalizeTrainVehInDepot ( const Train u)

◆ 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 884 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 861 of file train_cmd.cpp.

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

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().

◆ ReverseTrainDirection()

◆ 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 1630 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.

Referenced by FixupTrainLengths(), and ReverseTrainDirection().

◆ SwapTrainFlags()

static void SwapTrainFlags ( uint16_t *  swap_flag1,
uint16_t *  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
    [in,out]swap_flag1First train flag.
    [in,out]swap_flag2Second train flag.

Definition at line 1565 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 1718 of file train_cmd.cpp.

References AxisToDiagDir(), GetCrossingRailAxis(), HasVehicleOnPos(), IsLevelCrossingTile(), ReverseDiagDir(), TileOffsByDiagDir(), and TrainApproachingCrossingEnum().

Referenced by CheckLevelCrossing().

◆ 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, nullptr otherwise

Definition at line 1697 of file train_cmd.cpp.

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

Referenced by TrainApproachingCrossing().

◆ 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 3862 of file train_cmd.cpp.

References DiagDirToAxis(), Vehicle::direction, GetCrossingRoadAxis(), INVALID_TILE, Vehicle::IsFrontEngine(), IsLevelCrossingTile(), Vehicle::tile, TileOffsByDiagDir(), TrainCanLeaveTile(), VehicleExitDir(), Vehicle::vehstatus, and VS_CRASHED.

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

◆ 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 3787 of file train_cmd.cpp.

References _breakdown_speeds, GroundVehicleCache::cached_veh_length, Vehicle::cur_speed, DIR_E, DIR_N, DIR_NE, DIR_NW, DIR_S, DIR_SE, DIR_W, Vehicle::direction, GroundVehicle< T, Type >::gcache, IsDiagonalDirection(), ReverseTrainDirection(), TILE_SIZE, Vehicle::vehstatus, VS_TRAIN_SLOWING, Vehicle::x_pos, and Vehicle::y_pos.

Referenced by TrainCheckIfLineEnds().

◆ 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 3832 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 TrainApproachingCrossingTile(), and 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 3889 of file train_cmd.cpp.

References _breakdown_speeds, Vehicle::breakdown_ctr, Vehicle::cur_speed, DiagdirReachesTrackdirs(), Vehicle::direction, FindFirstTrack(), GB(), GetTileRailType(), GetTileTrackStatus(), IsLevelCrossingTile(), MaybeBarCrossingWithSound(), Rail90DegTurnDisallowed(), ReverseDiagDir(), Vehicle::tile, TileOffsByDiagDir(), TRACK_BIT_NONE, TrackdirBitsToTrackBits(), TrackStatusToRedSignals(), TrackStatusToTrackdirBits(), TrainApproachingLineEnd(), TrainCanLeaveTile(), TRANSPORT_RAIL, VehicleExitDir(), 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 3278 of file train_cmd.cpp.

References _accel_slowdown, _settings_client, _settings_game, RailTypeInfo::acceleration_type, AffectSpeedByZChange(), SoundSettings::ambient, TrainCache::cached_max_curve_speed, CCF_TRACK, CheckNextTrainTile(), ClearPathReservation(), Vehicle::cur_speed, Ticks::DAY_TICKS, DIAGDIR_BEGIN, DIAGDIR_END, DiagdirBetweenTiles(), DiagdirReachesTrackdirs(), DiagDirToDiagTrack(), DIRDIFF_45LEFT, DIRDIFF_45RIGHT, DirDifference(), Vehicle::direction, FindFirstBit(), FindFirstTrack(), FindFirstTrackdir(), SpecializedVehicle< T, Type >::First(), Train::GetCurveSpeedLimit(), GetNewVehiclePos(), GetOtherTunnelBridgeEnd(), GetRailTypeInfo(), GetReservedTrackbits(), GetTileRailType(), GetTileTrackStatus(), GetTunnelBridgeDirection(), Train::GetVehicleTrackdir(), HasBit(), HasCrossingReservation(), HasOnewaySignalBlockingTrackdir(), HasPbsSignalOnTrackdir(), HasReservedTracks(), HasSignalOnTrackdir(), HasSignals(), HasVehicleOnPos(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, INVALID_TILE, Vehicle::IsFrontEngine(), IsLevelCrossingTile(), IsPlainRailTile(), IsTileType(), IsTunnel(), IsValidDiagDirection(), AccelerationSlowdownParams::large_turn, MarkTileDirtyByTile(), MarkTrainAsStuck(), MP_TUNNELBRIDGE, GetNewVehiclePosResult::new_tile, SpecializedVehicle< T, Type >::Next(), GetNewVehiclePosResult::old_tile, Vehicle::owner, PathfinderSettings::path_backoff_interval, GameSettings::pf, SpecializedVehicle< T, Type >::Previous(), Vehicle::progress, Rail90DegTurnDisallowed(), PathfinderSettings::reverse_at_signals, ReverseDiagDir(), ReverseTrackdir(), ReverseTrainDirection(), SetSignalStateByTrackdir(), SetWindowDirty(), SIGNAL_STATE_RED, SIGSEG_PBS, SIGTYPE_PBS, AccelerationSlowdownParams::small_turn, SND_0E_LEVEL_CROSSING, ClientSettings::sound, Vehicle::subspeed, TFP_NONE, TFP_SIGNAL, TFP_STUCK, Vehicle::tick_counter, Vehicle::tile, TileAddByDiagDir(), TRACK_BIT_DEPOT, TRACK_BIT_LEFT, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_UPPER, TRACK_BIT_WORMHOLE, TRACK_BIT_X, TRACK_BIT_Y, TrackBitsToTrack(), TrackdirBitsToTrackBits(), TrackDirectionToTrackdir(), TrackdirToExitdir(), TrackdirToTrack(), TrackStatusToRedSignals(), TrackStatusToTrackdirBits(), TrackToTrackBits(), VehicleSettings::train_acceleration_model, TrainApproachingCrossingTile(), TrainCheckIfLineEnds(), TrainEnterStation(), TRANSPORT_RAIL, TryPathReserve(), TryReserveRailTrack(), Train::UpdateDeltaXY(), GroundVehicle< T, Type >::UpdateInclination(), UpdateLevelCrossing(), Vehicle::UpdatePosition(), UpdateSignalsOnSegment(), GameSettings::vehicle, VehicleEnterTile(), Vehicle::vehstatus, VETS_CANNOT_ENTER, VETS_ENTERED_STATION, VETS_ENTERED_WORMHOLE, VETS_STATION_ID_OFFSET, VRF_TRAIN_STUCK, VS_HIDDEN, Train::wait_counter, PathfinderSettings::wait_oneway_signal, PathfinderSettings::wait_twoway_signal, WC_VEHICLE_VIEW, Vehicle::x_pos, GetNewVehiclePosResult::y, and Vehicle::y_pos.

Referenced by AdvanceWagonsAfterSwap(), AdvanceWagonsBeforeSwap(), 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 3149 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()

◆ TrainLocoHandler()

static bool TrainLocoHandler ( Train v,
bool  mode 
)
static

Definition at line 3940 of file train_cmd.cpp.

◆ TrainMovedChangeSignals()

static bool TrainMovedChangeSignals ( TileIndex  tile,
DiagDirection  dir 
)
static

Definition at line 3073 of file train_cmd.cpp.

◆ TrainOnCrossing()

bool TrainOnCrossing ( TileIndex  tile)

Check if a level crossing tile has a train on it.

Parameters
tiletile to test
Returns
true if a train is on the crossing
Precondition
tile is a level crossing

Definition at line 1683 of file train_cmd.cpp.

References HasVehicleOnPos(), IsLevelCrossingTile(), and TrainOnTileEnum().

Referenced by CheckLevelCrossing().

◆ 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, nullptr otherwise

Definition at line 1672 of file train_cmd.cpp.

References BaseVehicle::type, and VEH_TRAIN.

Referenced by TrainOnCrossing().

◆ TryPathReserve()

◆ TryReserveSafeTrack()

static bool TryReserveSafeTrack ( const Train v,
TileIndex  tile,
Trackdir  td,
bool  override_railtype 
)
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 2593 of file train_cmd.cpp.

References YapfTrainFindNearestSafeTile().

◆ UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval()

void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval ( TileIndex  tile,
Axis  road_axis 
)

Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing tile.

Parameters
tileThe crossing tile which has been or is about to be removed, and which caused the update.
road_axisThe road axis.

Definition at line 1822 of file train_cmd.cpp.

References AxisToDiagDir(), CheckLevelCrossing(), GetCrossingRoadAxis(), IsCrossingBarred(), IsLevelCrossingTile(), MarkTileDirtyByTile(), ReverseDiagDir(), SetCrossingBarred(), Map::Size(), and TileOffsByDiagDir().

Referenced by CmdRemoveSingleRail(), and RemoveRoad().

◆ UpdateLevelCrossing()

void UpdateLevelCrossing ( TileIndex  tile,
bool  sound,
bool  force_bar 
)

Update a level crossing to barred or open (crossing may include multiple adjacent tiles).

Parameters
tileTile which causes the update.
soundShould we play sound?
force_barShould we force the crossing to be barred?

Definition at line 1773 of file train_cmd.cpp.

References AxisToDiagDir(), CheckLevelCrossing(), GetCrossingRoadAxis(), IsLevelCrossingTile(), ReverseDiagDir(), Map::Size(), TileAddByDiagDir(), and UpdateLevelCrossingTile().

Referenced by AfterLoadGame(), ChangeOwnershipOfCompanyItems(), CmdBuildRoad(), CmdBuildSingleRail(), Train::Crash(), DeleteLastWagon(), MaybeBarCrossingWithSound(), ReverseTrainDirection(), TrainController(), TryReserveRailTrack(), and UnreserveRailTrack().

◆ UpdateLevelCrossingTile()

static void UpdateLevelCrossingTile ( TileIndex  tile,
bool  sound,
bool  force_barred 
)
static

Sets a level crossing tile to the correct state.

Parameters
tileTile to update.
soundShould we play sound?
force_barredShould we set the crossing to barred?
Precondition
tile is a rail-road crossing.

Definition at line 1751 of file train_cmd.cpp.

References _settings_client, SoundSettings::ambient, CheckLevelCrossing(), IsCrossingBarred(), IsLevelCrossingTile(), MarkTileDirtyByTile(), SetCrossingBarred(), SND_0E_LEVEL_CROSSING, and ClientSettings::sound.

Referenced by UpdateLevelCrossing().

◆ UpdateStatusAfterSwap()

◆ 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_srcThe original source chain.
srcThe source chain after constructing the train.
check_limitWhether to check the vehicle limit.
Returns
possible error of this command.

Definition at line 1102 of file train_cmd.cpp.

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

Referenced by CmdMoveRailVehicle(), and 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 3047 of file train_cmd.cpp.

Referenced by AffectSpeedByZChange(), and TrainController().

◆ _breakdown_speeds

const uint16_t _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 3774 of file train_cmd.cpp.

Referenced by TrainApproachingLineEnd(), and TrainCheckIfLineEnds().

◆ _initial_tile_subcoord

const uint8_t _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 2447 of file train_cmd.cpp.

◆ _vehicle_initial_x_fract

const uint8_t _vehicle_initial_x_fract[4] = {10, 8, 4, 8}
static

Definition at line 54 of file train_cmd.cpp.

◆ _vehicle_initial_y_fract

const uint8_t _vehicle_initial_y_fract[4] = { 8, 4, 8, 10}
static

Definition at line 55 of file train_cmd.cpp.