Move dual-use of load_unload_ticks for bridge/tun signals to new field
[openttd-joker.git] / src / train.h
blob054a120a3d07014640dd824f0c31074de4037836
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file train.h Base for the train class. */
12 #ifndef TRAIN_H
13 #define TRAIN_H
15 #include "core/enum_type.hpp"
17 #include "newgrf_engine.h"
18 #include "cargotype.h"
19 #include "rail.h"
20 #include "engine_base.h"
21 #include "rail_map.h"
22 #include "ground_vehicle.hpp"
24 struct Train;
26 /** Rail vehicle flags. */
27 enum VehicleRailFlags {
28 VRF_REVERSING = 0,
29 VRF_WAITING_RESTRICTION = 1, ///< Train is waiting due to a routing restriction, only valid when VRF_TRAIN_STUCK is also set.
30 VRF_HAVE_SLOT = 2, ///< Train has 1 or more slots
31 VRF_POWEREDWAGON = 3, ///< Wagon is powered.
32 VRF_REVERSE_DIRECTION = 4, ///< Reverse the visible direction of the vehicle.
34 VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL = 6, ///< Electric train engine is allowed to run on normal rail. */
35 VRF_TOGGLE_REVERSE = 7, ///< Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle only).
36 VRF_TRAIN_STUCK = 8, ///< Train can't get a path reservation.
37 VRF_LEAVING_STATION = 9, ///< Train is just leaving a station.
40 /** Modes for ignoring signals. */
41 enum TrainForceProceeding {
42 TFP_NONE = 0, ///< Normal operation.
43 TFP_STUCK = 1, ///< Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
44 TFP_SIGNAL = 2, ///< Ignore next signal, after the signal ignore being stuck.
46 typedef SimpleTinyEnumT<TrainForceProceeding, byte> TrainForceProceedingByte;
48 /** Flags for Train::ConsistChanged */
49 enum ConsistChangeFlags {
50 CCF_LENGTH = 0x01, ///< Allow vehicles to change length.
51 CCF_CAPACITY = 0x02, ///< Allow vehicles to change capacity.
53 CCF_TRACK = 0, ///< Valid changes while vehicle is driving, and possibly changing tracks.
54 CCF_LOADUNLOAD = 0, ///< Valid changes while vehicle is loading/unloading.
55 CCF_AUTOREFIT = CCF_CAPACITY, ///< Valid changes for autorefitting in stations.
56 CCF_REFIT = CCF_LENGTH | CCF_CAPACITY, ///< Valid changes for refitting in a depot.
57 CCF_ARRANGE = CCF_LENGTH | CCF_CAPACITY, ///< Valid changes for arranging the consist in a depot.
58 CCF_SAVELOAD = CCF_LENGTH, ///< Valid changes when loading a savegame. (Everything that is not stored in the save.)
60 DECLARE_ENUM_AS_BIT_SET(ConsistChangeFlags)
62 byte FreightWagonMult(CargoID cargo);
64 void CheckTrainsLengths();
66 void FreeTrainTrackReservation(const Train *v, TileIndex origin = INVALID_TILE, Trackdir orig_td = INVALID_TRACKDIR);
67 bool TryPathReserve(Train *v, bool mark_as_stuck = false, bool first_tile_okay = false);
69 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length);
71 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type);
73 /** Variables that are cached to improve performance and such */
74 struct TrainCache {
75 /* Cached wagon override spritegroup */
76 const struct SpriteGroup *cached_override;
78 /* cached values, recalculated on load and each time a vehicle is added to/removed from the consist. */
79 bool cached_tilt; ///< train can tilt; feature provides a bonus in curves
81 byte user_def_data; ///< Cached property 0x25. Can be set by Callback 0x36.
83 /* cached max. speed / acceleration data */
84 int cached_max_curve_speed; ///< max consist speed limited by curves
87 /**
88 * 'Train' is either a loco or a wagon.
90 struct Train FINAL : public GroundVehicle<Train, VEH_TRAIN> {
91 TrainCache tcache;
93 /* Link between the two ends of a multiheaded engine */
94 Train *other_multiheaded_part;
96 uint16 crash_anim_pos; ///< Crash animation counter.
98 uint16 flags;
99 TrackBitsByte track;
100 TrainForceProceedingByte force_proceed;
101 RailTypeByte railtype;
102 RailTypes compatible_railtypes;
104 /** Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through signals. */
105 uint16 wait_counter;
107 uint16 tunnel_bridge_signal_num;
109 uint16 reverse_distance;
111 /** We don't want GCC to zero our struct! It already is zeroed and has an index! */
112 Train() : GroundVehicleBase() {}
113 /** We want to 'destruct' the right class. */
114 virtual ~Train() { this->PreDestructor(); }
116 friend struct GroundVehicle<Train, VEH_TRAIN>; // GroundVehicle needs to use the acceleration functions defined at Train.
118 void MarkDirty();
119 void UpdateDeltaXY(Direction direction);
120 ExpensesType GetExpenseType(bool income) const { return income ? EXPENSES_TRAIN_INC : EXPENSES_TRAIN_RUN; }
121 void PlayLeaveStationSound() const;
122 bool IsPrimaryVehicle() const { return this->IsFrontEngine(); }
123 void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const;
124 int GetDisplaySpeed() const { return this->gcache.last_speed; }
125 int GetDisplayMaxSpeed() const { return this->vcache.cached_max_speed; }
126 Money GetRunningCost() const;
127 int GetDisplayImageWidth(Point *offset = NULL) const;
128 bool IsInDepot() const { return this->track == TRACK_BIT_DEPOT; }
129 bool Tick();
130 void OnNewDay();
131 uint Crash(bool flooded = false);
132 Money CalculateCurrentOverallValue() const;
133 Trackdir GetVehicleTrackdir() const;
134 TileIndex GetOrderStationLocation(StationID station);
135 bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse);
137 void ReserveTrackUnderConsist() const;
139 int GetCurveSpeedLimit() const;
141 void ConsistChanged(ConsistChangeFlags allowed_changes);
143 int UpdateSpeed();
145 void UpdateAcceleration();
147 int GetCurrentMaxSpeed() const;
150 * Get the next real (non-articulated part and non rear part of dualheaded engine) vehicle in the consist.
151 * @return Next vehicle in the consist.
153 inline Train *GetNextUnit() const
155 Train *v = this->GetNextVehicle();
156 if (v != NULL && v->IsRearDualheaded()) v = v->GetNextVehicle();
158 return v;
162 * Get the previous real (non-articulated part and non rear part of dualheaded engine) vehicle in the consist.
163 * @return Previous vehicle in the consist.
165 inline Train *GetPrevUnit()
167 Train *v = this->GetPrevVehicle();
168 if (v != NULL && v->IsRearDualheaded()) v = v->GetPrevVehicle();
170 return v;
173 /* Get the last vehicle of a chain
174 * @return pointer the last vehicle in a chain
176 inline Train *GetLastUnit() {
177 Train *tmp = this;
178 while ( tmp->GetNextUnit() ) tmp = tmp->GetNextUnit();
179 return tmp;
183 * Calculate the offset from this vehicle's center to the following center taking the vehicle lengths into account.
184 * @return Offset from center to center.
186 int CalcNextVehicleOffset() const
188 /* For vehicles with odd lengths the part before the center will be one unit
189 * longer than the part after the center. This means we have to round up the
190 * length of the next vehicle but may not round the length of the current
191 * vehicle. */
192 return this->gcache.cached_veh_length / 2 + (this->Next() != NULL ? this->Next()->gcache.cached_veh_length + 1 : 0) / 2;
196 * Allows to know the weight value that this vehicle will use.
197 * @return Empty weight value from the engine in tonnes.
199 inline uint16 GetEmptyWeight() const
201 uint16 weight = 0;
203 /* Vehicle weight is not added for articulated parts. */
204 if (!this->IsArticulatedPart()) {
205 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
208 /* Powered wagons have extra weight added. */
209 if (HasBit(this->flags, VRF_POWEREDWAGON)) {
210 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
213 return weight * (this->IsWagon() ? FreightWagonMult(this->cargo_type) : 1);
217 * Allows to know the weight value that this vehicle will use.
218 * @return Loaded weight value from the engine in tonnes.
220 inline uint16 GetLoadedWeight() const
222 uint16 weight = (CargoSpec::Get(this->cargo_type)->weight * this->cargo_cap) / 16;
224 /* Vehicle weight is not added for articulated parts. */
225 if (!this->IsArticulatedPart()) {
226 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
229 /* Powered wagons have extra weight added. */
230 if (HasBit(this->flags, VRF_POWEREDWAGON)) {
231 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
234 return weight * (this->IsWagon() ? FreightWagonMult(this->cargo_type) : 1);
238 * Returns the rolling friction coefficient of this vehicle.
239 * @return Rolling friction coefficient in [1e-4].
241 inline uint32 GetRollingFriction() const
243 /* Roughly 1000 * 9.81 * 0.002
244 * 1000 for tonnes to kg
245 * 9.81 for g
246 * 0.0017 for track to wheel friction
248 return 17;
251 protected: // These functions should not be called outside acceleration code.
254 * Allows to know the power value that this vehicle will use.
255 * @return Power value from the engine in HP, or zero if the vehicle is not powered.
257 inline uint16 GetPower() const
259 /* Power is not added for articulated parts */
260 bool is_articulated_part = this->IsArticulatedPart();
261 bool has_power_on_rail = HasPowerOnRail(this->railtype, GetRailType(this->tile));
262 bool is_virtual = this->IsVirtual();
264 if (!is_articulated_part && (has_power_on_rail || is_virtual)) {
265 uint16 power = GetVehicleProperty(this, PROP_TRAIN_POWER, RailVehInfo(this->engine_type)->power);
266 /* Halve power for multiheaded parts */
267 if (this->IsMultiheaded()) power /= 2;
268 return power;
271 return 0;
275 * Returns a value if this articulated part is powered.
276 * @return Power value from the articulated part in HP, or zero if it is not powered.
278 inline uint16 GetPoweredPartPower(const Train *head) const
280 /* For powered wagons the engine defines the type of engine (i.e. railtype) */
281 bool is_powered_wagon = HasBit(this->flags, VRF_POWEREDWAGON);
282 bool has_power_on_rail = HasPowerOnRail(head->railtype, GetRailType(this->tile));
283 bool is_virtual = this->IsVirtual();
285 if (is_powered_wagon && (has_power_on_rail || is_virtual)) {
286 return RailVehInfo(this->gcache.first_engine)->pow_wag_power;
289 return 0;
293 * Allows to know the weight value that this vehicle will use.
294 * @return Weight value from the engine in tonnes.
296 inline uint16 GetWeight() const
298 uint16 weight = (CargoSpec::Get(this->cargo_type)->weight * this->cargo.StoredCount()) / 16;
300 /* Vehicle weight is not added for articulated parts. */
301 if (!this->IsArticulatedPart()) {
302 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
305 /* Powered wagons have extra weight added. */
306 if (HasBit(this->flags, VRF_POWEREDWAGON)) {
307 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
310 return weight * (this->IsWagon() ? FreightWagonMult(this->cargo_type) : 1);
314 * Allows to know the tractive effort value that this vehicle will use.
315 * @return Tractive effort value from the engine.
317 inline byte GetTractiveEffort() const
319 return GetVehicleProperty(this, PROP_TRAIN_TRACTIVE_EFFORT, RailVehInfo(this->engine_type)->tractive_effort);
323 * Gets the area used for calculating air drag.
324 * @return Area of the engine in m^2.
326 inline byte GetAirDragArea() const
328 /* Air drag is higher in tunnels due to the limited cross-section. */
329 return (this->track == TRACK_BIT_WORMHOLE && this->vehstatus & VS_HIDDEN) ? 28 : 14;
333 * Gets the air drag coefficient of this vehicle.
334 * @return Air drag value from the engine.
336 inline byte GetAirDrag() const
338 return RailVehInfo(this->engine_type)->air_drag;
342 * Checks the current acceleration status of this vehicle.
343 * @return Acceleration status.
345 inline AccelStatus GetAccelerationStatus() const
347 return (this->vehstatus & VS_STOPPED) || HasBit(this->flags, VRF_REVERSING) || HasBit(this->flags, VRF_TRAIN_STUCK) ? AS_BRAKE : AS_ACCEL;
351 * Calculates the current speed of this vehicle.
352 * @return Current speed in km/h-ish.
354 inline uint16 GetCurrentSpeed() const
356 return this->cur_speed;
360 * Allows to know the acceleration type of a vehicle.
361 * @return Acceleration type of the vehicle.
363 inline int GetAccelerationType() const
365 return GetRailTypeInfo(this->railtype)->acceleration_type;
369 * Returns the slope steepness used by this vehicle.
370 * @return Slope steepness used by the vehicle.
372 inline uint32 GetSlopeSteepness() const
374 return _settings_game.vehicle.train_slope_steepness;
378 * Gets the maximum speed allowed by the track for this vehicle.
379 * @return Maximum speed allowed.
381 inline uint16 GetMaxTrackSpeed() const
383 return GetRailTypeInfo(GetRailType(this->tile))->max_speed;
387 * Checks if the vehicle is at a tile that can be sloped.
388 * @return True if the tile can be sloped.
390 inline bool TileMayHaveSlopedTrack() const
392 /* Any track that isn't TRACK_BIT_X or TRACK_BIT_Y cannot be sloped. */
393 return this->track == TRACK_BIT_X || this->track == TRACK_BIT_Y;
397 * Trains can always use the faster algorithm because they
398 * have always the same direction as the track under them.
399 * @return false
401 inline bool HasToUseGetSlopePixelZ()
403 return false;
408 CommandCost CmdMoveRailVehicle(TileIndex, DoCommandFlag , uint32, uint32, const char *);
409 CommandCost CmdMoveVirtualRailVehicle(TileIndex, DoCommandFlag, uint32, uint32, const char*);
411 Train* CmdBuildVirtualRailWagon(const Engine*);
412 Train* CmdBuildVirtualRailVehicle(EngineID, bool lax_engine_check, StringID &error);
414 #define FOR_ALL_TRAINS(var) FOR_ALL_VEHICLES_OF_TYPE(Train, var)
416 #endif /* TRAIN_H */