OpenTTD Source 20260311-master-g511d3794ce
train.h
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#ifndef TRAIN_H
11#define TRAIN_H
12
13#include "core/enum_type.hpp"
14
15#include "newgrf_engine.h"
16#include "cargotype.h"
17#include "rail.h"
18#include "engine_base.h"
19#include "rail_map.h"
20#include "ground_vehicle.hpp"
21
22struct Train;
23
35
37
39enum TrainForceProceeding : uint8_t {
43};
44
46enum class ConsistChangeFlag : uint8_t {
49};
50
52
53static constexpr ConsistChangeFlags CCF_TRACK{};
59
61
63
64void FreeTrainTrackReservation(const Train *v);
65bool TryPathReserve(Train *v, bool mark_as_stuck = false, bool first_tile_okay = false);
66
67int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length);
68
69void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type);
70
72void NormalizeTrainVehInDepot(const Train *u);
73
75struct TrainCache {
77 const struct SpriteGroup *cached_override = nullptr;
78
79 /* cached values, recalculated on load and each time a vehicle is added to/removed from the consist. */
80 bool cached_tilt = false;
81 uint8_t user_def_data = 0;
82
85
91 auto operator<=>(const TrainCache &other) const = default;
92};
93
97struct Train final : public GroundVehicle<Train, VEH_TRAIN> {
99 uint16_t crash_anim_pos = 0;
100 uint16_t wait_counter = 0;
101
103
106
109
112
116 ~Train() override { this->PreDestructor(); }
117
118 friend struct GroundVehicle<Train, VEH_TRAIN>; // GroundVehicle needs to use the acceleration functions defined at Train.
119
120 void MarkDirty() override;
121 void UpdateDeltaXY() override;
122 ExpensesType GetExpenseType(bool income) const override { return income ? EXPENSES_TRAIN_REVENUE : EXPENSES_TRAIN_RUN; }
123 void PlayLeaveStationSound(bool force = false) const override;
124 bool IsPrimaryVehicle() const override { return this->IsFrontEngine(); }
125 void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override;
126 int GetDisplaySpeed() const override { return this->gcache.last_speed; }
127 int GetDisplayMaxSpeed() const override { return this->vcache.cached_max_speed; }
128 Money GetRunningCost() const override;
129 int GetCursorImageOffset() const;
130 int GetDisplayImageWidth(Point *offset = nullptr) const;
131 bool IsInDepot() const override { return this->track == TRACK_BIT_DEPOT; }
132 bool Tick() override;
133 void OnNewCalendarDay() override;
134 void OnNewEconomyDay() override;
135 uint Crash(bool flooded = false) override;
136 Trackdir GetVehicleTrackdir() const override;
137 TileIndex GetOrderStationLocation(StationID station) override;
139
140 void ReserveTrackUnderConsist() const;
141
142 uint16_t GetCurveSpeedLimit() const;
143
144 void ConsistChanged(ConsistChangeFlags allowed_changes);
145
146 int UpdateSpeed();
147
148 void UpdateAcceleration();
149
150 int GetCurrentMaxSpeed() const override;
151
156 inline Train *GetNextUnit() const
157 {
158 Train *v = this->GetNextVehicle();
159 if (v != nullptr && v->IsRearDualheaded()) v = v->GetNextVehicle();
160
161 return v;
162 }
163
169 {
170 Train *v = this->GetPrevVehicle();
171 if (v != nullptr && v->IsRearDualheaded()) v = v->GetPrevVehicle();
172
173 return v;
174 }
175
181 {
182 /* For vehicles with odd lengths the part before the center will be one unit
183 * longer than the part after the center. This means we have to round up the
184 * length of the next vehicle but may not round the length of the current
185 * vehicle. */
186 return this->gcache.cached_veh_length / 2 + (this->Next() != nullptr ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
187 }
188
197
198protected: // These functions should not be called outside acceleration code.
199
204 inline uint16_t GetPower() const
205 {
206 /* Power is not added for articulated parts */
207 if (!this->IsArticulatedPart() && HasPowerOnRail(this->railtypes, GetRailType(this->tile))) {
208 uint16_t power = GetVehicleProperty(this, PROP_TRAIN_POWER, RailVehInfo(this->engine_type)->power);
209 /* Halve power for multiheaded parts */
210 if (this->IsMultiheaded()) power /= 2;
211 return power;
212 }
213
214 return 0;
215 }
216
221 inline uint16_t GetPoweredPartPower() const
222 {
223 /* For powered wagons the engine defines the type of engine (i.e. railtype) */
224 if (this->flags.Test(VehicleRailFlag::PoweredWagon) && HasPowerOnRail(this->railtypes, GetRailType(this->tile))) {
225 return RailVehInfo(this->gcache.first_engine)->pow_wag_power;
226 }
227
228 return 0;
229 }
230
235 inline uint16_t GetWeight() const
236 {
237 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnitsInTrain(this->cargo.StoredCount());
238
239 /* Vehicle weight is not added for articulated parts. */
240 if (!this->IsArticulatedPart()) {
241 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
242 }
243
244 /* Powered wagons have extra weight added. */
245 if (this->flags.Test(VehicleRailFlag::PoweredWagon)) {
246 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
247 }
248
249 return weight;
250 }
251
256 uint16_t GetMaxWeight() const override;
257
262 inline uint8_t GetTractiveEffort() const
263 {
264 return GetVehicleProperty(this, PROP_TRAIN_TRACTIVE_EFFORT, RailVehInfo(this->engine_type)->tractive_effort);
265 }
266
271 inline uint8_t GetAirDragArea() const
272 {
273 /* Air drag is higher in tunnels due to the limited cross-section. */
274 return (this->track == TRACK_BIT_WORMHOLE && this->vehstatus.Test(VehState::Hidden)) ? 28 : 14;
275 }
276
281 inline uint8_t GetAirDrag() const
282 {
283 return RailVehInfo(this->engine_type)->air_drag;
284 }
285
294
299 inline uint16_t GetCurrentSpeed() const
300 {
301 return this->cur_speed;
302 }
303
308 inline uint32_t GetRollingFriction() const
309 {
310 /* Rolling friction for steel on steel is between 0.1% and 0.2%.
311 * The friction coefficient increases with speed in a way that
312 * it doubles at 512 km/h, triples at 1024 km/h and so on. */
313 return 15 * (512 + this->GetCurrentSpeed()) / 512;
314 }
315
320 inline uint32_t GetSlopeSteepness() const
321 {
322 return _settings_game.vehicle.train_slope_steepness;
323 }
324
329 inline uint16_t GetMaxTrackSpeed() const
330 {
332 }
333
338 inline int16_t GetCurveSpeedModifier() const
339 {
340 return GetVehicleProperty(this, PROP_TRAIN_CURVE_SPEED_MOD, RailVehInfo(this->engine_type)->curve_speed_mod, true);
341 }
342
347 inline bool TileMayHaveSlopedTrack() const
348 {
349 /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped. */
350 return this->track == TRACK_BIT_X || this->track == TRACK_BIT_Y;
351 }
352
359 {
360 return false;
361 }
362};
363
364#endif /* TRAIN_H */
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:21
Types/functions related to cargoes.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Enum-as-bit-set wrapper.
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition rail.h:220
VehicleAccelerationModel acceleration_type
Acceleration type of this rail type.
Definition rail.h:215
Direction
Defines the 8 directions on the map.
ExpensesType
Types of expenses.
@ EXPENSES_TRAIN_RUN
Running costs trains.
@ EXPENSES_TRAIN_REVENUE
Revenue from trains.
Base class for engines.
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:26
VehicleAccelerationModel
Acceleration model of a vehicle.
Definition engine_type.h:47
Type (helpers) for enums.
Base class and functions for all vehicles that move through ground.
AccelStatus
What is the status of our acceleration?
@ AS_BRAKE
We want to stop.
@ AS_ACCEL
We want to go faster, if possible of course.
#define Point
Macro that prevents name conflicts between included headers.
Functions for NewGRF engines.
@ PROP_TRAIN_CURVE_SPEED_MOD
Modifier to maximum speed in curves.
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle).
@ PROP_TRAIN_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
@ PROP_TRAIN_POWER
Power in hp (if dualheaded: sum of both vehicles).
Rail specific functions.
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition rail.h:377
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:301
Hides the direct accesses to the map array with map accessors.
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
EnumBitSet< RailType, uint64_t > RailTypes
Allow incrementing of Track variables.
Definition rail_type.h:38
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:138
Structure to return information about the closest depot location, and whether it could be found.
uint8_t cached_veh_length
Length of this vehicle in units of 1/VEHICLE_LENGTH of normal length. It is cached because this can b...
Base class for all vehicles that move through ground.
GroundVehicle< Train, Type > GroundVehicleBase
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Common wrapper for all the different sprite group types.
Variables that are cached to improve performance and such.
Definition train.h:75
uint16_t cached_max_curve_speed
max consist speed limited by curves
Definition train.h:84
auto operator<=>(const TrainCache &other) const =default
Compare variables with another instance of this class.
const struct SpriteGroup * cached_override
Cached wagon override spritegroup.
Definition train.h:77
int16_t cached_curve_speed_mod
curve speed modifier of the entire train
Definition train.h:83
uint8_t user_def_data
Cached property 0x25. Can be set by Callback 0x36.
Definition train.h:81
bool cached_tilt
train can tilt; feature provides a bonus in curves
Definition train.h:80
'Train' is either a loco or a wagon.
Definition train.h:97
void PlayLeaveStationSound(bool force=false) const override
Play the sound associated with leaving the station.
bool IsInDepot() const override
Check whether the vehicle is in the depot.
Definition train.h:131
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
void OnNewCalendarDay() override
Calendar day handler.
Train * GetNextUnit() const
Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consis...
Definition train.h:156
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
~Train() override
We want to 'destruct' the right class.
Definition train.h:116
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Get the sprite to display the train.
Train * other_multiheaded_part
Link between the two ends of a multiheaded engine.
Definition train.h:105
RailTypes railtypes
On which rail types the train can run.
Definition train.h:108
int GetDisplayMaxSpeed() const override
Gets the maximum speed in km-ish/h that can be sent into string parameters for string processing.
Definition train.h:127
uint16_t crash_anim_pos
Crash animation counter.
Definition train.h:99
uint8_t GetTractiveEffort() const
Allows to know the tractive effort value that this vehicle will use.
Definition train.h:262
bool Tick() override
Update train vehicle data for a tick.
bool HasToUseGetSlopePixelZ()
Trains can always use the faster algorithm because they have always the same direction as the track u...
Definition train.h:358
uint16_t GetCurrentSpeed() const
Calculates the current speed of this vehicle.
Definition train.h:299
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
TileIndex GetOrderStationLocation(StationID station) override
Get the location of the next station to visit.
Train * GetPrevUnit()
Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the co...
Definition train.h:168
TrainForceProceeding force_proceed
How the train should behave when it encounters next obstacle.
Definition train.h:111
uint32_t GetRollingFriction() const
Returns the rolling friction coefficient of this vehicle.
Definition train.h:308
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
TrackBits track
On which track the train currently is.
Definition train.h:110
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
uint16_t GetMaxTrackSpeed() const
Gets the maximum speed allowed by the track for this vehicle.
Definition train.h:329
VehicleRailFlags flags
Which flags has this train currently set.
Definition train.h:98
int CalcNextVehicleOffset() const
Calculate the offset from this vehicle's center to the following center taking the vehicle lengths in...
Definition train.h:180
uint16_t GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
uint16_t GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
uint8_t GetAirDrag() const
Gets the air drag coefficient of this vehicle.
Definition train.h:281
bool IsPrimaryVehicle() const override
Whether this is the primary vehicle in the chain.
Definition train.h:124
void MarkDirty() override
Goods at the consist have changed, update the graphics, cargo, and acceleration.
int GetDisplaySpeed() const override
Gets the speed in km-ish/h that can be sent into string parameters for string processing.
Definition train.h:126
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
uint Crash(bool flooded=false) override
The train vehicle crashed!
VehicleAccelerationModel GetAccelerationType() const
Allows to know the acceleration type of a vehicle.
Definition train.h:193
Train(VehicleID index)
Create new Train object.
Definition train.h:114
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition train.h:290
TrainCache tcache
Set of cached variables, recalculated on load and each time a vehicle is added to/removed from the co...
Definition train.h:102
void OnNewEconomyDay() override
Economy day handler.
int16_t GetCurveSpeedModifier() const
Returns the curve speed modifier of this vehicle.
Definition train.h:338
bool TileMayHaveSlopedTrack() const
Checks if the vehicle is at a tile that can be sloped.
Definition train.h:347
int GetCursorImageOffset() const
Get the offset for train image when it is used as cursor.
uint16_t GetWeight() const
Allows to know the weight value that this vehicle will use.
Definition train.h:235
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
ExpensesType GetExpenseType(bool income) const override
Sets the expense type associated to this vehicle type.
Definition train.h:122
uint16_t GetPoweredPartPower() const
Returns a value if this articulated part is powered.
Definition train.h:221
Money GetRunningCost() const override
Get running cost for the train consist.
RailTypes compatible_railtypes
With which rail types the train is compatible.
Definition train.h:107
uint8_t GetAirDragArea() const
Gets the area used for calculating air drag.
Definition train.h:271
uint16_t GetPower() const
Allows to know the power value that this vehicle will use.
Definition train.h:204
uint16_t wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition train.h:100
uint32_t GetSlopeSteepness() const
Returns the slope steepness used by this vehicle.
Definition train.h:320
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
Sprite sequence for a vehicle part.
EngineID engine_type
The type of engine used for this vehicle.
Direction direction
facing
VehicleCargoList cargo
The cargo this vehicle is carrying.
VehStates vehstatus
Status.
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
CargoType cargo_type
type of cargo this vehicle is carrying
void PreDestructor()
Destroy all stuff that (still) needs the virtual functions to work properly.
Definition vehicle.cpp:825
VehicleCache vcache
Cache of often used vehicle values.
uint16_t cur_speed
current speed
bool IsFrontEngine() const
Check if the vehicle is a front engine.
TileIndex tile
Current tile index.
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
TrackBits
Allow incrementing of Track variables.
Definition track_type.h:35
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels).
Definition track_type.h:52
@ TRACK_BIT_DEPOT
Bitflag for a depot.
Definition track_type.h:53
@ TRACK_BIT_Y
Y-axis track.
Definition track_type.h:38
@ TRACK_BIT_X
X-axis track.
Definition track_type.h:37
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:66
ConsistChangeFlag
Flags for Train::ConsistChanged.
Definition train.h:46
@ Capacity
Allow vehicles to change capacity.
Definition train.h:48
@ Length
Allow vehicles to change length.
Definition train.h:47
EnumBitSet< ConsistChangeFlag, uint8_t > ConsistChangeFlags
Bitset of the ConsistChangeFlag elements.
Definition train.h:51
static constexpr ConsistChangeFlags CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
Definition train.h:53
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
static constexpr ConsistChangeFlags CCF_SAVELOAD
Valid changes when loading a savegame. (Everything that is not stored in the save....
Definition train.h:58
void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
uint8_t FreightWagonMult(CargoType cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition train_cmd.cpp:68
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
static constexpr ConsistChangeFlags CCF_LOADUNLOAD
Valid changes while vehicle is loading/unloading.
Definition train.h:54
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition train_cmd.cpp:75
bool TrainOnCrossing(TileIndex tile)
Check if a level crossing tile has a train on it.
VehicleRailFlag
Rail vehicle flags.
Definition train.h:25
@ Reversed
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition train.h:31
@ LeavingStation
Train is just leaving a station.
Definition train.h:33
@ PoweredWagon
Wagon is powered.
Definition train.h:27
@ Reversing
Train is slowing down to reverse.
Definition train.h:26
@ Stuck
Train can't get a path reservation.
Definition train.h:32
@ AllowedOnNormalRail
Electric train engine is allowed to run on normal rail. *‍/.
Definition train.h:30
@ Flipped
Reverse the visible direction of the vehicle.
Definition train.h:28
EnumBitSet< VehicleRailFlag, uint16_t > VehicleRailFlags
Bitset of the VehicleRailFlag elements.
Definition train.h:36
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.
TrainForceProceeding
Modes for ignoring signals.
Definition train.h:39
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
Definition train.h:42
@ TFP_NONE
Normal operation.
Definition train.h:40
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition train.h:41
static constexpr ConsistChangeFlags CCF_REFIT
Valid changes for refitting in a depot.
Definition train.h:56
static constexpr ConsistChangeFlags CCF_AUTOREFIT
Valid changes for autorefitting in stations.
Definition train.h:55
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 constexpr ConsistChangeFlags CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Definition train.h:57
@ Hidden
Vehicle is not visible.
@ Stopped
Vehicle is stopped by the player.
EngineImageType
Visualisation contexts of vehicles and engines.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
@ VEH_TRAIN
Train vehicle type.