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 vehicle_base.h Base class for all vehicles. */
12 #ifndef VEHICLE_BASE_H
13 #define VEHICLE_BASE_H
15 #include "core/smallmap_type.hpp"
16 #include "track_type.h"
17 #include "command_type.h"
18 #include "order_base.h"
19 #include "triphistory.h"
20 #include "cargopacket.h"
21 #include "texteff.hpp"
22 #include "engine_type.h"
23 #include "order_func.h"
24 #include "transport_type.h"
25 #include "group_type.h"
26 #include "base_consist.h"
27 #include "network/network.h"
32 CommandCost
CmdRefitVehicle(TileIndex
, DoCommandFlag
, uint32
, uint32
, const char*);
34 /** Vehicle status bits in #Vehicle::vehstatus. */
36 VS_HIDDEN
= 0x01, ///< Vehicle is not visible.
37 VS_STOPPED
= 0x02, ///< Vehicle is stopped by the player.
38 VS_UNCLICKABLE
= 0x04, ///< Vehicle is not clickable by the user (shadow vehicles).
39 VS_DEFPAL
= 0x08, ///< Use default vehicle palette. @see DoDrawVehicle
40 VS_TRAIN_SLOWING
= 0x10, ///< Train is slowing down.
41 VS_SHADOW
= 0x20, ///< Vehicle is a shadow vehicle.
42 VS_AIRCRAFT_BROKEN
= 0x40, ///< Aircraft is broken down.
43 VS_CRASHED
= 0x80, ///< Vehicle is crashed.
46 /** Bit numbers in #Vehicle::vehicle_flags. */
48 VF_LOADING_FINISHED
, ///< Vehicle has finished loading.
49 VF_CARGO_UNLOADING
, ///< Vehicle is unloading cargo.
50 VF_BUILT_AS_PROTOTYPE
, ///< Vehicle is a prototype (accepted as exclusive preview).
51 VF_TIMETABLE_STARTED
, ///< Whether the vehicle has started running on the timetable yet.
52 VF_AUTOMATE_TIMETABLE
, ///< Whether the vehicle should fill and update in the timetable automatically.
53 VF_AUTOMATE_PRES_WAIT_TIME
, ///< Whether non-destructive automate should preserve waiting times
54 VF_STOP_LOADING
, ///< Don't load anymore during the next load cycle.
55 VF_PATHFINDER_LOST
, ///< Vehicle's pathfinder is lost.
56 VF_SERVINT_IS_CUSTOM
, ///< Service interval is custom.
57 VF_SERVINT_IS_PERCENT
, ///< Service interval is percent.
58 VF_SHOULD_GOTO_DEPOT
, ///< Vehicle was manually ordered to go to a depot on its orders list.
59 VF_SHOULD_SERVICE_AT_DEPOT
, ///< Vehicle was manually ordered to service at a depot on its orders list.
61 VF_LAST_LOAD_ST_SEP
= 13, ///< Each vehicle of this chain has its last_loading_station field set separately
64 /** Bit numbers used to indicate which of the #NewGRFCache values are valid. */
65 enum NewGRFCacheValidValues
{
66 NCVV_POSITION_CONSIST_LENGTH
= 0, ///< This bit will be set if the NewGRF var 40 currently stored is valid.
67 NCVV_POSITION_SAME_ID_LENGTH
= 1, ///< This bit will be set if the NewGRF var 41 currently stored is valid.
68 NCVV_CONSIST_CARGO_INFORMATION
= 2, ///< This bit will be set if the NewGRF var 42 currently stored is valid.
69 NCVV_COMPANY_INFORMATION
= 3, ///< This bit will be set if the NewGRF var 43 currently stored is valid.
70 NCVV_POSITION_IN_VEHICLE
= 4, ///< This bit will be set if the NewGRF var 4D currently stored is valid.
71 NCVV_END
, ///< End of the bits.
74 /** Cached often queried (NewGRF) values */
76 /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
77 uint32 position_consist_length
; ///< Cache for NewGRF var 40.
78 uint32 position_same_id_length
; ///< Cache for NewGRF var 41.
79 uint32 consist_cargo_information
; ///< Cache for NewGRF var 42. (Note: The cargotype is untranslated in the cache because the accessing GRF is yet unknown.)
80 uint32 company_information
; ///< Cache for NewGRF var 43.
81 uint32 position_in_vehicle
; ///< Cache for NewGRF var 4D.
82 uint8 cache_valid
; ///< Bitset that indicates which cache values are valid.
85 /** Meaning of the various bits of the visual effect. */
87 VE_OFFSET_START
= 0, ///< First bit that contains the offset (0 = front, 8 = centre, 15 = rear)
88 VE_OFFSET_COUNT
= 4, ///< Number of bits used for the offset
89 VE_OFFSET_CENTRE
= 8, ///< Value of offset corresponding to a position above the centre of the vehicle
91 VE_TYPE_START
= 4, ///< First bit used for the type of effect
92 VE_TYPE_COUNT
= 2, ///< Number of bits used for the effect type
93 VE_TYPE_DEFAULT
= 0, ///< Use default from engine class
94 VE_TYPE_STEAM
= 1, ///< Steam plumes
95 VE_TYPE_DIESEL
= 2, ///< Diesel fumes
96 VE_TYPE_ELECTRIC
= 3, ///< Electric sparks
98 VE_DISABLE_EFFECT
= 6, ///< Flag to disable visual effect
99 VE_ADVANCED_EFFECT
= VE_DISABLE_EFFECT
, ///< Flag for advanced effects
100 VE_DISABLE_WAGON_POWER
= 7, ///< Flag to disable wagon power
102 VE_DEFAULT
= 0xFF, ///< Default value to indicate that visual effect should be based on engine class
105 /** Models for spawning visual effects. */
106 enum VisualEffectSpawnModel
{
107 VESM_NONE
= 0, ///< No visual effect
108 VESM_STEAM
, ///< Steam model
109 VESM_DIESEL
, ///< Diesel model
110 VESM_ELECTRIC
, ///< Electric model
116 * Enum to handle ground vehicle subtypes.
117 * This is defined here instead of at #GroundVehicle because some common function require access to these flags.
118 * Do not access it directly unless you have to. Use the subtype access functions.
120 enum GroundVehicleSubtypeFlags
{
121 GVSF_FRONT
= 0, ///< Leading engine of a consist.
122 GVSF_ARTICULATED_PART
= 1, ///< Articulated part of an engine.
123 GVSF_WAGON
= 2, ///< Wagon (not used for road vehicles).
124 GVSF_ENGINE
= 3, ///< Engine that can be front engine, but might be placed behind another engine (not used for road vehicles).
125 GVSF_FREE_WAGON
= 4, ///< First in a wagon chain (in depot) (not used for road vehicles).
126 GVSF_MULTIHEADED
= 5, ///< Engine is multiheaded (not used for road vehicles).
127 GVSF_VIRTUAL
= 6, ///< Used for virtual trains during template design, it is needed to skip checks for tile or depot status
130 /** Cached often queried values common to all vehicles. */
131 struct VehicleCache
{
132 uint16 cached_max_speed
; ///< Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
133 uint16 cached_cargo_age_period
; ///< Number of ticks before carried cargo is aged.
135 byte cached_vis_effect
; ///< Visual effect to show (see #VisualEffect)
138 /** Sprite sequence for a vehicle part. */
139 struct VehicleSpriteSeq
{
143 bool operator==(const VehicleSpriteSeq
&other
) const
145 return this->count
== other
.count
&& MemCmpT
<PalSpriteID
>(this->seq
, other
.seq
, this->count
) == 0;
148 bool operator!=(const VehicleSpriteSeq
&other
) const
150 return !this->operator==(other
);
154 * Check whether the sequence contains any sprites.
158 return this->count
!= 0;
162 * Clear all information.
170 * Assign a single sprite to the sequence.
172 void Set(SpriteID sprite
)
175 this->seq
[0].sprite
= sprite
;
176 this->seq
[0].pal
= 0;
180 * Copy data from another sprite sequence, while dropping all recolouring information.
182 void CopyWithoutPalette(const VehicleSpriteSeq
&src
)
184 this->count
= src
.count
;
185 for (uint i
= 0; i
< src
.count
; ++i
) {
186 this->seq
[i
].sprite
= src
.seq
[i
].sprite
;
187 this->seq
[i
].pal
= 0;
191 void GetBounds(Rect
*bounds
) const;
192 void Draw(int x
, int y
, PaletteID default_pal
, bool force_pal
) const;
195 /** A vehicle pool for a little over 1 million vehicles. */
196 typedef Pool
<Vehicle
, VehicleID
, 512, 0xFF000> VehiclePool
;
197 extern VehiclePool _vehicle_pool
;
199 /* Some declarations of functions, so we can make them friendly */
201 struct GroundVehicleCache
;
202 extern const SaveLoad
*GetVehicleDescription(VehicleType vt
);
203 struct LoadgameState
;
204 extern bool LoadOldVehicle(LoadgameState
*ls
, int num
);
205 extern void FixOldVehicles();
209 /** %Vehicle data structure. */
210 struct Vehicle
: VehiclePool::PoolItem
<&_vehicle_pool
>, BaseVehicle
, BaseConsist
{
212 typedef std::map
<CargoID
, uint
> CapacitiesMap
;
214 Vehicle
*next
; ///< pointer to the next vehicle in the chain
215 Vehicle
*previous
; ///< NOSAVE: pointer to the previous vehicle in the chain
216 Vehicle
*first
; ///< NOSAVE: pointer to the first vehicle in the chain
218 Vehicle
*next_shared
; ///< pointer to the next vehicle that shares the order
219 Vehicle
*previous_shared
; ///< NOSAVE: pointer to the previous vehicle in the shared order chain
221 Vehicle
*ahead_separation
; ///< (outdated. Only for backwards compatibility)
222 Vehicle
*behind_separation
; ///< (outdated. Only for backwards compatibility)
225 friend const SaveLoad
*GetVehicleDescription(VehicleType vt
); ///< So we can use private/protected variables in the saveload code
226 friend void FixOldVehicles();
227 friend void AfterLoadVehicles(bool part_of_load
); ///< So we can set the #previous and #first pointers while loading
228 friend bool LoadOldVehicle(LoadgameState
*ls
, int num
); ///< So we can set the proper next pointer while loading
230 TileIndex tile
; ///< Current tile index
233 * Heading for this tile.
234 * For airports and train stations this tile does not necessarily belong to the destination station,
235 * but it can be used for heuristic purposes to estimate the distance.
239 Money profit_this_year
; ///< Profit this year << 8, low 8 bits are fract
240 Money profit_last_year
; ///< Profit last year << 8, low 8 bits are fract
241 Money profit_lifetime
; ///< Profit lifetime << 8, low 8 bits are fract
242 Money value
; ///< Value of the vehicle
244 TripHistory trip_history
; ///< Trip History Info
246 CargoPayment
*cargo_payment
; ///< The cargo payment we're currently in
248 Rect coord
; ///< NOSAVE: Graphical bounding box of the vehicle, i.e. what to redraw on moves.
250 Vehicle
*hash_viewport_next
; ///< NOSAVE: Next vehicle in the visual location hash.
251 Vehicle
**hash_viewport_prev
; ///< NOSAVE: Previous vehicle in the visual location hash.
253 Vehicle
*hash_tile_next
; ///< NOSAVE: Next vehicle in the tile location hash.
254 Vehicle
**hash_tile_prev
; ///< NOSAVE: Previous vehicle in the tile location hash.
255 Vehicle
**hash_tile_current
; ///< NOSAVE: Cache of the current hash chain.
257 SpriteID colourmap
; ///< NOSAVE: cached colour mapping
259 /* Related to age and service time */
260 Year build_year
; ///< Year the vehicle has been built.
261 Date age
; ///< Age in days
262 Date max_age
; ///< Maximum age
263 Date date_of_last_service
; ///< Last date the vehicle had a service at a depot.
264 uint16 reliability
; ///< Reliability.
265 uint16 reliability_spd_dec
; ///< Reliability decrease speed.
266 byte breakdown_ctr
; ///< Counter for managing breakdown events. @see Vehicle::HandleBreakdown
267 byte breakdown_delay
; ///< Counter for managing breakdown length.
268 byte breakdowns_since_last_service
; ///< Counter for the amount of breakdowns.
269 byte breakdown_chance
; ///< Current chance of breakdowns.
271 int32 x_pos
; ///< x coordinate.
272 int32 y_pos
; ///< y coordinate.
273 int32 z_pos
; ///< z coordinate.
274 DirectionByte direction
; ///< facing
276 OwnerByte owner
; ///< Which company owns the vehicle?
278 * currently displayed sprite index
279 * 0xfd == custom sprite, 0xfe == custom second head sprite
280 * 0xff == reserved for another custom sprite
283 VehicleSpriteSeq sprite_seq
; ///< Vehicle appearance.
284 byte x_extent
; ///< x-extent of vehicle bounding box
285 byte y_extent
; ///< y-extent of vehicle bounding box
286 byte z_extent
; ///< z-extent of vehicle bounding box
287 int8 x_bb_offs
; ///< x offset of vehicle bounding box
288 int8 y_bb_offs
; ///< y offset of vehicle bounding box
289 int8 x_offs
; ///< x offset for vehicle sprite
290 int8 y_offs
; ///< y offset for vehicle sprite
291 EngineID engine_type
; ///< The type of engine used for this vehicle.
293 TextEffectID fill_percent_te_id
; ///< a text-effect id to a loading indicator object
294 UnitID unitnumber
; ///< unit number, for display purposes only
296 uint16 cur_speed
; ///< current speed
297 byte subspeed
; ///< fractional speed
298 byte acceleration
; ///< used by train & aircraft
299 uint32 motion_counter
; ///< counter to occasionally play a vehicle sound.
300 byte progress
; ///< The percentage (if divided by 256) this vehicle already crossed the tile unit.
302 byte random_bits
; ///< Bits used for determining which randomized variational spritegroups to use when drawing.
303 byte waiting_triggers
; ///< Triggers to be yet matched before rerandomizing the random bits.
305 StationID last_station_visited
; ///< The last station we stopped at.
306 StationID last_loading_station
; ///< Last station the vehicle has stopped at and could possibly leave from with any cargo loaded. (See VF_LAST_LOAD_ST_SEP).
308 CargoID cargo_type
; ///< type of cargo this vehicle is carrying
309 byte cargo_subtype
; ///< Used for livery refits (NewGRF variations)
310 uint16 cargo_cap
; ///< total capacity
311 uint16 refit_cap
; ///< Capacity left over from before last refit.
312 VehicleCargoList cargo
; ///< The cargo this vehicle is carrying
313 uint16 cargo_age_counter
; ///< Ticks till cargo is aged next.
314 std::vector
<int8
> station_occupancies
; ///< Occupancies of vehicle at each station (set after leaving a station).
316 byte day_counter
; ///< Increased by one for each day
317 byte tick_counter
; ///< Increased by one for each tick
318 uint16 running_ticks
; ///< Number of ticks this vehicle was not stopped this day
320 byte vehstatus
; ///< Status
321 Order current_order
; ///< The current order (+ status, like: loading)
324 OrderList
*list
; ///< Pointer to the order list for this vehicle
325 Order
*old
; ///< Only used during conversion of old save games
326 } orders
; ///< The orders currently assigned to the vehicle.
328 uint16 load_unload_ticks
; ///< Ticks to wait before starting next cycle.
329 GroupID group_id
; ///< Index of group Pool array
330 byte subtype
; ///< subtype (Filled with values from #EffectVehicles/#TrainSubTypes/#AircraftSubTypes)
332 NewGRFCache grf_cache
; ///< Cache of often used calculated NewGRF values
333 VehicleCache vcache
; ///< Cache of often used vehicle values.
335 Vehicle(VehicleType type
= VEH_INVALID
);
337 void PreDestructor();
338 /** We want to 'destruct' the right class. */
341 uint32
GetLastLoadingStationValidCargoMask() const;
344 void CancelReservation(StationID next
, Station
*st
);
347 void HandleAutomaticTimetableSeparation();
349 GroundVehicleCache
*GetGroundVehicleCache();
350 const GroundVehicleCache
*GetGroundVehicleCache() const;
352 uint16
&GetGroundVehicleFlags();
353 const uint16
&GetGroundVehicleFlags() const;
355 void DeleteUnreachedImplicitOrders();
357 void HandleLoading(bool mode
= false);
359 void HandleWaiting(bool stop_waiting
= false);
362 * Marks the vehicles to be redrawn and updates cached variables
364 * This method marks the area of the vehicle on the screen as dirty.
365 * It can be use to repaint the vehicle.
369 virtual void MarkDirty() {}
372 * Updates the x and y offsets and the size of the sprite used
374 * @param direction the direction the vehicle is facing
376 virtual void UpdateDeltaXY(Direction direction
) {}
379 * Determines the effective direction-specific vehicle movement speed.
381 * This method belongs to the old vehicle movement method:
382 * A vehicle moves a step every 256 progress units.
383 * The vehicle speed is scaled by 3/4 when moving in X or Y direction due to the longer distance.
385 * However, this method is slightly wrong in corners, as the leftover progress is not scaled correctly
386 * when changing movement direction. #GetAdvanceSpeed() and #GetAdvanceDistance() are better wrt. this.
388 * @param speed Direction-independent unscaled speed.
389 * @return speed scaled by movement direction. 256 units are required for each movement step.
391 inline uint
GetOldAdvanceSpeed(uint speed
)
393 return (this->direction
& 1) ? speed
: speed
* 3 / 4;
397 * Determines the effective vehicle movement speed.
399 * Together with #GetAdvanceDistance() this function is a replacement for #GetOldAdvanceSpeed().
401 * A vehicle progresses independent of it's movement direction.
402 * However different amounts of "progress" are needed for moving a step in a specific direction.
403 * That way the leftover progress does not need any adaption when changing movement direction.
405 * @param speed Direction-independent unscaled speed.
406 * @return speed, scaled to match #GetAdvanceDistance().
408 static inline uint
GetAdvanceSpeed(uint speed
)
410 return speed
* 3 / 4;
414 * Determines the vehicle "progress" needed for moving a step.
416 * Together with #GetAdvanceSpeed() this function is a replacement for #GetOldAdvanceSpeed().
418 * @return distance to drive for a movement step on the map.
420 inline uint
GetAdvanceDistance()
422 return (this->direction
& 1) ? 192 : 256;
426 * Sets the expense type associated to this vehicle type
427 * @param income whether this is income or (running) expenses of the vehicle
429 virtual ExpensesType
GetExpenseType(bool income
) const { return EXPENSES_OTHER
; }
432 * Play the sound associated with leaving the station
434 virtual void PlayLeaveStationSound() const {}
437 * Whether this is the primary vehicle in the chain.
439 virtual bool IsPrimaryVehicle() const { return false; }
441 const Engine
*GetEngine() const;
444 * Gets the sprite to show for the given direction
445 * @param direction the direction the vehicle is facing
446 * @param [out] result Vehicle sprite sequence.
448 virtual void GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const { result
->Clear(); }
450 const GRFFile
*GetGRF() const;
451 uint32
GetGRFID() const;
454 * Invalidates cached NewGRF variables
455 * @see InvalidateNewGRFCacheOfChain
457 inline void InvalidateNewGRFCache()
459 this->grf_cache
.cache_valid
= 0;
463 * Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle)
464 * @see InvalidateNewGRFCache
466 inline void InvalidateNewGRFCacheOfChain()
468 for (Vehicle
*u
= this; u
!= NULL
; u
= u
->Next()) {
469 u
->InvalidateNewGRFCache();
474 * Check if the vehicle is a ground vehicle.
475 * @return True iff the vehicle is a train or a road vehicle.
477 inline bool IsGroundVehicle() const
479 return this->type
== VEH_TRAIN
|| this->type
== VEH_ROAD
;
483 * Gets the speed in km-ish/h that can be sent into SetDParam for string processing.
484 * @return the vehicle's speed
486 virtual int GetDisplaySpeed() const { return 0; }
489 * Gets the maximum speed in km-ish/h that can be sent into SetDParam for string processing.
490 * @return the vehicle's maximum speed
492 virtual int GetDisplayMaxSpeed() const { return 0; }
495 * Calculates the maximum speed of the vehicle under its current conditions.
496 * @return Current maximum speed in native units.
498 virtual int GetCurrentMaxSpeed() const { return 0; }
501 * Gets the running cost of a vehicle
502 * @return the vehicle's running cost
504 virtual Money
GetRunningCost() const { return 0; }
507 * Check whether the vehicle is in the depot.
508 * @return true if and only if the vehicle is in the depot.
510 virtual bool IsInDepot() const { return false; }
513 * Check whether the whole vehicle chain is in the depot.
514 * @return true if and only if the whole chain is in the depot.
516 virtual bool IsChainInDepot() const { return this->IsInDepot(); }
519 * Check whether the vehicle is in the depot *and* stopped.
520 * @return true if and only if the vehicle is in the depot and stopped.
522 bool IsStoppedInDepot() const
524 assert(this == this->First());
525 /* Free wagons have no VS_STOPPED state */
526 if (this->IsPrimaryVehicle() && !(this->vehstatus
& VS_STOPPED
)) return false;
527 return this->IsChainInDepot();
531 * Calls the tick handler of the vehicle
532 * @return is this vehicle still valid?
534 virtual bool Tick() { return true; };
537 * Calls the new day handler of the vehicle
539 virtual void OnNewDay() {};
542 * Crash the (whole) vehicle chain.
543 * @param flooded whether the cause of the crash is flooding or not.
544 * @return the number of lost souls.
546 virtual uint
Crash(bool flooded
= false);
549 * Returns the Trackdir on which the vehicle is currently located.
550 * Works for trains and ships.
551 * Currently works only sortof for road vehicles, since they have a fuzzy
552 * concept of being "on" a trackdir. Dunno really what it returns for a road
553 * vehicle that is halfway a tile, never really understood that part. For road
554 * vehicles that are at the beginning or end of the tile, should just return
555 * the diagonal trackdir on which they are driving. I _think_.
556 * For other vehicles types, or vehicles with no clear trackdir (such as those
557 * in depots), returns 0xFF.
558 * @return the trackdir of the vehicle
560 virtual Trackdir
GetVehicleTrackdir() const { return INVALID_TRACKDIR
; }
563 * Gets the running cost of a vehicle that can be sent into SetDParam for string processing.
564 * @return the vehicle's running cost
566 Money
GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
569 * Gets the profit vehicle had this year. It can be sent into SetDParam for string processing.
570 * @return the vehicle's profit this year
572 Money
GetDisplayProfitThisYear() const { return (this->profit_this_year
>> 8); }
575 * Gets the profit vehicle had last year. It can be sent into SetDParam for string processing.
576 * @return the vehicle's profit last year
578 Money
GetDisplayProfitLastYear() const { return (this->profit_last_year
>> 8); }
581 * Gets the lifetime profit of vehicle. It can be sent into SetDParam for string processing.
582 * @return the vehicle's lifetime profit
584 Money
GetDisplayProfitLifetime() const { return ((this->profit_lifetime
+ this->profit_this_year
) >> 8); }
586 void SetNext(Vehicle
*next
);
587 inline void SetFirst(Vehicle
*f
) { this->first
=f
; }
590 * Get the next vehicle of this vehicle.
591 * @note articulated parts are also counted as vehicles.
592 * @return the next vehicle or NULL when there isn't a next vehicle.
594 inline Vehicle
*Next() const { return this->next
; }
597 * Get the previous vehicle of this vehicle.
598 * @note articulated parts are also counted as vehicles.
599 * @return the previous vehicle or NULL when there isn't a previous vehicle.
601 inline Vehicle
*Previous() const { return this->previous
; }
604 * Get the first vehicle of this vehicle chain.
605 * @return the first vehicle of the chain.
607 inline Vehicle
*First() const { return this->first
; }
610 * Get the last vehicle of this vehicle chain.
611 * @return the last vehicle of the chain.
613 inline Vehicle
*Last()
616 while (v
->Next() != NULL
) v
= v
->Next();
621 * Get the last vehicle of this vehicle chain.
622 * @return the last vehicle of the chain.
624 inline const Vehicle
*Last() const
626 const Vehicle
*v
= this;
627 while (v
->Next() != NULL
) v
= v
->Next();
632 * Get the vehicle at offset \a n of this vehicle chain.
633 * @param n Offset from the current vehicle.
634 * @return The new vehicle or NULL if the offset is out-of-bounds.
636 inline Vehicle
*Move(int n
)
640 for (int i
= 0; i
!= n
&& v
!= NULL
; i
--) v
= v
->Previous();
642 for (int i
= 0; i
!= n
&& v
!= NULL
; i
++) v
= v
->Next();
648 * Get the vehicle at offset \a n of this vehicle chain.
649 * @param n Offset from the current vehicle.
650 * @return The new vehicle or NULL if the offset is out-of-bounds.
652 inline const Vehicle
*Move(int n
) const
654 const Vehicle
*v
= this;
656 for (int i
= 0; i
!= n
&& v
!= NULL
; i
--) v
= v
->Previous();
658 for (int i
= 0; i
!= n
&& v
!= NULL
; i
++) v
= v
->Next();
664 * Get the first order of the vehicles order list.
665 * @return first order of order list.
667 inline Order
*GetFirstOrder() const { return (this->orders
.list
== NULL
) ? NULL
: this->orders
.list
->GetFirstOrder(); }
669 void AddToShared(Vehicle
*shared_chain
);
670 void RemoveFromShared();
673 * Get the next vehicle of the shared vehicle chain.
674 * @return the next shared vehicle or NULL when there isn't a next vehicle.
676 inline Vehicle
*NextShared() const { return this->next_shared
; }
679 * Get the previous vehicle of the shared vehicle chain
680 * @return the previous shared vehicle or NULL when there isn't a previous vehicle.
682 inline Vehicle
*PreviousShared() const { return this->previous_shared
; }
685 * Get the first vehicle of this vehicle chain.
686 * @return the first vehicle of the chain.
688 inline Vehicle
*FirstShared() const { return (this->orders
.list
== NULL
) ? this->First() : this->orders
.list
->GetFirstSharedVehicle(); }
691 * Check if we share our orders with another vehicle.
692 * @return true if there are other vehicles sharing the same order
694 inline bool IsOrderListShared() const { return this->orders
.list
!= NULL
&& this->orders
.list
->IsShared(); }
697 * Get the number of orders this vehicle has.
698 * @return the number of orders this vehicle has.
700 inline VehicleOrderID
GetNumOrders() const { return (this->orders
.list
== NULL
) ? 0 : this->orders
.list
->GetNumOrders(); }
703 * Get the number of manually added orders this vehicle has.
704 * @return the number of manually added orders this vehicle has.
706 inline VehicleOrderID
GetNumManualOrders() const { return (this->orders
.list
== NULL
) ? 0 : this->orders
.list
->GetNumManualOrders(); }
709 * Get the next station the vehicle will stop at.
710 * @return ID of the next station the vehicle will stop at or INVALID_STATION.
712 inline CargoStationIDStackSet
GetNextStoppingStation() const
714 CargoStationIDStackSet set
;
715 if (this->orders
.list
!= NULL
) set
.FillNextStoppingStation(this, this->orders
.list
);
719 void ResetRefitCaps();
722 * Copy certain configurations and statistics of a vehicle after successful autoreplace/renew
723 * The function shall copy everything that cannot be copied by a command (like orders / group etc),
724 * and that shall not be resetted for the new vehicle.
725 * @param src The old vehicle
727 inline void CopyVehicleConfigAndStatistics(const Vehicle
*src
)
729 this->CopyConsistPropertiesFrom(src
);
731 this->unitnumber
= src
->unitnumber
;
733 this->current_order
= src
->current_order
;
734 this->dest_tile
= src
->dest_tile
;
736 this->profit_this_year
= src
->profit_this_year
;
737 this->profit_last_year
= src
->profit_last_year
;
738 this->profit_lifetime
= -this->profit_this_year
;
742 bool HandleBreakdown();
744 bool NeedsAutorenewing(const Company
*c
, bool use_renew_setting
= true) const;
746 bool NeedsServicing() const;
747 bool NeedsAutomaticServicing() const;
750 * Determine the location for the station where the vehicle goes to next.
751 * Things done for example are allocating slots in a road stop or exact
752 * location of the platform is determined for ships.
753 * @param station the station to make the next location of the vehicle.
754 * @return the location (tile) to aim for.
756 virtual TileIndex
GetOrderStationLocation(StationID station
) { return INVALID_TILE
; }
759 * Find the closest depot for this vehicle and tell us the location,
760 * DestinationID and whether we should reverse.
761 * @param location where do we go to?
762 * @param destination what hangar do we go to?
763 * @param reverse should the vehicle be reversed?
764 * @return true if a depot could be found.
766 virtual bool FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
) { return false; }
768 CommandCost
SendToDepot(DoCommandFlag flags
, DepotCommand command
);
770 void UpdateVisualEffect(bool allow_power_change
= true);
771 void ShowVisualEffect() const;
773 void UpdatePosition();
774 void UpdateViewport(bool dirty
);
775 void UpdatePositionAndViewport();
776 void MarkAllViewportsDirty() const;
778 inline uint16
GetServiceInterval() const { return this->service_interval
; }
780 inline void SetServiceInterval(uint16 interval
) { this->service_interval
= interval
; }
782 inline bool ServiceIntervalIsCustom() const { return HasBit(this->vehicle_flags
, VF_SERVINT_IS_CUSTOM
); }
784 inline bool ServiceIntervalIsPercent() const { return HasBit(this->vehicle_flags
, VF_SERVINT_IS_PERCENT
); }
786 inline void SetServiceIntervalIsCustom(bool on
) { SB(this->vehicle_flags
, VF_SERVINT_IS_CUSTOM
, 1, on
); }
788 inline void SetServiceIntervalIsPercent(bool on
) { SB(this->vehicle_flags
, VF_SERVINT_IS_PERCENT
, 1, on
); }
792 * Advance cur_real_order_index to the next real order.
793 * cur_implicit_order_index is not touched.
795 void SkipToNextRealOrderIndex()
797 if (this->GetNumManualOrders() > 0) {
798 /* Advance to next real order */
800 this->cur_real_order_index
++;
801 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
802 } while (this->GetOrder(this->cur_real_order_index
)->IsType(OT_IMPLICIT
));
804 this->cur_real_order_index
= 0;
810 * Increments cur_implicit_order_index, keeps care of the wrap-around and invalidates the GUI.
811 * cur_real_order_index is incremented as well, if needed.
812 * Note: current_order is not invalidated.
814 void IncrementImplicitOrderIndex()
816 if (this->cur_implicit_order_index
== this->cur_real_order_index
) {
817 /* Increment real order index as well */
818 this->SkipToNextRealOrderIndex();
821 assert(this->cur_real_order_index
== 0 || this->cur_real_order_index
< this->GetNumOrders());
823 /* Advance to next implicit order */
825 this->cur_implicit_order_index
++;
826 if (this->cur_implicit_order_index
>= this->GetNumOrders()) this->cur_implicit_order_index
= 0;
827 } while (this->cur_implicit_order_index
!= this->cur_real_order_index
&& !this->GetOrder(this->cur_implicit_order_index
)->IsType(OT_IMPLICIT
));
829 InvalidateVehicleOrder(this, 0);
833 * Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates the GUI.
834 * cur_implicit_order_index is incremented as well, if it was equal to cur_real_order_index, i.e. cur_real_order_index is skipped
835 * but not any implicit orders.
836 * Note: current_order is not invalidated.
838 void IncrementRealOrderIndex()
840 if (this->cur_implicit_order_index
== this->cur_real_order_index
) {
841 /* Increment both real and implicit order */
842 this->IncrementImplicitOrderIndex();
844 /* Increment real order only */
845 this->SkipToNextRealOrderIndex();
846 InvalidateVehicleOrder(this, 0);
851 * Skip implicit orders until cur_real_order_index is a non-implicit order.
853 void UpdateRealOrderIndex()
855 /* Make sure the index is valid */
856 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
858 if (this->GetNumManualOrders() > 0) {
859 /* Advance to next real order */
860 while (this->GetOrder(this->cur_real_order_index
)->IsType(OT_IMPLICIT
)) {
861 this->cur_real_order_index
++;
862 if (this->cur_real_order_index
>= this->GetNumOrders()) this->cur_real_order_index
= 0;
865 this->cur_real_order_index
= 0;
870 * Returns order 'index' of a vehicle or NULL when it doesn't exists
871 * @param index the order to fetch
872 * @return the found (or not) order
874 inline Order
*GetOrder(int index
) const
876 return (this->orders
.list
== NULL
) ? NULL
: this->orders
.list
->GetOrderAt(index
);
880 * Returns the last order of a vehicle, or NULL if it doesn't exists
881 * @return last order of a vehicle, if available
883 inline Order
*GetLastOrder() const
885 return (this->orders
.list
== NULL
) ? NULL
: this->orders
.list
->GetLastOrder();
888 bool IsEngineCountable() const;
889 bool HasEngineType() const;
890 bool HasDepotOrder() const;
891 void HandlePathfindingResult(bool path_found
);
892 void MarkSeparationInvalid();
893 void SetSepSettings(TTSepMode Mode
, uint Parameter
);
896 * Check if the vehicle is a front engine.
897 * @return Returns true if the vehicle is a front engine.
899 inline bool IsFrontEngine() const
901 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_FRONT
);
905 * Check if the vehicle is an articulated part of an engine.
906 * @return Returns true if the vehicle is an articulated part.
908 inline bool IsArticulatedPart() const
910 return this->IsGroundVehicle() && HasBit(this->subtype
, GVSF_ARTICULATED_PART
);
914 * Check if an engine has an articulated part.
915 * @return True if the engine has an articulated part.
917 inline bool HasArticulatedPart() const
919 return this->Next() != NULL
&& this->Next()->IsArticulatedPart();
923 * Get the next part of an articulated engine.
924 * @return Next part of the articulated engine.
925 * @pre The vehicle is an articulated engine.
927 inline Vehicle
*GetNextArticulatedPart() const
929 assert(this->HasArticulatedPart());
934 * Get the first part of an articulated engine.
935 * @return First part of the engine.
937 inline Vehicle
*GetFirstEnginePart()
940 while (v
->IsArticulatedPart()) v
= v
->Previous();
945 * Get the first part of an articulated engine.
946 * @return First part of the engine.
948 inline const Vehicle
*GetFirstEnginePart() const
950 const Vehicle
*v
= this;
951 while (v
->IsArticulatedPart()) v
= v
->Previous();
956 * Get the last part of an articulated engine.
957 * @return Last part of the engine.
959 inline Vehicle
*GetLastEnginePart()
962 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
967 * Get the next real (non-articulated part) vehicle in the consist.
968 * @return Next vehicle in the consist.
970 inline Vehicle
*GetNextVehicle() const
972 const Vehicle
*v
= this;
973 while (v
->HasArticulatedPart()) v
= v
->GetNextArticulatedPart();
975 /* v now contains the last articulated part in the engine */
980 * Get the previous real (non-articulated part) vehicle in the consist.
981 * @return Previous vehicle in the consist.
983 inline Vehicle
*GetPrevVehicle() const
985 Vehicle
*v
= this->Previous();
986 while (v
!= NULL
&& v
->IsArticulatedPart()) v
= v
->Previous();
991 bool IsDrawn() const;
995 * Iterate over all vehicles from a given point.
996 * @param var The variable used to iterate over.
997 * @param start The vehicle to start the iteration at.
999 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
1002 * Iterate over all vehicles.
1003 * @param var The variable used to iterate over.
1005 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
1008 * Class defining several overloaded accessors so we don't
1009 * have to cast vehicle types that often
1011 template <class T
, VehicleType Type
>
1012 struct SpecializedVehicle
: public Vehicle
{
1013 static const VehicleType EXPECTED_TYPE
= Type
; ///< Specialized type
1015 typedef SpecializedVehicle
<T
, Type
> SpecializedVehicleBase
; ///< Our type
1018 * Set vehicle type correctly
1020 inline SpecializedVehicle
<T
, Type
>() : Vehicle(Type
)
1022 this->sprite_seq
.count
= 1;
1026 * Get the first vehicle in the chain
1027 * @return first vehicle in the chain
1029 inline T
*First() const { return (T
*)this->Vehicle::First(); }
1032 * Get the last vehicle in the chain
1033 * @return last vehicle in the chain
1035 inline T
*Last() { return (T
*)this->Vehicle::Last(); }
1038 * Get the last vehicle in the chain
1039 * @return last vehicle in the chain
1041 inline const T
*Last() const { return (const T
*)this->Vehicle::Last(); }
1044 * Get next vehicle in the chain
1045 * @return next vehicle in the chain
1047 inline T
*Next() const { return (T
*)this->Vehicle::Next(); }
1050 * Get previous vehicle in the chain
1051 * @return previous vehicle in the chain
1053 inline T
*Previous() const { return (T
*)this->Vehicle::Previous(); }
1056 * Get the next part of an articulated engine.
1057 * @return Next part of the articulated engine.
1058 * @pre The vehicle is an articulated engine.
1060 inline T
*GetNextArticulatedPart() { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1063 * Get the next part of an articulated engine.
1064 * @return Next part of the articulated engine.
1065 * @pre The vehicle is an articulated engine.
1067 inline T
*GetNextArticulatedPart() const { return (T
*)this->Vehicle::GetNextArticulatedPart(); }
1070 * Get the first part of an articulated engine.
1071 * @return First part of the engine.
1073 inline T
*GetFirstEnginePart() { return (T
*)this->Vehicle::GetFirstEnginePart(); }
1076 * Get the first part of an articulated engine.
1077 * @return First part of the engine.
1079 inline const T
*GetFirstEnginePart() const { return (const T
*)this->Vehicle::GetFirstEnginePart(); }
1082 * Get the last part of an articulated engine.
1083 * @return Last part of the engine.
1085 inline T
*GetLastEnginePart() { return (T
*)this->Vehicle::GetLastEnginePart(); }
1088 * Get the next real (non-articulated part) vehicle in the consist.
1089 * @return Next vehicle in the consist.
1091 inline T
*GetNextVehicle() const { return (T
*)this->Vehicle::GetNextVehicle(); }
1094 * Get the previous real (non-articulated part) vehicle in the consist.
1095 * @return Previous vehicle in the consist.
1097 inline T
*GetPrevVehicle() const { return (T
*)this->Vehicle::GetPrevVehicle(); }
1100 * Tests whether given index is a valid index for vehicle of this type
1101 * @param index tested index
1102 * @return is this index valid index of T?
1104 static inline bool IsValidID(size_t index
)
1106 return Vehicle::IsValidID(index
) && Vehicle::Get(index
)->type
== Type
;
1110 * Gets vehicle with given index
1111 * @return pointer to vehicle with given index casted to T *
1113 static inline T
*Get(size_t index
)
1115 return (T
*)Vehicle::Get(index
);
1119 * Returns vehicle if the index is a valid index for this vehicle type
1120 * @return pointer to vehicle with given index if it's a vehicle of this type
1122 static inline T
*GetIfValid(size_t index
)
1124 return IsValidID(index
) ? Get(index
) : NULL
;
1128 * Converts a Vehicle to SpecializedVehicle with type checking.
1129 * @param v Vehicle pointer
1130 * @return pointer to SpecializedVehicle
1132 static inline T
*From(Vehicle
*v
)
1134 assert(v
->type
== Type
);
1139 * Converts a const Vehicle to const SpecializedVehicle with type checking.
1140 * @param v Vehicle pointer
1141 * @return pointer to SpecializedVehicle
1143 static inline const T
*From(const Vehicle
*v
)
1145 assert(v
->type
== Type
);
1146 return (const T
*)v
;
1150 * Update vehicle sprite- and position caches
1151 * @param force_update Force updating the vehicle on the viewport.
1152 * @param update_delta Also update the delta?
1154 inline void UpdateViewport(bool force_update
, bool update_delta
)
1156 /* Skip updating sprites on dedicated servers without screen */
1157 if (_network_dedicated
) return;
1159 /* Explicitly choose method to call to prevent vtable dereference -
1160 * it gives ~3% runtime improvements in games with many vehicles */
1161 if (update_delta
) ((T
*)this)->T::UpdateDeltaXY(this->direction
);
1162 VehicleSpriteSeq seq
;
1163 ((T
*)this)->T::GetImage(this->direction
, EIT_ON_MAP
, &seq
);
1164 if (force_update
|| this->sprite_seq
!= seq
) {
1165 this->sprite_seq
= seq
;
1166 this->Vehicle::UpdateViewport(true);
1172 * Iterate over all vehicles of a particular type.
1173 * @param name The type of vehicle to iterate over.
1174 * @param var The variable used to iterate over.
1176 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) \
1177 for (size_t vehicle_index = 0; var = NULL, vehicle_index < name::GetPoolSize(); vehicle_index++) \
1178 if ((var = name::GetIfValid(vehicle_index)) != NULL)
1180 /** Generates sequence of free UnitID numbers */
1181 struct FreeUnitIDGenerator
{
1182 bool *cache
; ///< array of occupied unit id numbers
1183 UnitID maxid
; ///< maximum ID at the moment of constructor call
1184 UnitID curid
; ///< last ID returned; 0 if none
1186 FreeUnitIDGenerator(VehicleType type
, CompanyID owner
);
1189 /** Releases allocated memory */
1190 ~FreeUnitIDGenerator() { free(this->cache
); }
1193 /** Sentinel for an invalid coordinate. */
1194 static const int32 INVALID_COORD
= 0x7fffffff;
1196 #endif /* VEHICLE_BASE_H */