train_cmd.cpp File Reference

Handling of trains. More...

#include "stdafx.h"
#include "gui.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 "vehicle_gui.h"
#include "newgrf_sound.h"
#include "newgrf_text.h"
#include "group.h"
#include "strings_func.h"
#include "functions.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "ai/ai.hpp"
#include "newgrf_station.h"
#include "effectvehicle_func.h"
#include "gamelog.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 "table/strings.h"
#include "table/train_cmd.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  RailtypeSlowdownParams
struct  TrainCollideChecker

Defines

#define MKIT(a, b, c, d)   ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)

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)
 Checks for line end.
static void TrainController (Train *v, Vehicle *nomove)
static TileIndex TrainApproachingCrossingTile (const Train *v)
 Determines whether train is approaching a rail-road crossing (thus making it barred).
static void CheckIfTrainNeedsService (Train *v)
static void CheckNextTrainTile (Train *v)
 Check if the train is on the last reserved tile and try to extend the path then.
static DiagDirection TrainExitDir (Direction direction, TrackBits track)
 Determine the side in which the train will leave the tile.
byte FreightWagonMult (CargoID cargo)
 Return the cargo weight multiplier to use for a rail vehicle.
static void RailVehicleLengthChanged (const Train *u)
 Logs a bug in GRF and shows a warning message if this is for the first time this happened.
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 spritenum, Direction direction)
static SpriteID GetRailIcon (EngineID engine, bool rear_head, int &y)
void DrawTrainEngine (int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal)
static CommandCost CmdBuildRailWagon (TileIndex tile, DoCommandFlag flags, const Engine *e, Vehicle **ret)
 Build a railroad wagon.
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.
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 (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Move a rail vehicle around inside the depot.
CommandCost CmdSellRailWagon (DoCommandFlag flags, Vehicle *t, uint16 data, uint32 user)
 Sell a (single) train wagon/engine.
static void SetLastSpeed (Train *v, int spd)
static void MarkTrainAsStuck (Train *v)
 Mark a train as stuck and stop it if it isn't stopped right now.
static void SwapTrainFlags (uint16 *swap_flag1, uint16 *swap_flag2)
static void UpdateStatusAfterSwap (Train *v)
 Updates some variables after swapping the vehicle.
static void ReverseTrainSwapVeh (Train *v, int l, int r)
static VehicleTrainOnTileEnum (Vehicle *v, void *)
 Check if the vehicle is a train.
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.
void UpdateLevelCrossing (TileIndex tile, bool sound)
 Sets correct crossing state.
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 void ReverseTrainDirection (Train *v)
CommandCost CmdReverseTrainDirection (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Reverse train.
CommandCost CmdForceTrainProceed (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Force a train through a red signal.
static FindDepotData FindClosestTrainDepot (Train *v, int max_distance)
 returns the tile of a depot to goto to.
static bool CheckTrainStayInDepot (Train *v)
static void ClearPathReservation (const Train *v, TileIndex tile, Trackdir track_dir)
 Clear the reservation of a tile that was just left by a wagon on track_dir.
void FreeTrainTrackReservation (const Train *v, TileIndex origin, Trackdir orig_td)
 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)
 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_tailtype)
 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, byte 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)
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 void DeleteLastWagon (Train *v)
 Deletes/Clears the last wagon of a crashed train.
static void ChangeTrainDirRandomly (Train *v)
static bool HandleCrashedTrain (Train *v)
static bool TrainApproachingLineEnd (Train *v, bool signal)
 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 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 RailtypeSlowdownParams _railtype_slowdown []
static const uint16 _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.


Function Documentation

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:
v First vehicle in chain

Definition at line 1623 of file train_cmd.cpp.

References GroundVehicleCache::cached_veh_length, Vehicle::first, GroundVehicle< T, Type >::gcache, GetRailDepotTrack(), SpecializedVehicle< T, Type >::Last(), SpecializedVehicle< T, Type >::Next(), SpecializedVehicle< T, Type >::Previous(), TicksToLeaveDepot(), Vehicle::tile, TRACK_BIT_DEPOT, TrackToTrackBits(), Vehicle::vehstatus, and VS_HIDDEN.

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:
v First vehicle in chain

Definition at line 1595 of file train_cmd.cpp.

References GroundVehicleCache::cached_veh_length, Vehicle::first, GroundVehicle< T, Type >::gcache, SpecializedVehicle< T, Type >::Last(), SpecializedVehicle< T, Type >::Next(), and SpecializedVehicle< T, Type >::Previous().

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_head The destination chain of the to be moved vehicle.
dst The destination for the to be moved vehicle.
src_head The source chain of the to be moved vehicle.
src The to be moved vehicle.
move_chain Whether to move all vehicles after src or not.

Definition at line 1033 of file train_cmd.cpp.

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

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().

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_dst The original destination chain.
dst The destination chain after constructing the train.
original_dst The original source chain.
dst The source chain after constructing the train.
Returns:
possible error of this command.

Definition at line 910 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().

static void CheckNextTrainTile ( Train v  )  [static]
static CommandCost CheckTrainAttachment ( Train t  )  [static]
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.

Definition at line 2858 of file train_cmd.cpp.

References AddVehicleNewsItem(), FindVehicleOnPos(), FindVehicleOnPosXY(), GetOtherTunnelBridgeEnd(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, NS_ACCIDENT, TrainCollideChecker::num, Vehicle::owner, SetDParam(), Vehicle::tile, TRACK_BIT_DEPOT, TRACK_BIT_WORMHOLE, TrainCollideChecker::v, Vehicle::x_pos, and Vehicle::y_pos.

void CheckTrainsLengths (  ) 
static void ClearPathReservation ( const Train v,
TileIndex  tile,
Trackdir  track_dir 
) [static]
CommandCost CmdBuildRailVehicle ( TileIndex  tile,
DoCommandFlag  flags,
const Engine e,
uint16  data,
Vehicle **  ret 
)

Build a railroad vehicle.

Parameters:
tile tile of the depot where rail-vehicle is built.
flags type of operation.
e the engine to build.
data bit 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 669 of file train_cmd.cpp.

References _cur_year, _current_company, _date, RailVehicleInfo::capacity, Vehicle::cargo_cap, Vehicle::cargo_type, CheckConsistencyOfArticulatedVehicle(), CMD_ERROR, CmdBuildRailWagon(), Train::ConsistChanged(), Vehicle::cur_image, DC_AUTOREPLACE, DC_EXEC, DEFAULT_GROUP, DiagDirToDir(), Vehicle::direction, ENGINE_EXCLUSIVE_PREVIEW, GroundVehicleCache::first_engine, GroundVehicle< T, Type >::gcache, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::Get(), Engine::GetDefaultCargoType(), Engine::GetLifeLengthInDays(), GetRailDepotDirection(), GetRailType(), Vehicle::group_id, HasBit(), HasPowerOnRail(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, Vehicle::max_age, NormalizeTrainVehInDepot(), Vehicle::owner, RAILVEH_MULTIHEAD, RAILVEH_WAGON, Vehicle::reliability, Vehicle::reliability_spd_dec, SetBit(), GroundVehicle< T, Type >::SetEngine(), GroundVehicle< T, Type >::SetFrontEngine(), Vehicle::spritenum, Vehicle::tile, TILE_SIZE, TileX(), TileY(), TRACK_BIT_DEPOT, UpdateTrainGroupID(), Vehicle::vehicle_flags, VehicleMove(), VehicleRandomBits(), Vehicle::vehstatus, VF_BUILT_AS_PROTOTYPE, VS_DEFPAL, VS_HIDDEN, VS_STOPPED, Vehicle::x_pos, Vehicle::y_pos, and Vehicle::z_pos.

Referenced by CmdBuildVehicle().

static CommandCost CmdBuildRailWagon ( TileIndex  tile,
DoCommandFlag  flags,
const Engine e,
Vehicle **  ret 
) [static]
CommandCost CmdForceTrainProceed ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)

Force a train through a red signal.

Parameters:
tile unused
flags type of operation
p1 train to ignore the red signal
p2 unused
text unused
Returns:
the cost of this operation or an error

Definition at line 1838 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, Tcache, Tzero >::PoolItem< Tpool >::index, Train::IsInDepot(), Vehicle::owner, SetWindowDirty(), TFP_NONE, TFP_SIGNAL, and TFP_STUCK.

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

Move a rail vehicle around inside the depot.

Parameters:
tile unused
flags type of operation Note: DC_AUTOREPLACE is set when autoreplace tries to undo its modifications or moves vehicles to temporary locations inside the depot.
p1 various bitstuffed elements

  • p1 (bit 0 - 19) source vehicle index
  • p1 (bit 20) move all vehicles following the source vehicle
p2 what wagon to put the source wagon AFTER, XXX - INVALID_VEHICLE to make a new line
text unused
Returns:
the cost of this operation or an error

Definition at line 1107 of file train_cmd.cpp.

References ArrangeTrains(), CheckOwnership(), CMD_ERROR, DC_AUTOREPLACE, DC_EXEC, DEFAULT_GROUP, DeleteVehicleOrders(), DeleteWindowById(), CommandCost::Failed(), SpecializedVehicle< T, Type >::First(), GB(), Train::GetFirstEnginePart(), SpecializedVehicle< Train, Type >::GetIfValid(), Train::GetLastEnginePart(), Vehicle::group_id, HasBit(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, INVALID_VEHICLE, InvalidateWindowClassesData(), InvalidateWindowData(), GroundVehicle< T, Type >::IsEngine(), GroundVehicle< T, Type >::IsFrontEngine(), GroundVehicle< T, Type >::IsRearDualheaded(), Train::IsStoppedInDepot(), MakeTrainBackup(), NormaliseSubtypes(), NormaliseTrainHead(), Vehicle::owner, RemoveVehicleFromGroup(), RestoreTrainBackup(), return_cmd_error, SetTrainGroupID(), Vehicle::tile, Vehicle::unitnumber, ValidateTrains(), Vehicle::vehstatus, and VS_CRASHED.

CommandCost CmdReverseTrainDirection ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)
CommandCost CmdSellRailWagon ( DoCommandFlag  flags,
Vehicle t,
uint16  data,
uint32  user 
)

Sell a (single) train wagon/engine.

Parameters:
flags type of operation
t the train wagon to sell
data the 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
user the user for the order backup.
Returns:
the cost of this operation or an error

Definition at line 1294 of file train_cmd.cpp.

References CommandCost::AddCost(), Vehicle::AddToShared(), ArrangeTrains(), OrderBackup::Backup(), Vehicle::CopyVehicleConfigAndStatistics(), DC_AUTOREPLACE, DC_EXEC, DeleteVehicleOrders(), EXPENSES_NEW_VEHICLES, CommandCost::Failed(), SpecializedVehicle< T, Type >::First(), Vehicle::first, SpecializedVehicle< Train, Type >::From(), Train::GetFirstEnginePart(), Vehicle::group_id, HasBit(), InvalidateWindowClassesData(), InvalidateWindowData(), GroundVehicle< T, Type >::IsEngine(), GroundVehicle< T, Type >::IsFrontEngine(), IsLocalCompany(), Train::IsPrimaryVehicle(), GroundVehicle< T, Type >::IsRearDualheaded(), Vehicle::list, MAKE_ORDER_BACKUP_FLAG, MakeTrainBackup(), Vehicle::Next(), NormaliseSubtypes(), NormaliseTrainHead(), RestoreTrainBackup(), return_cmd_error, ShowVehicleViewWindow(), Vehicle::tile, ValidateTrains(), and Vehicle::value.

Referenced by CmdSellVehicle().

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

Collect trackbits of all crashed train vehicles on a tile.

Parameters:
v Vehicle passed from Find/HasVehicleOnPos()
data trackdirbits for the result
Returns:
NULL to iterate over all vehicles on the tile.

Definition at line 3228 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().

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:
v the Vehicle of which last wagon is to be removed

Definition at line 3252 of file train_cmd.cpp.

References CollectTrackbitsFromCrashedVehiclesEnum(), Train::ConsistChanged(), DiagDirToDiagTrackBits(), FindVehicleOnPos(), SpecializedVehicle< T, Type >::First(), FOR_EACH_SET_TRACK, GetTunnelBridgeDirection(), HasReservedTracks(), INVALID_DIAGDIR, IsLevelCrossingTile(), IsRailDepotTile(), IsTileType(), MP_TUNNELBRIDGE, SpecializedVehicle< T, Type >::Next(), Vehicle::owner, Vehicle::SetNext(), SetSignalsOnBothDir(), SetWindowDirty(), Vehicle::tile, TRACK_BEGIN, TRACK_BIT_DEPOT, TRACK_BIT_NONE, TRACK_BIT_WORMHOLE, TRACK_X, TRACK_Y, TrackBitsToTrack(), TryReserveRailTrack(), UnreserveRailTrack(), UpdateLevelCrossing(), and UpdateSignalsOnSegment().

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:
v The train
tile The tile the train is about to enter
enterdir Diagonal direction the train is coming from
tracks Usable tracks on the new tile
path_found [out] Whether a path has been found or not.
do_track_reservation Path reservation is requested
dest [out] State and destination of the requested path
Returns:
The best track the train should follow

Definition at line 2146 of file train_cmd.cpp.

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

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 2161 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, TileOffsByDiagDir(), PBSTileInfo::trackdir, TRACKDIR_BIT_NONE, TrackdirBitsToTrackBits(), TrackdirCrossesTrackdirs(), TrackdirReachesTrackdirs(), TrackdirToTrack(), TryReserveRailTrack(), and UnreserveRailTrack().

static FindDepotData FindClosestTrainDepot ( Train v,
int  max_distance 
) [static]
void FreeTrainTrackReservation ( const Train v,
TileIndex  origin,
Trackdir  orig_td 
)

Free the reserved path in front of a vehicle.

Definition at line 2077 of file train_cmd.cpp.

References ClearPathReservation(), RailtypeInfo::compatible_railtypes, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::Follow(), GetRailTypeInfo(), GetReservedTrackbits(), GetSignalStateByTrackdir(), GetStationIndex(), Train::GetVehicleTrackdir(), HasPbsSignalOnTrackdir(), HasSignalOnTrackdir(), INVALID_TILE, INVALID_TRACKDIR, GroundVehicle< T, Type >::IsFrontEngine(), IsOnewaySignal(), IsRailStationTile(), IsTileType(), IsValidTrackdir(), CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_bridge, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_station, CFollowTrackT< Ttr_type_, VehicleType, T90deg_turns_allowed_, Tmask_reserved_tracks >::m_is_tunnel, 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, MarkTileDirtyByTile(), MP_RAILWAY, MP_TUNNELBRIDGE, RemoveFirstTrackdir(), ReverseTrackdir(), SetSignalStateByTrackdir(), SIGNAL_STATE_RED, Vehicle::tile, TrackBitsToTrackdirBits(), TRACKDIR_BIT_NONE, TrackdirToTrack(), TracksOverlap(), TrackToTrackBits(), and UnreserveRailTrack().

Referenced by CmdBuildRailStation(), CmdBuildSingleSignal(), CmdConvertRail(), CmdRemoveSingleRail(), Train::Crash(), DoClearBridge(), DoClearTunnel(), RemoveFromRailBaseStation(), and RemoveRailStation().

byte FreightWagonMult ( CargoID  cargo  ) 

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

Parameters:
cargo Cargo type to get multiplier for
Returns:
Cargo weight multiplier

Definition at line 81 of file train_cmd.cpp.

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

Referenced by DrawTrainDetails(), Train::GetWeight(), TrainDetailsCapacityTab(), and TrainDetailsCargoTab().

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_id the ID of the station where we're stopping
tile the tile where the vehicle currently is
v the 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 275 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().

static void InsertInConsist ( Train dst,
Train chain 
) [static]

Inserts a chain into the train at dst.

Parameters:
dst the place where to append after.
chain the chain to actually add.

Definition at line 842 of file train_cmd.cpp.

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

Referenced by ArrangeTrains(), and NormaliseDualHeads().

static void MakeTrainBackup ( TrainList list,
Train t 
) [static]

Make a backup of a train into a train list.

Parameters:
list to make the backup in
t the train to make the backup of

Definition at line 792 of file train_cmd.cpp.

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

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().

static void MarkTrainAsStuck ( Train v  )  [static]
static void MaybeBarCrossingWithSound ( TileIndex  tile  )  [inline, static]

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

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

Definition at line 1580 of file train_cmd.cpp.

References BarCrossing(), IsCrossingBarred(), and MarkTileDirtyByTile().

Referenced by TrainCheckIfLineEnds().

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:
t the train to normalise.

Definition at line 856 of file train_cmd.cpp.

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

Referenced by ArrangeTrains().

static void NormaliseSubtypes ( Train chain  )  [static]
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:
head the train to update.

Definition at line 1074 of file train_cmd.cpp.

References Train::ConsistChanged(), GetFreeUnitNumber(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, InvalidateWindowData(), GroundVehicle< T, Type >::IsFrontEngine(), SetWindowWidgetDirty(), Vehicle::unitnumber, UpdateTrainGroupID(), and VEH_TRAIN.

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().

static void RailVehicleLengthChanged ( const Train u  )  [static]
static void RemoveFromConsist ( Train part,
bool  chain = false 
) [static]

Remove the given wagon from its consist.

Parameters:
part the part of the train to remove.
chain whether to remove the whole chain.

Definition at line 825 of file train_cmd.cpp.

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

Referenced by ArrangeTrains(), and NormaliseDualHeads().

static void RestoreTrainBackup ( TrainList list  )  [static]

Restore the train from the backup list.

Parameters:
list the train to restore.

Definition at line 801 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 CmdMoveRailVehicle(), and CmdSellRailWagon().

static bool TrainApproachingCrossing ( TileIndex  tile  )  [static]

Finds a vehicle approaching rail-road crossing.

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

Definition at line 1536 of file train_cmd.cpp.

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

Referenced by UpdateLevelCrossing().

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

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

Parameters:
v vehicle on tile
data tile with crossing we are testing
Returns:
v if it is approaching a crossing, NULL otherwise

Definition at line 1515 of file train_cmd.cpp.

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

Referenced by TrainApproachingCrossing().

static TileIndex TrainApproachingCrossingTile ( const Train v  )  [static]

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

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

Definition at line 3453 of file train_cmd.cpp.

References DiagDirToAxis(), Vehicle::direction, GetCrossingRoadAxis(), INVALID_TILE, GroundVehicle< T, Type >::IsFrontEngine(), IsLevelCrossingTile(), Vehicle::tile, TileOffsByDiagDir(), TrainCanLeaveTile(), TrainExitDir(), Vehicle::vehstatus, and VS_CRASHED.

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

static bool TrainApproachingLineEnd ( Train v,
bool  signal 
) [static]

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

Parameters:
v front train engine
signal not line end, just a red signal
Returns:
true iff we did NOT have to reverse

Definition at line 3382 of file train_cmd.cpp.

References 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, TILE_SIZE, Vehicle::vehstatus, VS_TRAIN_SLOWING, Vehicle::x_pos, and Vehicle::y_pos.

Referenced by TrainCheckIfLineEnds().

static bool TrainCanLeaveTile ( const Train v  )  [static]

Determines whether train would like to leave the tile.

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

Definition at line 3423 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().

static bool TrainCheckIfLineEnds ( Train v  )  [static]
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:
v first vehicle of chain
Returns:
number of victims (including 2 drivers; zero if train was already crashed)

Definition at line 2791 of file train_cmd.cpp.

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

static void TrainEnterStation ( Train v,
StationID  station 
) [static]

Trains enters a station, send out a news item if it is the first train, and start loading.

Parameters:
v Train that entered the station.
station Station visited.

Definition at line 2657 of file train_cmd.cpp.

References _local_company, AddVehicleNewsItem(), SpecializedStation< Station, false >::Get(), HVOT_TRAIN, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, AI::NewEvent(), NS_ARRIVAL_COMPANY, NS_ARRIVAL_OTHER, Vehicle::owner, SAT_TRAIN_ARRIVES, SetDParam(), SetWindowDirty(), TFP_NONE, and Vehicle::tile.

static DiagDirection TrainExitDir ( Direction  direction,
TrackBits  track 
) [inline, static]

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

Parameters:
direction vehicle direction
track vehicle track bits
Returns:
side of tile the train will leave

Definition at line 61 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 TrainApproachingCrossingTile(), and TrainCheckIfLineEnds().

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

Check if the vehicle is a train.

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

Definition at line 1503 of file train_cmd.cpp.

References BaseVehicle::type, and VEH_TRAIN.

Referenced by UpdateLevelCrossing().

bool TryPathReserve ( Train v,
bool  mark_as_stuck,
bool  first_tile_okay 
)
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:
v The vehicle.
tile The tile the search should start from.
td The trackdir the search should start from.
override_railtype Whether all physically compatible railtypes should be followed.
Returns:
True if a path to a safe stopping tile could be reserved.

Definition at line 2253 of file train_cmd.cpp.

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

void UpdateLevelCrossing ( TileIndex  tile,
bool  sound 
)

Sets correct crossing state.

Parameters:
tile tile to update
sound should we play sound?
Precondition:
tile is a rail-road crossing

Definition at line 1558 of file train_cmd.cpp.

References HasCrossingReservation(), HasVehicleOnPos(), IsCrossingBarred(), IsLevelCrossingTile(), MarkTileDirtyByTile(), SetCrossingBarred(), TrainApproachingCrossing(), and TrainOnTileEnum().

Referenced by CmdBuildRoad(), CmdBuildSingleRail(), Train::Crash(), DeleteLastWagon(), and UnreserveRailTrack().

static void UpdateStatusAfterSwap ( Train v  )  [static]

Updates some variables after swapping the vehicle.

Parameters:
v swapped vehicle

Definition at line 1449 of file train_cmd.cpp.

References Vehicle::direction, ReverseDir(), Vehicle::tile, TRACK_BIT_DEPOT, TRACK_BIT_WORMHOLE, SpecializedVehicle< T, Type >::UpdateViewport(), VehicleEnterTile(), Vehicle::x_pos, and Vehicle::y_pos.

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_dst The original destination chain.
dst The destination chain after constructing the train.
original_dst The original source chain.
dst The source chain after constructing the train.
check_limit Whether to check the vehicle limit.
Returns:
possible error of this command.

Definition at line 1013 of file train_cmd.cpp.

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

Referenced by CmdMoveRailVehicle(), and CmdSellRailWagon().


Variable Documentation

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

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

const RailtypeSlowdownParams _railtype_slowdown[] [static]
Initial value:
 {
  
  {256 / 4, 256 / 2, 256 / 4, 2}, 
  {256 / 4, 256 / 2, 256 / 4, 2}, 
  {256 / 4, 256 / 2, 256 / 4, 2}, 
  {0,       256 / 2, 256 / 4, 2}, 
}

Definition at line 2696 of file train_cmd.cpp.


Generated on Thu Jan 20 22:58:05 2011 for OpenTTD by  doxygen 1.6.1