4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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 <http://www.gnu.org/licenses/>.
10 /** @file train.h Base for the train class. */
15 #include "newgrf_engine.h"
16 #include "cargotype.h"
18 #include "engine_base.h"
20 #include "ground_vehicle.hpp"
21 #include "pathfinder/pos.h"
25 /** Rail vehicle flags. */
26 enum VehicleRailFlags
{
28 VRF_POWEREDWAGON
= 3, ///< Wagon is powered.
29 VRF_REVERSE_DIRECTION
= 4, ///< Reverse the visible direction of the vehicle.
31 VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL
= 6, ///< Electric train engine is allowed to run on normal rail. */
32 VRF_TOGGLE_REVERSE
= 7, ///< Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle only).
33 VRF_TRAIN_STUCK
= 8, ///< Train can't get a path reservation.
34 VRF_LEAVING_STATION
= 9, ///< Train is just leaving a station.
37 /** Modes for ignoring signals. */
38 enum TrainForceProceeding
{
39 TFP_NONE
= 0, ///< Normal operation.
40 TFP_STUCK
= 1, ///< Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
41 TFP_SIGNAL
= 2, ///< Ignore next signal, after the signal ignore being stuck.
43 typedef SimpleTinyEnumT
<TrainForceProceeding
, byte
> TrainForceProceedingByte
;
45 byte
FreightWagonMult(CargoID cargo
);
47 void CheckTrainsLengths();
49 void FreeTrainTrackReservation(const Train
*v
);
50 bool TryPathReserve(Train
*v
, bool mark_as_stuck
= false, bool first_tile_okay
= false);
52 int GetTrainStopLocation(StationID station_id
, TileIndex tile
, const Train
*v
, int *station_ahead
, int *station_length
);
54 void GetTrainSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
);
56 /** Variables that are cached to improve performance and such */
58 /* Cached wagon override spritegroup */
59 const struct SpriteGroup
*cached_override
;
61 /* cached values, recalculated on load and each time a vehicle is added to/removed from the consist. */
62 bool cached_tilt
; ///< train can tilt; feature provides a bonus in curves
64 byte user_def_data
; ///< Cached property 0x25. Can be set by Callback 0x36.
66 /* cached max. speed / acceleration data */
67 int cached_max_curve_speed
; ///< max consist speed limited by curves
71 * 'Train' is either a loco or a wagon.
73 struct Train FINAL
: public GroundVehicle
<Train
, VEH_TRAIN
> {
76 /* Link between the two ends of a multiheaded engine */
77 Train
*other_multiheaded_part
;
79 uint16 crash_anim_pos
; ///< Crash animation counter.
82 TrackdirByte trackdir
;
83 TrainForceProceedingByte force_proceed
;
84 RailTypeByte railtype
;
85 RailTypes compatible_railtypes
;
87 /** Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through signals. */
90 /** We don't want GCC to zero our struct! It already is zeroed and has an index! */
91 Train() : GroundVehicleBase() {}
92 /** We want to 'destruct' the right class. */
93 virtual ~Train() { this->PreDestructor(); }
95 friend struct GroundVehicle
<Train
, VEH_TRAIN
>; // GroundVehicle needs to use the acceleration functions defined at Train.
98 void UpdateDeltaXY(Direction direction
);
99 ExpensesType
GetExpenseType(bool income
) const { return income
? EXPENSES_TRAIN_INC
: EXPENSES_TRAIN_RUN
; }
100 void PlayLeaveStationSound() const;
101 bool IsPrimaryVehicle() const { return this->IsFrontEngine(); }
102 SpriteID
GetImage(Direction direction
, EngineImageType image_type
) const;
103 int GetDisplaySpeed() const { return this->gcache
.last_speed
; }
104 int GetDisplayMaxSpeed() const { return this->vcache
.cached_max_speed
; }
105 Money
GetRunningCost() const;
106 int GetDisplayImageWidth(Point
*offset
= NULL
) const;
107 bool IsInDepot() const { return this->trackdir
== TRACKDIR_DEPOT
; }
110 uint
Crash(bool flooded
= false);
111 Trackdir
GetTrackdir() const;
112 RailPathPos
GetPos() const;
113 RailPathPos
GetReversePos() const;
114 TileIndex
GetOrderStationLocation(StationID station
);
115 bool FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
);
117 void ReserveTrackUnderConsist() const;
119 int GetCurveSpeedLimit() const;
121 void ConsistChanged(bool same_length
);
125 void UpdateAcceleration();
127 int GetCurrentMaxSpeed() const;
130 * Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consist.
131 * @return Next vehicle in the consist.
133 inline Train
*GetNextUnit() const
135 Train
*v
= this->GetNextVehicle();
136 if (v
!= NULL
&& v
->IsRearDualheaded()) v
= v
->GetNextVehicle();
142 * Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the consist.
143 * @return Previous vehicle in the consist.
145 inline Train
*GetPrevUnit()
147 Train
*v
= this->GetPrevVehicle();
148 if (v
!= NULL
&& v
->IsRearDualheaded()) v
= v
->GetPrevVehicle();
154 * Calculate the offset from this vehicle's center to the following center taking the vehicle lengths into account.
155 * @return Offset from center to center.
157 int CalcNextVehicleOffset() const
159 /* For vehicles with odd lengths the part before the center will be one unit
160 * longer than the part after the center. This means we have to round up the
161 * length of the next vehicle but may not round the length of the current
163 return this->gcache
.cached_veh_length
/ 2 + (this->Next() != NULL
? this->Next()->gcache
.cached_veh_length
+ 1 : 0) / 2;
167 * Get the railtype the vehicle is currently running on.
168 * @return The railtype under the vehicle
170 inline RailType
GetTrackRailType() const
172 return !IsRailwayTile(this->tile
) ? GetRailType(this->tile
) :
173 (this->trackdir
== TRACKDIR_WORMHOLE
) ? GetBridgeRailType(this->tile
) :
174 GetRailType(this->tile
, TrackdirToTrack(this->trackdir
));
177 protected: // These functions should not be called outside acceleration code.
180 * Allows to know the power value that this vehicle will use.
181 * @return Power value from the engine in HP, or zero if the vehicle is not powered.
183 inline uint16
GetPower() const
185 /* Power is not added for articulated parts */
186 if (!this->IsArticulatedPart() && HasPowerOnRail(this->railtype
, this->GetTrackRailType())) {
187 uint16 power
= GetVehicleProperty(this, PROP_TRAIN_POWER
, RailVehInfo(this->engine_type
)->power
);
188 /* Halve power for multiheaded parts */
189 if (this->IsMultiheaded()) power
/= 2;
197 * Returns a value if this articulated part is powered.
198 * @return Power value from the articulated part in HP, or zero if it is not powered.
200 inline uint16
GetPoweredPartPower(const Train
*head
) const
202 /* For powered wagons the engine defines the type of engine (i.e. railtype) */
203 if (HasBit(this->flags
, VRF_POWEREDWAGON
) && HasPowerOnRail(head
->railtype
, this->GetTrackRailType())) {
204 return RailVehInfo(this->gcache
.first_engine
)->pow_wag_power
;
211 * Allows to know the weight value that this vehicle will use.
212 * @return Weight value from the engine in tonnes.
214 inline uint16
GetWeight() const
216 uint16 weight
= (CargoSpec::Get(this->cargo_type
)->weight
* this->cargo
.StoredCount() * FreightWagonMult(this->cargo_type
)) / 16;
218 /* Vehicle weight is not added for articulated parts. */
219 if (!this->IsArticulatedPart()) {
220 weight
+= GetVehicleProperty(this, PROP_TRAIN_WEIGHT
, RailVehInfo(this->engine_type
)->weight
);
223 /* Powered wagons have extra weight added. */
224 if (HasBit(this->flags
, VRF_POWEREDWAGON
)) {
225 weight
+= RailVehInfo(this->gcache
.first_engine
)->pow_wag_weight
;
232 * Allows to know the tractive effort value that this vehicle will use.
233 * @return Tractive effort value from the engine.
235 inline byte
GetTractiveEffort() const
237 return GetVehicleProperty(this, PROP_TRAIN_TRACTIVE_EFFORT
, RailVehInfo(this->engine_type
)->tractive_effort
);
241 * Gets the area used for calculating air drag.
242 * @return Area of the engine in m^2.
244 inline byte
GetAirDragArea() const
246 /* Air drag is higher in tunnels due to the limited cross-section. */
247 return (this->trackdir
== TRACKDIR_WORMHOLE
&& this->vehstatus
& VS_HIDDEN
) ? 28 : 14;
251 * Gets the air drag coefficient of this vehicle.
252 * @return Air drag value from the engine.
254 inline byte
GetAirDrag() const
256 return RailVehInfo(this->engine_type
)->air_drag
;
260 * Checks the current acceleration status of this vehicle.
261 * @return Acceleration status.
263 inline AccelStatus
GetAccelerationStatus() const
265 return (this->vehstatus
& VS_STOPPED
) || HasBit(this->flags
, VRF_REVERSING
) || HasBit(this->flags
, VRF_TRAIN_STUCK
) ? AS_BRAKE
: AS_ACCEL
;
269 * Calculates the current speed of this vehicle.
270 * @return Current speed in km/h-ish.
272 inline uint16
GetCurrentSpeed() const
274 return this->cur_speed
;
278 * Returns the rolling friction coefficient of this vehicle.
279 * @return Rolling friction coefficient in [1e-4].
281 inline uint32
GetRollingFriction() const
283 /* Rolling friction for steel on steel is between 0.1% and 0.2%.
284 * The friction coefficient increases with speed in a way that
285 * it doubles at 512 km/h, triples at 1024 km/h and so on. */
286 return 15 * (512 + this->GetCurrentSpeed()) / 512;
290 * Allows to know the acceleration type of a vehicle.
291 * @return Acceleration type of the vehicle.
293 inline int GetAccelerationType() const
295 return GetRailTypeInfo(this->railtype
)->acceleration_type
;
299 * Returns the slope steepness used by this vehicle.
300 * @return Slope steepness used by the vehicle.
302 inline uint32
GetSlopeSteepness() const
304 return _settings_game
.vehicle
.train_slope_steepness
;
308 * Gets the maximum speed allowed by the track for this vehicle.
309 * @return Maximum speed allowed.
311 inline uint16
GetMaxTrackSpeed() const
313 return GetRailTypeInfo(this->GetTrackRailType())->max_speed
;
317 * Checks if the vehicle is at a tile that can be sloped.
318 * @return True if the tile can be sloped.
320 inline bool TileMayHaveSlopedTrack() const
322 /* Any track that isn't TRACK_X or TRACK_Y cannot be sloped. */
323 return IsDiagonalTrackdir(this->trackdir
);
327 * Trains can always use the faster algorithm because they
328 * have always the same direction as the track under them.
331 inline bool HasToUseGetSlopePixelZ()
337 #define FOR_ALL_TRAINS(var) FOR_ALL_VEHICLES_OF_TYPE(Train, var)