vehicle_base.h

Go to the documentation of this file.
00001 /* $Id: vehicle_base.h 21843 2011-01-18 21:58:22Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #ifndef VEHICLE_BASE_H
00013 #define VEHICLE_BASE_H
00014 
00015 #include "track_type.h"
00016 #include "direction_type.h"
00017 #include "command_type.h"
00018 #include "order_base.h"
00019 #include "cargopacket.h"
00020 #include "texteff.hpp"
00021 #include "engine_type.h"
00022 #include "order_func.h"
00023 #include "transport_type.h"
00024 #include "group_type.h"
00025 
00027 enum VehStatus {
00028   VS_HIDDEN          = 0x01, 
00029   VS_STOPPED         = 0x02, 
00030   VS_UNCLICKABLE     = 0x04, 
00031   VS_DEFPAL          = 0x08, 
00032   VS_TRAIN_SLOWING   = 0x10, 
00033   VS_SHADOW          = 0x20, 
00034   VS_AIRCRAFT_BROKEN = 0x40, 
00035   VS_CRASHED         = 0x80, 
00036 };
00037 
00039 enum VehicleFlags {
00040   VF_LOADING_FINISHED,        
00041   VF_CARGO_UNLOADING,         
00042   VF_BUILT_AS_PROTOTYPE,      
00043   VF_TIMETABLE_STARTED,       
00044   VF_AUTOFILL_TIMETABLE,      
00045   VF_AUTOFILL_PRES_WAIT_TIME, 
00046   VF_STOP_LOADING,            
00047   VF_PATHFINDER_LOST,         
00048 };
00049 
00051 enum NewGRFCacheValidValues {
00052   NCVV_POSITION_CONSIST_LENGTH   = 0, 
00053   NCVV_POSITION_SAME_ID_LENGTH   = 1, 
00054   NCVV_CONSIST_CARGO_INFORMATION = 2, 
00055   NCVV_COMPANY_INFORMATION       = 3, 
00056   NCVV_END,                           
00057 };
00058 
00060 struct NewGRFCache {
00061   /* Values calculated when they are requested for the first time after invalidating the NewGRF cache. */
00062   uint32 position_consist_length;   
00063   uint32 position_same_id_length;   
00064   uint32 consist_cargo_information; 
00065   uint32 company_information;       
00066   uint8  cache_valid;               
00067 };
00068 
00070 enum VisualEffect {
00071   VE_OFFSET_START        = 0, 
00072   VE_OFFSET_COUNT        = 4, 
00073   VE_OFFSET_CENTRE       = 8, 
00074 
00075   VE_TYPE_START          = 4, 
00076   VE_TYPE_COUNT          = 2, 
00077   VE_TYPE_DEFAULT        = 0, 
00078   VE_TYPE_STEAM          = 1, 
00079   VE_TYPE_DIESEL         = 2, 
00080   VE_TYPE_ELECTRIC       = 3, 
00081 
00082   VE_DISABLE_EFFECT      = 6, 
00083   VE_DISABLE_WAGON_POWER = 7, 
00084 
00085   VE_DEFAULT = 0xFF,          
00086 };
00087 
00089 struct VehicleCache {
00090   uint16 cached_max_speed; 
00091 
00092   byte cached_vis_effect;  
00093 };
00094 
00096 typedef Pool<Vehicle, VehicleID, 512, 0xFF000> VehiclePool;
00097 extern VehiclePool _vehicle_pool;
00098 
00099 /* Some declarations of functions, so we can make them friendly */
00100 struct SaveLoad;
00101 struct GroundVehicleCache;
00102 extern const SaveLoad *GetVehicleDescription(VehicleType vt);
00103 struct LoadgameState;
00104 extern bool LoadOldVehicle(LoadgameState *ls, int num);
00105 extern bool AfterLoadGame();
00106 extern void FixOldVehicles();
00107 
00109 struct Vehicle : VehiclePool::PoolItem<&_vehicle_pool>, BaseVehicle {
00110 private:
00111   Vehicle *next;                      
00112   Vehicle *previous;                  
00113   Vehicle *first;                     
00114 
00115   Vehicle *next_shared;               
00116   Vehicle *previous_shared;           
00117 public:
00118   friend const SaveLoad *GetVehicleDescription(VehicleType vt); 
00119   friend bool AfterLoadGame();
00120   friend void FixOldVehicles();
00121   friend void AfterLoadVehicles(bool part_of_load);             
00122   friend bool LoadOldVehicle(LoadgameState *ls, int num);       
00123 
00124   char *name;                         
00125 
00126   TileIndex tile;                     
00127 
00133   TileIndex dest_tile;
00134 
00135   Money profit_this_year;             
00136   Money profit_last_year;             
00137   Money value;                        
00138 
00139   CargoPayment *cargo_payment;        
00140 
00141   /* Used for timetabling. */
00142   uint32 current_order_time;          
00143   int32 lateness_counter;             
00144   Date timetable_start;               
00145 
00146   /* Boundaries for the current position in the world and a next hash link.
00147    * NOSAVE: All of those can be updated with VehiclePositionChanged() */
00148   Rect coord;
00149   Vehicle *next_hash, **prev_hash;
00150   Vehicle *next_new_hash, **prev_new_hash;
00151   Vehicle **old_new_hash;
00152 
00153   SpriteID colourmap;                 
00154 
00155   /* Related to age and service time */
00156   Year build_year;
00157   Date age;                           
00158   Date max_age;                       
00159   Date date_of_last_service;
00160   Date service_interval;
00161   uint16 reliability;                 
00162   uint16 reliability_spd_dec;         
00163   byte breakdown_ctr;                 
00164   byte breakdown_delay;               
00165   byte breakdowns_since_last_service;
00166   byte breakdown_chance;
00167 
00168   int32 x_pos;                        
00169   int32 y_pos;                        
00170   byte z_pos;                         
00171   DirectionByte direction;            
00172 
00173   OwnerByte owner;                    
00174   byte spritenum;                     
00175 
00176 
00177   SpriteID cur_image;                 
00178   byte x_extent;                      
00179   byte y_extent;                      
00180   byte z_extent;                      
00181   int8 x_offs;                        
00182   int8 y_offs;                        
00183   EngineID engine_type;
00184 
00185   TextEffectID fill_percent_te_id;    
00186   UnitID unitnumber;                  
00187 
00188   uint16 cur_speed;                   
00189   byte subspeed;                      
00190   byte acceleration;                  
00191   uint32 motion_counter;
00192   byte progress;
00193 
00194   /* for randomized variational spritegroups
00195    * bitmask used to resolve them; parts of it get reseeded when triggers
00196    * of corresponding spritegroups get matched */
00197   byte random_bits;
00198   byte waiting_triggers;              
00199 
00200   StationID last_station_visited;
00201 
00202   CargoID cargo_type;                 
00203   byte cargo_subtype;                 
00204   uint16 cargo_cap;                   
00205   VehicleCargoList cargo;             
00206 
00207   byte day_counter;                   
00208   byte tick_counter;                  
00209   byte running_ticks;                 
00210 
00211   byte vehstatus;                     
00212   Order current_order;                
00213   VehicleOrderID cur_order_index;     
00214 
00215   union {
00216     OrderList *list;            
00217     Order     *old;             
00218   } orders;
00219 
00220   byte vehicle_flags;                 
00221 
00223   uint16 load_unload_ticks;
00224 
00225   GroupID group_id;                   
00226 
00227   byte subtype;                       
00228 
00229   NewGRFCache grf_cache;              
00230   VehicleCache vcache;                
00231 
00232   Vehicle(VehicleType type = VEH_INVALID);
00233 
00234   void PreDestructor();
00236   virtual ~Vehicle();
00237 
00238   void BeginLoading();
00239   void LeaveStation();
00240 
00241   GroundVehicleCache *GetGroundVehicleCache();
00242   const GroundVehicleCache *GetGroundVehicleCache() const;
00243 
00244   void DeleteUnreachedAutoOrders();
00245 
00246   void HandleLoading(bool mode = false);
00247 
00252   virtual const char *GetTypeString() const { return "base vehicle"; }
00253 
00262   virtual void MarkDirty() {}
00263 
00269   virtual void UpdateDeltaXY(Direction direction) {}
00270 
00284   FORCEINLINE uint GetOldAdvanceSpeed(uint speed)
00285   {
00286     return (this->direction & 1) ? speed : speed * 3 / 4;
00287   }
00288 
00301   static FORCEINLINE uint GetAdvanceSpeed(uint speed)
00302   {
00303     return speed * 3 / 4;
00304   }
00305 
00313   FORCEINLINE uint GetAdvanceDistance()
00314   {
00315     return (this->direction & 1) ? 192 : 256;
00316   }
00317 
00322   virtual ExpensesType GetExpenseType(bool income) const { return EXPENSES_OTHER; }
00323 
00327   virtual void PlayLeaveStationSound() const {}
00328 
00332   virtual bool IsPrimaryVehicle() const { return false; }
00333 
00339   virtual SpriteID GetImage(Direction direction) const { return 0; }
00340 
00345   FORCEINLINE void InvalidateNewGRFCache()
00346   {
00347     this->grf_cache.cache_valid = 0;
00348   }
00349 
00354   FORCEINLINE void InvalidateNewGRFCacheOfChain()
00355   {
00356     for (Vehicle *u = this; u != NULL; u = u->Next()) {
00357       u->InvalidateNewGRFCache();
00358     }
00359   }
00360 
00365   FORCEINLINE bool IsGroundVehicle() const
00366   {
00367     return this->type == VEH_TRAIN || this->type == VEH_ROAD;
00368   }
00369 
00374   virtual int GetDisplaySpeed() const { return 0; }
00375 
00380   virtual int GetDisplayMaxSpeed() const { return 0; }
00381 
00386   virtual Money GetRunningCost() const { return 0; }
00387 
00392   virtual bool IsInDepot() const { return false; }
00393 
00398   virtual bool IsStoppedInDepot() const { return this->IsInDepot() && (this->vehstatus & VS_STOPPED) != 0; }
00399 
00404   virtual bool Tick() { return true; };
00405 
00409   virtual void OnNewDay() {};
00410 
00416   virtual uint Crash(bool flooded = false);
00417 
00430   virtual Trackdir GetVehicleTrackdir() const { return INVALID_TRACKDIR; }
00431 
00436   Money GetDisplayRunningCost() const { return (this->GetRunningCost() >> 8); }
00437 
00442   Money GetDisplayProfitThisYear() const { return (this->profit_this_year >> 8); }
00443 
00448   Money GetDisplayProfitLastYear() const { return (this->profit_last_year >> 8); }
00449 
00450   void SetNext(Vehicle *next);
00451 
00457   inline Vehicle *Next() const { return this->next; }
00458 
00464   inline Vehicle *Previous() const { return this->previous; }
00465 
00470   inline Vehicle *First() const { return this->first; }
00471 
00476   inline Vehicle *Last()
00477   {
00478     Vehicle *v = this;
00479     while (v->Next() != NULL) v = v->Next();
00480     return v;
00481   }
00482 
00487   inline const Vehicle *Last() const
00488   {
00489     const Vehicle *v = this;
00490     while (v->Next() != NULL) v = v->Next();
00491     return v;
00492   }
00493 
00498   inline Order *GetFirstOrder() const { return (this->orders.list == NULL) ? NULL : this->orders.list->GetFirstOrder(); }
00499 
00500   void AddToShared(Vehicle *shared_chain);
00501   void RemoveFromShared();
00502 
00507   inline Vehicle *NextShared() const { return this->next_shared; }
00508 
00513   inline Vehicle *PreviousShared() const { return this->previous_shared; }
00514 
00519   inline Vehicle *FirstShared() const { return (this->orders.list == NULL) ? this->First() : this->orders.list->GetFirstSharedVehicle(); }
00520 
00525   inline bool IsOrderListShared() const { return this->orders.list != NULL && this->orders.list->IsShared(); }
00526 
00531   inline VehicleOrderID GetNumOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumOrders(); }
00532 
00537   inline VehicleOrderID GetNumManualOrders() const { return (this->orders.list == NULL) ? 0 : this->orders.list->GetNumManualOrders(); }
00538 
00545   inline void CopyVehicleConfigAndStatistics(const Vehicle *src)
00546   {
00547     this->unitnumber = src->unitnumber;
00548 
00549     this->cur_order_index = src->cur_order_index;
00550     this->current_order = src->current_order;
00551     this->dest_tile  = src->dest_tile;
00552 
00553     this->profit_this_year = src->profit_this_year;
00554     this->profit_last_year = src->profit_last_year;
00555 
00556     this->current_order_time = src->current_order_time;
00557     this->lateness_counter = src->lateness_counter;
00558     this->timetable_start = src->timetable_start;
00559 
00560     if (HasBit(src->vehicle_flags, VF_TIMETABLE_STARTED)) SetBit(this->vehicle_flags, VF_TIMETABLE_STARTED);
00561     if (HasBit(src->vehicle_flags, VF_AUTOFILL_TIMETABLE)) SetBit(this->vehicle_flags, VF_AUTOFILL_TIMETABLE);
00562     if (HasBit(src->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME)) SetBit(this->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
00563 
00564     this->service_interval = src->service_interval;
00565   }
00566 
00567 
00568   bool HandleBreakdown();
00569 
00570   bool NeedsAutorenewing(const Company *c) const;
00571 
00572   bool NeedsServicing() const;
00573   bool NeedsAutomaticServicing() const;
00574 
00582   virtual TileIndex GetOrderStationLocation(StationID station) { return INVALID_TILE; }
00583 
00592   virtual bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) { return false; }
00593 
00594   CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command);
00595 
00596   void UpdateVisualEffect(bool allow_power_change = true);
00597   void ShowVisualEffect() const;
00598 
00603   void IncrementOrderIndex()
00604   {
00605     this->cur_order_index++;
00606     if (this->cur_order_index >= this->GetNumOrders()) this->cur_order_index = 0;
00607     InvalidateVehicleOrder(this, 0);
00608   }
00609 
00615   inline Order *GetOrder(int index) const
00616   {
00617     return (this->orders.list == NULL) ? NULL : this->orders.list->GetOrderAt(index);
00618   }
00619 
00620   Order *GetNextManualOrder(int index) const;
00621 
00626   inline Order *GetLastOrder() const
00627   {
00628     return (this->orders.list == NULL) ? NULL : this->orders.list->GetLastOrder();
00629   }
00630 
00631   bool IsEngineCountable() const;
00632   bool HasDepotOrder() const;
00633   void HandlePathfindingResult(bool path_found);
00634 };
00635 
00636 #define FOR_ALL_VEHICLES_FROM(var, start) FOR_ALL_ITEMS_FROM(Vehicle, vehicle_index, var, start)
00637 #define FOR_ALL_VEHICLES(var) FOR_ALL_VEHICLES_FROM(var, 0)
00638 
00643 template <class T, VehicleType Type>
00644 struct SpecializedVehicle : public Vehicle {
00645   static const VehicleType EXPECTED_TYPE = Type; 
00646 
00650   FORCEINLINE SpecializedVehicle<T, Type>() : Vehicle(Type) { }
00651 
00656   FORCEINLINE T *First() const { return (T *)this->Vehicle::First(); }
00657 
00662   FORCEINLINE T *Last() { return (T *)this->Vehicle::Last(); }
00663 
00668   FORCEINLINE const T *Last() const { return (const T *)this->Vehicle::Last(); }
00669 
00674   FORCEINLINE T *Next() const { return (T *)this->Vehicle::Next(); }
00675 
00680   FORCEINLINE T *Previous() const { return (T *)this->Vehicle::Previous(); }
00681 
00682 
00688   static FORCEINLINE bool IsValidID(size_t index)
00689   {
00690     return Vehicle::IsValidID(index) && Vehicle::Get(index)->type == Type;
00691   }
00692 
00697   static FORCEINLINE T *Get(size_t index)
00698   {
00699     return (T *)Vehicle::Get(index);
00700   }
00701 
00706   static FORCEINLINE T *GetIfValid(size_t index)
00707   {
00708     return IsValidID(index) ? Get(index) : NULL;
00709   }
00710 
00716   static FORCEINLINE T *From(Vehicle *v)
00717   {
00718     assert(v->type == Type);
00719     return (T *)v;
00720   }
00721 
00727   static FORCEINLINE const T *From(const Vehicle *v)
00728   {
00729     assert(v->type == Type);
00730     return (const T *)v;
00731   }
00732 
00738   FORCEINLINE void UpdateViewport(bool moved, bool turned)
00739   {
00740     extern void VehicleMove(Vehicle *v, bool update_viewport);
00741 
00742     /* Explicitly choose method to call to prevent vtable dereference -
00743      * it gives ~3% runtime improvements in games with many vehicles */
00744     if (turned) ((T *)this)->T::UpdateDeltaXY(this->direction);
00745     SpriteID old_image = this->cur_image;
00746     this->cur_image = ((T *)this)->T::GetImage(this->direction);
00747     if (moved || this->cur_image != old_image) VehicleMove(this, true);
00748   }
00749 };
00750 
00751 #define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
00752 
00756 struct DisasterVehicle : public SpecializedVehicle<DisasterVehicle, VEH_DISASTER> {
00757   uint16 image_override;
00758   VehicleID big_ufo_destroyer_target;
00759 
00761   DisasterVehicle() : SpecializedVehicle<DisasterVehicle, VEH_DISASTER>() {}
00763   virtual ~DisasterVehicle() {}
00764 
00765   const char *GetTypeString() const { return "disaster vehicle"; }
00766   void UpdateDeltaXY(Direction direction);
00767   bool Tick();
00768 };
00769 
00770 #define FOR_ALL_DISASTERVEHICLES(var) FOR_ALL_VEHICLES_OF_TYPE(DisasterVehicle, var)
00771 
00773 struct FreeUnitIDGenerator {
00774   bool *cache;  
00775   UnitID maxid; 
00776   UnitID curid; 
00777 
00778   FreeUnitIDGenerator(VehicleType type, CompanyID owner);
00779   UnitID NextID();
00780 
00782   ~FreeUnitIDGenerator() { free(this->cache); }
00783 };
00784 
00785 static const int32 INVALID_COORD = 0x7fffffff;
00786 
00787 #endif /* VEHICLE_BASE_H */

Generated on Thu Jan 20 22:57:43 2011 for OpenTTD by  doxygen 1.6.1