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

Base implementations of all vehicles. More...

#include "stdafx.h"
#include "error.h"
#include "roadveh.h"
#include "ship.h"
#include "spritecache.h"
#include "timetable.h"
#include "viewport_func.h"
#include "news_func.h"
#include "command_func.h"
#include "company_func.h"
#include "train.h"
#include "aircraft.h"
#include "newgrf_debug.h"
#include "newgrf_sound.h"
#include "newgrf_station.h"
#include "group_gui.h"
#include "strings_func.h"
#include "zoom_func.h"
#include "vehicle_func.h"
#include "autoreplace_func.h"
#include "autoreplace_gui.h"
#include "station_base.h"
#include "ai/ai.hpp"
#include "depot_func.h"
#include "network/network.h"
#include "core/pool_func.hpp"
#include "economy_base.h"
#include "articulated_vehicles.h"
#include "roadstop_base.h"
#include "core/random_func.hpp"
#include "core/backup_type.hpp"
#include "core/container_func.hpp"
#include "order_backup.h"
#include "sound_func.h"
#include "effectvehicle_func.h"
#include "effectvehicle_base.h"
#include "vehiclelist.h"
#include "bridge_map.h"
#include "tunnel_map.h"
#include "depot_map.h"
#include "gamelog.h"
#include "linkgraph/linkgraph.h"
#include "linkgraph/refresh.h"
#include "framerate_type.h"
#include "autoreplace_cmd.h"
#include "misc_cmd.h"
#include "train_cmd.h"
#include "vehicle_cmd.h"
#include "newgrf_roadstop.h"
#include "timer/timer.h"
#include "timer/timer_game_calendar.h"
#include "timer/timer_game_economy.h"
#include "timer/timer_game_tick.h"
#include "table/strings.h"
#include "safeguards.h"

Go to the source code of this file.

Macros

#define GEN_HASHX(x)   GB((x), GEN_HASHX_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHX_BITS)
 
#define GEN_HASHY(y)   (GB((y), GEN_HASHY_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS)
 
#define GEN_HASH(x, y)   (GEN_HASHY(y) + GEN_HASHX(x))
 

Typedefs

using AutoreplaceMap = std::map< VehicleID, bool >
 List of vehicles that should check for autoreplace this tick.
 

Functions

void VehicleServiceInDepot (Vehicle *v)
 Service a vehicle and all subsequent vehicles in the consist.
 
void ShowNewGrfVehicleError (EngineID engine, StringID part1, StringID part2, GRFBugs bug_type, bool critical)
 Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
 
void VehicleLengthChanged (const Vehicle *u)
 Logs a bug in GRF and shows a warning message if this is for the first time this happened.
 
static VehicleVehicleFromTileHash (int xl, int yl, int xu, int yu, void *data, VehicleFromPosProc *proc, bool find_first)
 
static VehicleVehicleFromPosXY (int x, int y, void *data, VehicleFromPosProc *proc, bool find_first)
 Helper function for FindVehicleOnPos/HasVehicleOnPos.
 
void FindVehicleOnPosXY (int x, int y, void *data, VehicleFromPosProc *proc)
 Find a vehicle from a specific location.
 
bool HasVehicleOnPosXY (int x, int y, void *data, VehicleFromPosProc *proc)
 Checks whether a vehicle in on a specific location.
 
static VehicleVehicleFromPos (TileIndex tile, void *data, VehicleFromPosProc *proc, bool find_first)
 Helper function for FindVehicleOnPos/HasVehicleOnPos.
 
void FindVehicleOnPos (TileIndex tile, void *data, VehicleFromPosProc *proc)
 Find a vehicle from a specific location.
 
bool HasVehicleOnPos (TileIndex tile, void *data, VehicleFromPosProc *proc)
 Checks whether a vehicle is on a specific location.
 
static VehicleEnsureNoVehicleProcZ (Vehicle *v, void *data)
 Callback that returns 'real' vehicles lower or at height *(int*)data .
 
CommandCost EnsureNoVehicleOnGround (TileIndex tile)
 Ensure there is no vehicle at the ground at the given position.
 
static VehicleGetVehicleTunnelBridgeProc (Vehicle *v, void *data)
 Procedure called for every vehicle found in tunnel/bridge in the hash map.
 
CommandCost TunnelBridgeIsFree (TileIndex tile, TileIndex endtile, const Vehicle *ignore)
 Finds vehicle in tunnel / bridge.
 
static VehicleEnsureNoTrainOnTrackProc (Vehicle *v, void *data)
 
CommandCost EnsureNoTrainOnTrackBits (TileIndex tile, TrackBits track_bits)
 Tests if a vehicle interacts with the specified track bits.
 
static void UpdateVehicleTileHash (Vehicle *v, bool remove)
 
static void UpdateVehicleViewportHash (Vehicle *v, int x, int y, int old_x, int old_y)
 
void ResetVehicleHash ()
 
void ResetVehicleColourMap ()
 
void InitializeVehicles ()
 
uint CountVehiclesInChain (const Vehicle *v)
 
void VehicleEnteredDepotThisTick (Vehicle *v)
 Adds a vehicle to the list of vehicles that visited a depot this tick.
 
void RunVehicleCalendarDayProc ()
 Age all vehicles, spreading out the action using the current TimerGameCalendar::date_fract.
 
static void RunEconomyVehicleDayProc ()
 Increases the day counter for all vehicles and calls 1-day and 32-day handlers.
 
void CallVehicleTicks ()
 
static void DoDrawVehicle (const Vehicle *v)
 Add vehicle sprite for drawing to the screen.
 
void ViewportAddVehicles (DrawPixelInfo *dpi)
 Add the vehicle sprites that should be drawn at a part of the screen.
 
VehicleCheckClickOnVehicle (const Viewport *vp, int x, int y)
 Find the vehicle close to the clicked coordinates.
 
void DecreaseVehicleValue (Vehicle *v)
 Decrease the value of a vehicle.
 
void CheckVehicleBreakdown (Vehicle *v)
 
void EconomyAgeVehicle (Vehicle *v)
 Update economy age of a vehicle.
 
void AgeVehicle (Vehicle *v)
 Update age of a vehicle.
 
uint8_t CalcPercentVehicleFilled (const Vehicle *front, StringID *colour)
 Calculates how full a vehicle is.
 
void VehicleEnterDepot (Vehicle *v)
 Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it, etc.
 
GetNewVehiclePosResult GetNewVehiclePos (const Vehicle *v)
 Get position information of a vehicle when moving one pixel in the direction it is facing.
 
Direction GetDirectionTowards (const Vehicle *v, int x, int y)
 
VehicleEnterTileStatus VehicleEnterTile (Vehicle *v, TileIndex tile, int x, int y)
 Call the tile callback function for a vehicle entering a tile.
 
UnitID GetFreeUnitNumber (VehicleType type)
 Get an unused unit number for a vehicle (if allowed).
 
bool CanBuildVehicleInfrastructure (VehicleType type, uint8_t subtype)
 Check whether we can build infrastructure for the given vehicle type.
 
LiveryScheme GetEngineLiveryScheme (EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
 Determines the LiveryScheme for a vehicle.
 
const LiveryGetEngineLivery (EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v, uint8_t livery_setting)
 Determines the livery for a vehicle.
 
static PaletteID GetEngineColourMap (EngineID engine_type, CompanyID company, EngineID parent_engine_type, const Vehicle *v)
 
PaletteID GetEnginePalette (EngineID engine_type, CompanyID company)
 Get the colour map for an engine.
 
PaletteID GetVehiclePalette (const Vehicle *v)
 Get the colour map for a vehicle.
 
static bool PreviousOrderIsUnbunching (const Vehicle *v)
 Check if the previous order is a depot unbunching order.
 
static void SpawnAdvancedVisualEffect (const Vehicle *v)
 Call CBID_VEHICLE_SPAWN_VISUAL_EFFECT and spawn requested effects.
 
bool CanVehicleUseStation (EngineID engine_type, const Station *st)
 Can this station be used by the given engine type?
 
bool CanVehicleUseStation (const Vehicle *v, const Station *st)
 Can this station be used by the given vehicle?
 
StringID GetVehicleCannotUseStationReason (const Vehicle *v, const Station *st)
 Get reason string why this station can't be used by the given vehicle.
 
void GetVehicleSet (VehicleSet &set, Vehicle *v, uint8_t num_vehicles)
 Calculates the set of vehicles that will be affected by a given selection.
 
bool VehiclesHaveSameEngineList (const Vehicle *v1, const Vehicle *v2)
 Checks if two vehicle chains have the same list of engines.
 
bool VehiclesHaveSameOrderList (const Vehicle *v1, const Vehicle *v2)
 Checks if two vehicles have the same list of orders.
 

Variables

static const uint GEN_HASHX_BITS = 6
 
static const uint GEN_HASHY_BITS = 6
 
static const uint GEN_HASHX_BUCKET_BITS = 7
 
static const uint GEN_HASHY_BUCKET_BITS = 6
 
static const int GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_BASE_SHIFT)
 
static const int GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_BASE_SHIFT)
 
static const int GEN_HASHX_INC = 1
 
static const int GEN_HASHY_INC = 1 << GEN_HASHX_BITS
 
static const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1
 
static const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS
 
VehiclePool _vehicle_pool ("Vehicle")
 The pool with all our precious vehicles.
 
const int HASH_BITS = 7
 
const int HASH_SIZE = 1 << HASH_BITS
 
const int HASH_MASK = HASH_SIZE - 1
 
const int TOTAL_HASH_SIZE = 1 << (HASH_BITS * 2)
 
const int TOTAL_HASH_MASK = TOTAL_HASH_SIZE - 1
 
const int HASH_RES = 0
 
static Vehicle_vehicle_tile_hash [TOTAL_HASH_SIZE]
 
static Vehicle_vehicle_viewport_hash [1<<(GEN_HASHX_BITS+GEN_HASHY_BITS)]
 
static AutoreplaceMap _vehicles_to_autoreplace
 
static const uint8_t _breakdown_chance [64]
 
static const Direction _new_direction_table []
 
static const int8_t _vehicle_smoke_pos [8]
 
static IntervalTimer< TimerGameEconomy_economy_vehicles_yearly ({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::VEHICLE}, [](auto) { for(Vehicle *v :Vehicle::Iterate()) { if(v->IsPrimaryVehicle()) { Money profit=v->GetDisplayProfitThisYear();if(v->economy_age >=VEHICLE_PROFIT_MIN_AGE &&profit< 0) { if(_settings_client.gui.vehicle_income_warn &&v->owner==_local_company) { SetDParam(0, v->index);SetDParam(1, profit);AddVehicleAdviceNewsItem(TimerGameEconomy::UsingWallclockUnits() ? STR_NEWS_VEHICLE_UNPROFITABLE_PERIOD :STR_NEWS_VEHICLE_UNPROFITABLE_YEAR, v->index);} AI::NewEvent(v->owner, new ScriptEventVehicleUnprofitable(v->index));} v->profit_last_year=v->profit_this_year;v->profit_this_year=0;SetWindowDirty(WC_VEHICLE_DETAILS, v->index);} } GroupStatistics::UpdateProfits();SetWindowClassesDirty(WC_TRAINS_LIST);SetWindowClassesDirty(WC_SHIPS_LIST);SetWindowClassesDirty(WC_ROADVEH_LIST);SetWindowClassesDirty(WC_AIRCRAFT_LIST);})
 

Detailed Description

Base implementations of all vehicles.

Definition in file vehicle.cpp.

Macro Definition Documentation

◆ GEN_HASH

#define GEN_HASH (   x,
 
)    (GEN_HASHY(y) + GEN_HASHX(x))

Definition at line 79 of file vehicle.cpp.

◆ GEN_HASHX

#define GEN_HASHX (   x)    GB((x), GEN_HASHX_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHX_BITS)

Definition at line 77 of file vehicle.cpp.

◆ GEN_HASHY

#define GEN_HASHY (   y)    (GB((y), GEN_HASHY_BUCKET_BITS + ZOOM_BASE_SHIFT, GEN_HASHY_BITS) << GEN_HASHX_BITS)

Definition at line 78 of file vehicle.cpp.

Typedef Documentation

◆ AutoreplaceMap

using AutoreplaceMap = std::map<VehicleID, bool>

List of vehicles that should check for autoreplace this tick.

Mapping of vehicle -> leave depot immediately after autoreplace.

Definition at line 694 of file vehicle.cpp.

Function Documentation

◆ AgeVehicle()

◆ CalcPercentVehicleFilled()

uint8_t CalcPercentVehicleFilled ( const Vehicle front,
StringID colour 
)

Calculates how full a vehicle is.

Parameters
frontThe front vehicle of the consist to check.
colourThe string to show depending on if we are unloading or loading
Returns
A percentage of how full the Vehicle is. Percentages are rounded towards 50%, so that 0% and 100% are only returned if the vehicle is completely empty or full. This is useful for both display and conditional orders.

Definition at line 1493 of file vehicle.cpp.

References Vehicle::cargo, Vehicle::cargo_cap, Vehicle::cargo_type, CeilDiv(), Vehicle::current_order, SpecializedStation< Station, false >::GetIfValid(), Order::GetLoadType(), Station::goods, HasBit(), GoodsEntry::HasRating(), Order::IsType(), Vehicle::last_station_visited, Vehicle::Next(), OLFB_FULL_LOAD, OLFB_NO_LOAD, VehicleCargoList::StoredCount(), BaseConsist::vehicle_flags, VF_CARGO_UNLOADING, VF_LOADING_FINISHED, and VF_STOP_LOADING.

Referenced by AfterLoadVehiclesPhase2(), Vehicle::LeaveStation(), LoadUnloadVehicle(), and ProcessConditionalOrder().

◆ CallVehicleTicks()

void CallVehicleTicks ( )

Definition at line 984 of file vehicle.cpp.

◆ CanBuildVehicleInfrastructure()

◆ CanVehicleUseStation() [1/2]

bool CanVehicleUseStation ( const Vehicle v,
const Station st 
)

Can this station be used by the given vehicle?

Parameters
vthe vehicle to test
stthe station to test for
Returns
true if and only if the vehicle can use this station.

Definition at line 3091 of file vehicle.cpp.

References CanVehicleUseStation(), Vehicle::engine_type, SpecializedVehicle< T, Type >::From(), BaseVehicle::type, and VEH_ROAD.

◆ CanVehicleUseStation() [2/2]

bool CanVehicleUseStation ( EngineID  engine_type,
const Station st 
)

Can this station be used by the given engine type?

Parameters
engine_typethe type of vehicles to test
stthe station to test for
Returns
true if and only if the vehicle of the type can use this station.
Note
For road vehicles the Vehicle is needed to determine whether it can use the station. This function will return true for road vehicles when at least one of the facilities is available.

Definition at line 3058 of file vehicle.cpp.

References AIR_CTOL, AirportFTAClass::AIRPLANES, Station::airport, FACIL_AIRPORT, FACIL_BUS_STOP, FACIL_DOCK, FACIL_TRAIN, FACIL_TRUCK_STOP, BaseStation::facilities, AirportFTAClass::flags, Airport::GetFTA(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_engine_pool >::GetIfValid(), AirportFTAClass::HELICOPTERS, AircraftVehicleInfo::subtype, Engine::type, VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, and VEH_TRAIN.

Referenced by CanVehicleUseStation(), CheckOrders(), CmdBuildAircraft(), CmdCloneOrder(), CmdInsertOrder(), DrawOrderString(), Aircraft::FindClosestDepot(), RoadVehicle::GetOrderStationLocation(), Ship::GetOrderStationLocation(), and UpdateAirplanesOnNewStation().

◆ CheckClickOnVehicle()

Vehicle * CheckClickOnVehicle ( const Viewport vp,
int  x,
int  y 
)

Find the vehicle close to the clicked coordinates.

Parameters
vpViewport clicked in.
xX coordinate in the viewport.
yY coordinate in the viewport.
Returns
Closest vehicle, or nullptr if none found.

Definition at line 1248 of file vehicle.cpp.

References abs(), Vehicle::coord, Vehicle::hash_viewport_next, Viewport::height, Viewport::left, MAX_VEHICLE_PIXEL_X, MAX_VEHICLE_PIXEL_Y, ScaleByZoom(), Viewport::top, Vehicle::vehstatus, Viewport::virtual_left, Viewport::virtual_top, VS_HIDDEN, VS_UNCLICKABLE, Viewport::width, and Viewport::zoom.

◆ CheckVehicleBreakdown()

void CheckVehicleBreakdown ( Vehicle v)

Definition at line 1318 of file vehicle.cpp.

◆ CountVehiclesInChain()

uint CountVehiclesInChain ( const Vehicle v)

Definition at line 703 of file vehicle.cpp.

◆ DecreaseVehicleValue()

void DecreaseVehicleValue ( Vehicle v)

◆ DoDrawVehicle()

◆ EconomyAgeVehicle()

◆ EnsureNoTrainOnTrackBits()

CommandCost EnsureNoTrainOnTrackBits ( TileIndex  tile,
TrackBits  track_bits 
)

Tests if a vehicle interacts with the specified track bits.

All track bits interact except parallel TRACK_BIT_HORZ or TRACK_BIT_VERT.

Parameters
tileThe tile.
track_bitsThe track bits.
Returns
true if no train that interacts, is found. false if a train is found.

Definition at line 608 of file vehicle.cpp.

References BaseVehicle::type, and VehicleFromPos().

Referenced by CmdConvertRail(), EnsureNoTrainOnTrack(), and ExploreSegment().

◆ EnsureNoTrainOnTrackProc()

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

Definition at line 588 of file vehicle.cpp.

◆ EnsureNoVehicleOnGround()

CommandCost EnsureNoVehicleOnGround ( TileIndex  tile)

◆ EnsureNoVehicleProcZ()

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

Callback that returns 'real' vehicles lower or at height *(int*)data .

Parameters
vVehicle to examine.
dataPointer to height data.
Returns
v if conditions are met, else nullptr.

Definition at line 531 of file vehicle.cpp.

References AIR_SHADOW, Vehicle::subtype, BaseVehicle::type, VEH_AIRCRAFT, VEH_DISASTER, and Vehicle::z_pos.

Referenced by EnsureNoVehicleOnGround().

◆ FindVehicleOnPos()

void FindVehicleOnPos ( TileIndex  tile,
void *  data,
VehicleFromPosProc *  proc 
)

Find a vehicle from a specific location.

It will call proc for ALL vehicles on the tile and YOU must make SURE that the "best one" is stored in the data value and is ALWAYS the same regardless of the order of the vehicles where proc was called on! When you fail to do this properly you create an almost untraceable DESYNC!

Note
The return value of proc will be ignored.
Use this function when you have the intention that all vehicles should be iterated over.
Parameters
tileThe location on the map
dataArbitrary data passed to proc.
procThe proc that determines whether a vehicle will be "found".

Definition at line 505 of file vehicle.cpp.

References VehicleFromPos().

Referenced by BuildDepotVehicleList(), CheckTrainCollision(), CmdConvertRail(), CmdConvertRoad(), DeleteLastWagon(), FloodVehicles(), FollowTrainReservation(), GetTrainForReservation(), RoadStop::Entry::Rebuild(), and RemoveRoadStop().

◆ FindVehicleOnPosXY()

void FindVehicleOnPosXY ( int  x,
int  y,
void *  data,
VehicleFromPosProc *  proc 
)

Find a vehicle from a specific location.

It will call proc for ALL vehicles on the tile and YOU must make SURE that the "best one" is stored in the data value and is ALWAYS the same regardless of the order of the vehicles where proc was called on! When you fail to do this properly you create an almost untraceable DESYNC!

Note
The return value of proc will be ignored.
Use this when you have the intention that all vehicles should be iterated over.
Parameters
xThe X location on the map
yThe Y location on the map
dataArbitrary data passed to proc
procThe proc that determines whether a vehicle will be "found".

Definition at line 445 of file vehicle.cpp.

References VehicleFromPosXY().

Referenced by CheckTrainCollision().

◆ GetDirectionTowards()

Direction GetDirectionTowards ( const Vehicle v,
int  x,
int  y 
)

Definition at line 1808 of file vehicle.cpp.

◆ GetEngineColourMap()

static PaletteID GetEngineColourMap ( EngineID  engine_type,
CompanyID  company,
EngineID  parent_engine_type,
const Vehicle v 
)
static

Definition at line 2093 of file vehicle.cpp.

◆ GetEngineLivery()

const Livery * GetEngineLivery ( EngineID  engine_type,
CompanyID  company,
EngineID  parent_engine_type,
const Vehicle v,
uint8_t  livery_setting 
)

Determines the livery for a vehicle.

Parameters
engine_typeEngineID of the vehicle
companyOwner of the vehicle
parent_engine_typeEngineID of the front vehicle. INVALID_VEHICLE if vehicle is at front itself.
vthe vehicle. nullptr if in purchase list etc.
livery_settingThe livery settings to use for acquiring the livery information.
Returns
livery to use

Definition at line 2064 of file vehicle.cpp.

References _local_company, Vehicle::First(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_group_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_company_pool >::Get(), GetEngineLiveryScheme(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_group_pool >::GetIfValid(), Vehicle::group_id, Livery::in_use, INVALID_GROUP, LIT_ALL, LIT_COMPANY, Group::livery, and Group::parent.

Referenced by LiveryHelper().

◆ GetEngineLiveryScheme()

◆ GetEnginePalette()

PaletteID GetEnginePalette ( EngineID  engine_type,
CompanyID  company 
)

Get the colour map for an engine.

This used for unbuilt engines in the user interface.

Parameters
engine_typeID of engine
companyID of company
Returns
A ready-to-use palette modifier

Definition at line 2142 of file vehicle.cpp.

References INVALID_ENGINE.

Referenced by DrawEngineList(), EnginePreviewWindow::DrawWidget(), and NewsWindow::DrawWidget().

◆ GetFreeUnitNumber()

UnitID GetFreeUnitNumber ( VehicleType  type)

◆ GetNewVehiclePos()

GetNewVehiclePosResult GetNewVehiclePos ( const Vehicle v)

◆ GetVehicleCannotUseStationReason()

StringID GetVehicleCannotUseStationReason ( const Vehicle v,
const Station st 
)

Get reason string why this station can't be used by the given vehicle.

Parameters
vThe vehicle to test.
stThe station to test for.
Returns
The string explaining why the vehicle cannot use the station.

Definition at line 3104 of file vehicle.cpp.

References AIR_CTOL, RoadVehicle::compatible_roadtypes, FACIL_AIRPORT, BaseStation::facilities, SpecializedVehicle< T, Type >::From(), Vehicle::GetEngine(), Vehicle::HasArticulatedPart(), HasTileAnyRoadType(), INVALID_STRING_ID, IsBayRoadStopTile(), RoadVehicle::IsBus(), RoadStop::next, ROADSTOP_BUS, ROADSTOP_TRUCK, RoadVehicle::roadtype, AircraftVehicleInfo::subtype, BaseVehicle::type, VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, VEH_TRAIN, and RoadStop::xy.

Referenced by CmdCloneOrder(), and CmdInsertOrder().

◆ GetVehiclePalette()

PaletteID GetVehiclePalette ( const Vehicle v)

Get the colour map for a vehicle.

Parameters
vVehicle to get colour map for
Returns
A ready-to-use palette modifier

Definition at line 2152 of file vehicle.cpp.

References Vehicle::engine_type, GroundVehicleCache::first_engine, Vehicle::GetGroundVehicleCache(), INVALID_ENGINE, Vehicle::IsGroundVehicle(), and Vehicle::owner.

Referenced by DoDrawVehicle(), DrawAircraftImage(), DrawRoadVehImage(), DrawShipImage(), DrawTrainDetails(), DrawTrainImage(), and SetMouseCursorVehicle().

◆ GetVehicleSet()

void GetVehicleSet ( VehicleSet &  set,
Vehicle v,
uint8_t  num_vehicles 
)

Calculates the set of vehicles that will be affected by a given selection.

Parameters
[in,out]setSet of affected vehicles.
vFirst vehicle of the selection.
num_vehiclesNumber of vehicles in the selection (not counting articulated parts).
Precondition
set must be empty.
Postcondition
set will contain the vehicles that will be refitted.

Definition at line 3218 of file vehicle.cpp.

References SpecializedVehicle< T, Type >::From(), SpecializedVehicle< T, Type >::GetFirstEnginePart(), include(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, Vehicle::IsArticulatedPart(), GroundVehicle< T, Type >::IsMultiheaded(), SpecializedVehicle< T, Type >::Next(), BaseVehicle::type, and VEH_TRAIN.

Referenced by RefitWindow::BuildRefitList(), RefitWindow::DrawWidget(), and RefitVehicle().

◆ GetVehicleTunnelBridgeProc()

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

Procedure called for every vehicle found in tunnel/bridge in the hash map.

Definition at line 560 of file vehicle.cpp.

References BaseVehicle::type, VEH_ROAD, VEH_SHIP, and VEH_TRAIN.

Referenced by TunnelBridgeIsFree().

◆ HasVehicleOnPos()

bool HasVehicleOnPos ( TileIndex  tile,
void *  data,
VehicleFromPosProc *  proc 
)

Checks whether a vehicle is on a specific location.

It will call proc for vehicles until it returns non-nullptr.

Note
Use FindVehicleOnPos when you have the intention that all vehicles should be iterated over.
Parameters
tileThe location on the map
dataArbitrary data passed to proc.
procThe proc that determines whether a vehicle will be "found".
Returns
True if proc returned non-nullptr.

Definition at line 520 of file vehicle.cpp.

References VehicleFromPos().

Referenced by CheckRoadBlockedForOvertaking(), ExploreSegment(), CYapfCostShipT< Types >::PfCalcCost(), TrainApproachingCrossing(), TrainController(), and TrainOnCrossing().

◆ HasVehicleOnPosXY()

bool HasVehicleOnPosXY ( int  x,
int  y,
void *  data,
VehicleFromPosProc *  proc 
)

Checks whether a vehicle in on a specific location.

It will call proc for vehicles until it returns non-nullptr.

Note
Use FindVehicleOnPosXY when you have the intention that all vehicles should be iterated over.
Parameters
xThe X location on the map
yThe Y location on the map
dataArbitrary data passed to proc
procThe proc that determines whether a vehicle will be "found".
Returns
True if proc returned non-nullptr.

Definition at line 461 of file vehicle.cpp.

References VehicleFromPosXY().

◆ InitializeVehicles()

void InitializeVehicles ( )

Definition at line 697 of file vehicle.cpp.

◆ PreviousOrderIsUnbunching()

static bool PreviousOrderIsUnbunching ( const Vehicle v)
static

Check if the previous order is a depot unbunching order.

Returns
true Iff the previous order is a depot order with the unbunch flag.

Definition at line 2501 of file vehicle.cpp.

References BaseConsist::cur_implicit_order_index, Order::GetDepotActionType(), Vehicle::GetFirstOrder(), Vehicle::GetLastOrder(), Vehicle::GetOrder(), Order::IsType(), and ODATFB_UNBUNCH.

Referenced by Vehicle::IsWaitingForUnbunching(), and Vehicle::LeaveUnbunchingDepot().

◆ ResetVehicleColourMap()

void ResetVehicleColourMap ( )

Definition at line 685 of file vehicle.cpp.

◆ ResetVehicleHash()

void ResetVehicleHash ( )

Definition at line 678 of file vehicle.cpp.

◆ RunEconomyVehicleDayProc()

static void RunEconomyVehicleDayProc ( )
static

◆ RunVehicleCalendarDayProc()

◆ ShowNewGrfVehicleError()

void ShowNewGrfVehicleError ( EngineID  engine,
StringID  part1,
StringID  part2,
GRFBugs  bug_type,
bool  critical 
)

Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.

Parameters
engineThe engine that caused the problem
part1Part 1 of the error message, taking the grfname as parameter 1
part2Part 2 of the error message, taking the engine as parameter 2
bug_typeFlag to check and set in grfconfig
criticalShall the "OpenTTD might crash"-message be shown when the player tries to unpause?

Definition at line 317 of file vehicle.cpp.

References _networking, DC_EXEC, Debug, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_engine_pool >::Get(), GetGRFConfig(), Engine::GetGRFID(), GRFConfig::GetName(), GetString(), GRFConfig::grf_bugs, HasBit(), PM_PAUSED_ERROR, PM_PAUSED_NORMAL, SetBit(), SetDParam(), SetDParamStr(), ShowErrorMessage(), StrMakeValid(), and WL_CRITICAL.

Referenced by CheckConsistencyOfArticulatedVehicle(), Train::ConsistChanged(), Vehicle::UpdateVisualEffect(), and VehicleLengthChanged().

◆ SpawnAdvancedVisualEffect()

◆ TunnelBridgeIsFree()

CommandCost TunnelBridgeIsFree ( TileIndex  tile,
TileIndex  endtile,
const Vehicle ignore 
)

Finds vehicle in tunnel / bridge.

Parameters
tilefirst end
endtilesecond end
ignoreIgnore this vehicle when searching
Returns
Succeeded command (if tunnel/bridge is free) or failed command (if a vehicle is using the tunnel/bridge).

Definition at line 575 of file vehicle.cpp.

References GetVehicleTunnelBridgeProc(), BaseVehicle::type, and VehicleFromPos().

Referenced by ClearPathReservation(), CmdBuildRoad(), CmdConvertRail(), CmdConvertRoad(), DoClearBridge(), DoClearTunnel(), and RemoveRoad().

◆ UpdateVehicleTileHash()

static void UpdateVehicleTileHash ( Vehicle v,
bool  remove 
)
static

Definition at line 619 of file vehicle.cpp.

◆ UpdateVehicleViewportHash()

static void UpdateVehicleViewportHash ( Vehicle v,
int  x,
int  y,
int  old_x,
int  old_y 
)
static

Definition at line 654 of file vehicle.cpp.

◆ VehicleEnterDepot()

void VehicleEnterDepot ( Vehicle v)

Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it, etc.

Parameters
vVehicle that entered a depot.

Definition at line 1552 of file vehicle.cpp.

References _current_company, _local_company, _settings_client, AddVehicleAdviceNewsItem(), CCF_ARRANGE, Clamp(), ClrBit(), Train::ConsistChanged(), TimerGameTick::counter, BaseConsist::cur_real_order_index, Vehicle::cur_speed, Vehicle::current_order, DC_EXEC, Vehicle::DeleteUnreachedImplicitOrders(), BaseConsist::depot_unbunching_last_departure, Vehicle::dest_tile, CommandCost::Failed(), Vehicle::First(), SpecializedVehicle< T, Type >::From(), SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), SpecializedVehicle< Ship, VEH_SHIP >::From(), CommandCost::GetCost(), Order::GetDepotActionType(), Order::GetDepotOrderType(), Order::GetDestination(), Vehicle::GetOrder(), Order::GetRefitCargo(), GetStationIndex(), ClientSettings::gui, HandleAircraftEnterHangar(), Vehicle::IncrementImplicitOrderIndex(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, INVALID_DIAGDIR, InvalidateWindowData(), Order::IsRefit(), Order::IsType(), Vehicle::last_loading_station, Order::MakeDummy(), Vehicle::MarkDirty(), MarkTileDirtyByTile(), AI::NewEvent(), ODATFB_HALT, ODATFB_NEAREST_DEPOT, ODATFB_UNBUNCH, ODTFB_PART_OF_ORDERS, Vehicle::owner, Vehicle::profit_this_year, BaseConsist::ResetDepotUnbunching(), Backup< T >::Restore(), BaseConsist::round_trip_time, SetDepotReservation(), SetDParam(), SetWindowClassesDirty(), SetWindowDirty(), GUISettings::show_track_reservation, ShowCostOrIncomeAnimation(), Ship::state, TFP_NONE, Vehicle::tile, TRACK_BIT_DEPOT, BaseVehicle::type, Ship::UpdateCache(), UpdateSignalsOnSegment(), UpdateVehicleTimetable(), SpecializedVehicle< T, Type >::UpdateViewport(), VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, VEH_TRAIN, VehicleServiceInDepot(), Vehicle::vehstatus, VRF_TOGGLE_REVERSE, VS_HIDDEN, Train::wait_counter, WC_AIRCRAFT_LIST, WC_ROADVEH_LIST, WC_SHIPS_LIST, WC_TRAINS_LIST, WC_VEHICLE_DEPOT, WC_VEHICLE_VIEW, Vehicle::x_pos, Vehicle::y_pos, and Vehicle::z_pos.

Referenced by AircraftEventHandler_EnterHangar(), AircraftEventHandler_InHangar(), CheckTrainStayInDepot(), and VehicleEnter_Track().

◆ VehicleEnteredDepotThisTick()

void VehicleEnteredDepotThisTick ( Vehicle v)

Adds a vehicle to the list of vehicles that visited a depot this tick.

Parameters
*vvehicle to add

Definition at line 921 of file vehicle.cpp.

References Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, Vehicle::vehstatus, and VS_STOPPED.

◆ VehicleEnterTile()

VehicleEnterTileStatus VehicleEnterTile ( Vehicle v,
TileIndex  tile,
int  x,
int  y 
)

Call the tile callback function for a vehicle entering a tile.

Parameters
vVehicle entering the tile
tileTile entered
xX position
yY position
Returns
Some meta-data over the to be entered tile.
See also
VehicleEnterTileStatus to see what the bits in the return value mean.

Definition at line 1838 of file vehicle.cpp.

References _tile_type_procs, GetTileType(), and TileTypeProcs::vehicle_enter_tile_proc.

Referenced by TrainController(), and UpdateStatusAfterSwap().

◆ VehicleFromPos()

static Vehicle * VehicleFromPos ( TileIndex  tile,
void *  data,
VehicleFromPosProc *  proc,
bool  find_first 
)
static

Helper function for FindVehicleOnPos/HasVehicleOnPos.

Note
Do not call this function directly!
Parameters
tileThe location on the map
dataArbitrary data passed to proc.
procThe proc that determines whether a vehicle will be "found".
find_firstWhether to return on the first found or iterate over all vehicles
Returns
the best matching or first vehicle (depending on find_first).

Definition at line 476 of file vehicle.cpp.

References GB(), Vehicle::hash_tile_next, Vehicle::tile, TileX(), and TileY().

Referenced by EnsureNoTrainOnTrackBits(), EnsureNoVehicleOnGround(), FindVehicleOnPos(), HasVehicleOnPos(), and TunnelBridgeIsFree().

◆ VehicleFromPosXY()

static Vehicle * VehicleFromPosXY ( int  x,
int  y,
void *  data,
VehicleFromPosProc *  proc,
bool  find_first 
)
static

Helper function for FindVehicleOnPos/HasVehicleOnPos.

Note
Do not call this function directly!
Parameters
xThe X location on the map
yThe Y location on the map
dataArbitrary data passed to proc
procThe proc that determines whether a vehicle will be "found".
find_firstWhether to return on the first found or iterate over all vehicles
Returns
the best matching or first vehicle (depending on find_first).

Definition at line 418 of file vehicle.cpp.

References GB(), and TILE_SIZE.

Referenced by FindVehicleOnPosXY(), and HasVehicleOnPosXY().

◆ VehicleFromTileHash()

static Vehicle * VehicleFromTileHash ( int  xl,
int  yl,
int  xu,
int  yu,
void *  data,
VehicleFromPosProc *  proc,
bool  find_first 
)
static

Definition at line 389 of file vehicle.cpp.

◆ VehicleLengthChanged()

void VehicleLengthChanged ( const Vehicle u)

Logs a bug in GRF and shows a warning message if this is for the first time this happened.

Parameters
ufirst vehicle of chain

Definition at line 346 of file vehicle.cpp.

References _gamelog, Vehicle::engine_type, GBUG_VEH_LENGTH, Vehicle::GetEngine(), GetGRFConfig(), GRFConfig::grf_bugs, Engine::grf_prop, Gamelog::GRFBugReverse(), GRFFilePropsBase< Tcnt >::grfid, HasBit(), GRFFilePropsBase< Tcnt >::local_id, and ShowNewGrfVehicleError().

Referenced by Train::ConsistChanged(), and RoadVehUpdateCache().

◆ VehicleServiceInDepot()

◆ VehiclesHaveSameEngineList()

bool VehiclesHaveSameEngineList ( const Vehicle v1,
const Vehicle v2 
)

Checks if two vehicle chains have the same list of engines.

Parameters
v1First vehicle chain.
v1Second vehicle chain.
Returns
True if same, false if different.

Definition at line 3272 of file vehicle.cpp.

References Vehicle::GetEngine(), and Vehicle::GetNextVehicle().

Referenced by DepotWindow::OnVehicleSelect().

◆ VehiclesHaveSameOrderList()

bool VehiclesHaveSameOrderList ( const Vehicle v1,
const Vehicle v2 
)

Checks if two vehicles have the same list of orders.

Parameters
v1First vehicles.
v1Second vehicles.
Returns
True if same, false if different.

Definition at line 3289 of file vehicle.cpp.

References Order::Equals(), Vehicle::GetFirstOrder(), and Order::next.

Referenced by DepotWindow::OnVehicleSelect(), and OrdersWindow::OnVehicleSelect().

◆ ViewportAddVehicles()

Variable Documentation

◆ _breakdown_chance

const uint8_t _breakdown_chance[64]
static
Initial value:
= {
3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 5, 5, 6, 6, 7, 7,
8, 8, 9, 9, 10, 10, 11, 11,
12, 13, 13, 13, 13, 14, 15, 16,
17, 19, 21, 25, 28, 31, 34, 37,
40, 44, 48, 52, 56, 60, 64, 68,
72, 80, 90, 100, 110, 120, 130, 140,
150, 170, 190, 210, 230, 250, 250, 250,
}

Definition at line 1307 of file vehicle.cpp.

◆ _new_direction_table

const Direction _new_direction_table[]
static
Initial value:
= {
}
@ DIR_SW
Southwest.
@ DIR_NW
Northwest.
@ DIR_N
North.
@ DIR_SE
Southeast.
@ DIR_S
South.
@ DIR_NE
Northeast.
@ DIR_W
West.
@ DIR_E
East.

Definition at line 1802 of file vehicle.cpp.

◆ _vehicle_smoke_pos

const int8_t _vehicle_smoke_pos[8]
static
Initial value:
= {
1, 1, 1, 0, -1, -1, -1, 0
}

Definition at line 2724 of file vehicle.cpp.

◆ _vehicle_tile_hash

Vehicle* _vehicle_tile_hash[TOTAL_HASH_SIZE]
static

Definition at line 387 of file vehicle.cpp.

◆ _vehicle_viewport_hash

Vehicle* _vehicle_viewport_hash[1<<(GEN_HASHX_BITS+GEN_HASHY_BITS)]
static

Definition at line 652 of file vehicle.cpp.

◆ _vehicles_to_autoreplace

AutoreplaceMap _vehicles_to_autoreplace
static

Definition at line 695 of file vehicle.cpp.

◆ GEN_HASHX_BITS

const uint GEN_HASHX_BITS = 6
static

Definition at line 69 of file vehicle.cpp.

◆ GEN_HASHX_BUCKET_BITS

const uint GEN_HASHX_BUCKET_BITS = 7
static

Definition at line 73 of file vehicle.cpp.

◆ GEN_HASHX_INC

const int GEN_HASHX_INC = 1
static

Definition at line 86 of file vehicle.cpp.

◆ GEN_HASHX_MASK

const uint GEN_HASHX_MASK = (1 << GEN_HASHX_BITS) - 1
static

Definition at line 90 of file vehicle.cpp.

◆ GEN_HASHX_SIZE

const int GEN_HASHX_SIZE = 1 << (GEN_HASHX_BUCKET_BITS + GEN_HASHX_BITS + ZOOM_BASE_SHIFT)
static

Definition at line 82 of file vehicle.cpp.

◆ GEN_HASHY_BITS

const uint GEN_HASHY_BITS = 6
static

Definition at line 70 of file vehicle.cpp.

◆ GEN_HASHY_BUCKET_BITS

const uint GEN_HASHY_BUCKET_BITS = 6
static

Definition at line 74 of file vehicle.cpp.

◆ GEN_HASHY_INC

const int GEN_HASHY_INC = 1 << GEN_HASHX_BITS
static

Definition at line 87 of file vehicle.cpp.

◆ GEN_HASHY_MASK

const uint GEN_HASHY_MASK = ((1 << GEN_HASHY_BITS) - 1) << GEN_HASHX_BITS
static

Definition at line 91 of file vehicle.cpp.

◆ GEN_HASHY_SIZE

const int GEN_HASHY_SIZE = 1 << (GEN_HASHY_BUCKET_BITS + GEN_HASHY_BITS + ZOOM_BASE_SHIFT)
static

Definition at line 83 of file vehicle.cpp.

◆ HASH_BITS

const int HASH_BITS = 7

Definition at line 377 of file vehicle.cpp.

◆ HASH_MASK

const int HASH_MASK = HASH_SIZE - 1

Definition at line 379 of file vehicle.cpp.

◆ HASH_RES

const int HASH_RES = 0

Definition at line 385 of file vehicle.cpp.

◆ HASH_SIZE

const int HASH_SIZE = 1 << HASH_BITS

Definition at line 378 of file vehicle.cpp.

◆ TOTAL_HASH_MASK

const int TOTAL_HASH_MASK = TOTAL_HASH_SIZE - 1

Definition at line 381 of file vehicle.cpp.

◆ TOTAL_HASH_SIZE

const int TOTAL_HASH_SIZE = 1 << (HASH_BITS * 2)

Definition at line 380 of file vehicle.cpp.